akim akim - 1 year ago 56
Python Question

Indentation preserving formatting of multiline strings

I generate bits of (C++) code using format strings such as

memfn_declaration = '''\
{static}auto {fun}({formals}){const}
-> {result};

Format strings are nice for this, but is there a way to make them keep the indentation level for
here? It's typically multiline.

I know I can just indent the string corresponding to
by two spaces, I know there are plenty of functions to this end, but that's not what I'm asking: I'm looking for something that would work without tweaking the strings I pass.

Answer Source

Now that you've posted your own answer and clarified at little more about what you want. I think it would be slightly better to implement it by defining your own str subclass that extends the way strings can be formatted by supporting a new conversion type, 'i', which must be followed by a decimal number representing the level of indentation desired.

Here's an implementation that works in both Python 2 & 3:

import re
from textwrap import dedent
    from textwrap import indent
except ImportError:
    def indent(s, prefix):
        return prefix + prefix.join(s.splitlines(True))

class Indentable(str):
    indent_format_spec = re.compile(r'''i([0-9]+)''')

    def __format__(self, format_spec):
        matches = self.indent_format_spec.search(format_spec)
        if matches:
            level = int(matches.group(1))
            first, sep, text = dedent(self).strip().partition('\n')
            return first + sep + indent(text, ' ' * level)

        return super(Indentable, self).__format__(format_spec)

sample_format_string = '''\
  {static}auto {fun}({formals}){const}
    -> {result};

specs = {
    'doc': Indentable('''
        // Convert a string to a float.
        // Quite obsolete.
        // Use something better instead.
    'static': '',
    'fun': 'atof',
    'formals': 'const char*',
    'const': '',
    'result': 'float',



  // Convert a string to a float.
  // Quite obsolete.
  // Use something better instead.
  auto atof(const char*)
    -> float;