python - Indentation preserving formatting of multiline strings -
i generate bits of (c++) code using format strings such as
memfn_declaration = '''\ {doc} {static}auto {fun}({formals}){const} -> {result}; ''' format strings nice this, there way make them keep indentation level {doc} here? it's typically multiline.
i know can indent string corresponding doc 2 spaces, know there plenty of functions end, that's not i'm asking: i'm looking work without tweaking strings pass.
now you've posted own answer , clarified @ little more want. think better implement defining own str subclass extends way strings can formatted supporting new conversion type, 'i', must followed decimal number representing level of indentation desired.
here's implementation works in both python 2 & 3:
import re textwrap import dedent try: 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 = '''\ {doc:i2} {static}auto {fun}({formals}){const} -> {result}; ''' specs = { 'doc': indentable(''' // convert string float. // quite obsolete. // use better instead. '''), 'static': '', 'fun': 'atof', 'formals': 'const char*', 'const': '', 'result': 'float', } print(sample_format_string.format(**specs)) output:
// convert string float. // quite obsolete. // use better instead. auto atof(const char*) -> float;
Comments
Post a Comment