Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #51657

Re: Script that converts between indentation and curly braces in Python code

References <09DBD544-FA04-48DC-8FEA-1E788FE1C6A6@gmail.com> <CAAM7w92xAY1z5yVrv6cdL-cAHHFeg8mW+fSAPKsH9u5QHM842w@mail.gmail.com>
Date 2013-07-31 14:55 +0100
Subject Re: Script that converts between indentation and curly braces in Python code
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.26.1375278953.1251.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Jul 31, 2013 at 1:39 PM, Beth McNany <beth.mcnany@gmail.com> wrote:
> ok, ok, if you *really* want it, you could keep track of how many leading
> spaces there are (you are using spaces, right?), and insert an open bracket
> where that number increases and a closing bracket where it decreases.  Of
> course, as with all parsing problems, this is oversimplification... if you
> have multi-line statements you'll need to check for those (if line starts
> with """ or ''', ends with \, or if there's an unclosed bracket or paren...)
> - but that'd be a reasonable place to start if you're only doing short code
> snippets.
>

Since the braced version won't run anyway, how about a translation like this:

def foo():
    print("""Hello,
world!""")
    for i in range(5):
        foo()
    return 42

-->

0-def foo():
4-print("""Hello,
0-world!""")
4-for i in range(5):
8-foo()
4-return 42

That's a simple translation that guarantees safe round-tripping, and
you can probably do it with a one-liner fwiw... let's see...

# Assumes spaces OR tabs but not both
# Can't see an easy way to count leading spaces other than:
# len(s)-len(s.lstrip())
code = '\n'.join("%d-%s"%(len(s)-len(s.lstrip()),s.lstrip()) for s in
code.split('\n'))

# Recreates with spaces, choose tabs for the multiplication if you prefer
code = '\n'.join(' '*int(s.split('-',1)[0])+s.split('-',1)[1] for s in
code.split('\n'))

These would be better done in a couple of lines, but I like doing
one-liners just for fun. :)

ChrisA

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: Script that converts between indentation and curly braces in Python code Chris Angelico <rosuav@gmail.com> - 2013-07-31 14:55 +0100
  Re: Script that converts between indentation and curly braces in Python code Rotwang <sg552@hotmail.co.uk> - 2013-07-31 15:07 +0100
    Re: Script that converts between indentation and curly braces in Python code Chris Angelico <rosuav@gmail.com> - 2013-07-31 15:23 +0100

csiph-web