On Wed, Jul 31, 2013 at 1:39 PM, Beth McNany <beth.mcn...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to