Source formatting for long expressions.

Christopher Armstrong radix at
Mon Jun 10 02:16:00 CEST 2002

>>>>> "ca" == Christopher Armstrong <radix at> writes:

>>>>> "mvl" == Martin v Loewis <martin at> writes:

    mvl> As you can see, it tries to align further arguments to a function
    mvl> together with the opening parenthesis. I would assume that any other
    mvl> auto-formatters use the same style, so you won't get any "sane"
    mvl> indentation until you drop the nesting level (perhaps in favour of
    mvl> method invocations).

    ca> I'm probably going to end up doing this myself, and I thought of
    ca> something while reading your message. I could have two steps for
    ca> formatting: template- generation and indentation. the first step would
    ca> generate something like a repr() of all of my objects, but with \ns and
    ca> \ts embedded at strategic locations. Then I could replace all \ts with
    ca> current_indent_level, calculating current_indent_level by counting (s,
    ca> {s, and [s. I'm going to try this out now.  :-)

I got this working. It was fairly easy, once I got a templated source 

def indentify(s):
    out = []
    stack = []
    for ch in s:
        if ch in ['[', '(', '{']:
        elif ch in [']', ')', '}']:
        if ch == '\t':
            out.append('  '*len(stack))
    return string.join(out, '')

This is a fairly stupid indenter, but it works for my needs::

>>> print aot.indentify("Instance('', \
\n\tfoo=bar, \n\tbaz={\n\t'quux': 1, \n\t'spam': \n\tInstance('Eggs', \
\n\tmore='state')})") #this source will really be generated by my __repr__s.
    'quux': 1, 

                                Chris Armstrong
                         << radix at >>

More information about the Python-list mailing list