Refactor Template.parse()

Split out Template.parse() as a separate function. This saves an expensive
method call to self.functions() for every potential intrinsic function in
the template, plus makes a template parsing routine available to other
parts of the code that may want to use it, without being tied to a
Template's ideas of what the intrinsic functions available are.

Change-Id: I1d4b847967357dbe5c9960223a063377aec50e5d
This commit is contained in:
Zane Bitter 2014-03-11 16:43:39 -04:00
parent 20c5274dfe
commit 1c499bc2ad
1 changed files with 17 additions and 13 deletions

View File

@ -163,17 +163,21 @@ class Template(collections.Mapping):
return self._functionmaps[self.version]
def parse(self, stack, snippet):
parse = functools.partial(self.parse, stack)
return parse(self.functions(), stack, snippet)
if isinstance(snippet, collections.Mapping):
if len(snippet) == 1:
fn_name, args = next(snippet.iteritems())
Func = self.functions().get(fn_name)
if Func is not None:
return Func(stack, fn_name, parse(args))
return dict((k, parse(v)) for k, v in snippet.iteritems())
elif (not isinstance(snippet, basestring) and
isinstance(snippet, collections.Iterable)):
return [parse(v) for v in snippet]
else:
return snippet
def parse(functions, stack, snippet):
recurse = functools.partial(parse, functions, stack)
if isinstance(snippet, collections.Mapping):
if len(snippet) == 1:
fn_name, args = next(snippet.iteritems())
Func = functions.get(fn_name)
if Func is not None:
return Func(stack, fn_name, recurse(args))
return dict((k, recurse(v)) for k, v in snippet.iteritems())
elif (not isinstance(snippet, basestring) and
isinstance(snippet, collections.Iterable)):
return [recurse(v) for v in snippet]
else:
return snippet