Source formatting for long expressions.

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


>>>>> "ca" == Christopher Armstrong <radix at twistedmatrix.com> writes:

>>>>> "mvl" == Martin v Loewis <martin at v.loewis.de> 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).

[snip..]
    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 
representation::

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


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

>>> print aot.indentify("Instance('twisted.internet.app.Application', \
\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.
Instance('twisted.internet.app.Application', 
  foo=bar, 
  baz={
    'quux': 1, 
    'spam': 
    Instance('Eggs', 
      more='state')})


-- 
                                Chris Armstrong
                         << radix at twistedmatrix.com >>
                http://twistedmatrix.com/users/carmstro.twistd/






More information about the Python-list mailing list