3

In a use case for autogenerating code from a Mako template, I'd like to have a nice syntax to remove leading whitespace (similar to removing newlines with \ at the end of a line).

The following code

from mako.template import Template

# 1) Bad
print(Template(r'''
    void myfunction(\
    %for arg_name, arg_type in arguments:
        ${', ' if loop.index else ''}${arg_type} ${arg_name}\
    %endfor
    )
''').render(arguments=[('string', 'a'), ('int', 'b')]))

# 2) Good but ugly
print(Template(r'''
    void myfunction(\
    %for arg_name, arg_type in arguments:
<%    %>${', ' if loop.index else ''}${arg_type} ${arg_name}\
    %endfor
<%%>)
''').render(arguments=[('string', 'a'), ('int', 'b')]))

will print these results:

void myfunction(        a string        , b int    )
void myfunction(a string, b int)

I want the latter output — so is there a nicer syntax while still keeping my Mako template nicely indented? My solution with an empty <% %> isn't exactly beautiful.

jxramos
  • 7,356
  • 6
  • 57
  • 105
AndiDog
  • 68,631
  • 21
  • 159
  • 205

1 Answers1

0

There are a lot of subjective words in this question like beautiful and nice, and nicer. But I'll give it a try. Let me know if any of these fit the bill for you.

Note that both of the following do what you ask, but option #1 may be the easiest to read, but it also removes all the white space before the void, which may not be intended. Option #2 should work well for what you describe.

With option #2 below you can substitute whatever character you like best to denote all of the following white space should be deleted.

import re

# 1) Better?
print(Template(r'''
    void myfunction(\
    %for arg_name, arg_type in arguments:
        ${', ' if loop.index else ''}${arg_type} ${arg_name}\
    %endfor
    )
'''.replace('  ', '')).render(arguments=[('string', 'a'), ('int', 'b')]))

# 2) More Better?
print(Template(re.sub(r'>\s*', '', r'''
    void myfunction(\
    %for arg_name, arg_type in arguments:
>       ${', ' if loop.index else ''}${arg_type} ${arg_name}\
    %endfor
>   )
''')).render(arguments=[('string', 'a'), ('int', 'b')]))
jxramos
  • 7,356
  • 6
  • 57
  • 105