I generate bits of (C++) code using format strings such as
memfn_declaration = '''\
{doc}
{static}auto {fun}({formals}){const}
-> {result};
'''
{doc}
doc
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
try:
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 = '''\
{doc:i2}
{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',
}
print(sample_format_string.format(**specs))
Output:
// Convert a string to a float.
// Quite obsolete.
// Use something better instead.
auto atof(const char*)
-> float;