Consider using a template engine such as Jinja2 with Python.
You may wish to change the syntax from the default {%, {{, etc. in order to make it more compatible with LaTeX's own. For example:
env = jinja2.Environment(
loader=jinja2.FileSystemLoader( JINJA_DIRS ),
comment_start_string='["', # don't conflict with e.g. {#1
comment_end_string = '"]',
block_start_string = '[%',
block_end_string = '%]',
variable_start_string = '[=',
variable_end_string = ']',
autoescape=True,
finalize=_jinja2_finalize_callback, # make a function that escapes TeX
)
template = env.get_template( self.template )
tex = template.render( content )
In addition to functions that are passed to the template's environment, Jinja2 supports macros. For example, your above code should work as expected as:
[% macro blah(egg, spam) -%]
foo [=egg] \to [=spam] bar
[%- endmacro %]
[= blah("chicken","pork") ]
% substitutes with "foo chicken \to pork"
I'm not sure what your goals are, and this requires a bit of work, but isn't an insurmountable problem at all if you're familiar with Python.
I hope that helps.