its a little odd to tell exactly who/when knows what in this scenario. It seems like there is some concept of templates coming from somewhere with variables declared in them, and some other code needs to call upon these templates, and needs to "know" what variables will be called.
That is, i need something to happen in response to a variable being present in a template.
Usually, when I have to do this kind of thing it's with Python string templates, but same idea, I use an object with __getattr__ or __getitem__ on it.
That is, template:
variable one: ${namespace.FOO}
variable two: ${namespace.BAR}
usage:
class MyNamespace(object):
def __getattr__(self, key):
print "namespace attribute %s called" % key
return "HELLO!"
template.render(namespace=MyNamespace())
This is kind of an entirely different approach to what you're looking for, but is very simple and performant.
Otherwise, you truly need to know the names before anything is rendered, yes you'd have to dig into Lexer, lex the template, get the parsetree back, walk through it and look for undeclared_identifiers() stuck on nodes. Take a look at lexer.py and parsetree.py to see how that works, a quick lex looks like:
from mako.lexer import Lexer
parsetree = Lexer("some template").parse()
def find_undeclared(node):
stack = [node]
while stack:
node = stack.pop(0)
stack.extend(node.get_children())
if hasattr(node, "undeclared_identifiers"):
for ident in node.undeclared_identifiers():
yield ident