Skip to content
Myr

there is now a workaround in the compiler that makes sure it's possible to call things with python keywords. {{ foo(class=42) }} works again

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent de6bf71 · Browse files · 7 files+269 added−116 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+269 added−116 removed

  • other:+269 added−116 removed

7 files+269 added−116 removed

modified:examples/bench.py+96 added-29 removed
1"""2 This benchmark compares some python templating engines with Jinja 2 so3 that we get a picture of how fast Jinja 2 is for a semi real world4 template. If a template engine is not installed the test is skipped.5"""6import sys2from django.conf import settings3settings.configure()4from django.template import Template as DjangoTemplate, Context as DjangoContext5from jinja2 import Environment as JinjaEnvironment6from mako.template import Template as MakoTemplate7from genshi.template import MarkupTemplate as GenshiTemplate8from Cheetah.Template import Template as CheetahTemplate7from timeit import Timer8from jinja2 import Environment as JinjaEnvironment910context = {11 'page_title': 'mitsuhiko\'s benchmark',12 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]
36 unmodified lines
49 </body>50</html>\51""")5253def test_jinja():54 jinja_template.render(context)5556try:57 from django.conf import settings58 settings.configure()59 from django.template import Template as DjangoTemplate, Context as DjangoContext60except ImportError:61 test_django = None62else:54django_template = DjangoTemplate("""\63 django_template = DjangoTemplate("""\64<!doctype html>65<html>66 <head>67 <title>{{ page_title }}</title>
21 unmodified lines
89 </body>90</html>\91""")9293 def test_django():94 c = DjangoContext(context)95 c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'),96 ('products.html', 'Products')]97 django_template.render(c)9899try:100 from mako.template import Template as MakoTemplate101except ImportError:102 test_mako = None103else:84mako_template = MakoTemplate("""\104 mako_template = MakoTemplate("""\105<!doctype html>106<html>107 <head>108 <title>${page_title|h}</title>
21 unmodified lines
130 </body>131</html>\132""")133134 def test_mako():135 mako_template.render(**context)136137try:138 from genshi.template import MarkupTemplate as GenshiTemplate139except ImportError:140 test_genshi = None141else:114genshi_template = GenshiTemplate("""\142 genshi_template = GenshiTemplate("""\143<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">144 <head>145 <title>${page_title}</title>146 </head>
17 unmodified lines
164 </body>165</html>\166""")167168 def test_genshi():169 genshi_template.generate(**context).render('html', strip_whitespace=False)170171try:172 from Cheetah.Template import Template as CheetahTemplate173except ImportError:174 test_cheetah = None175else:140cheetah_template = CheetahTemplate("""\176 cheetah_template = CheetahTemplate("""\177#import cgi178<!doctype html>179<html>180 <head>
22 unmodified lines
203 </body>204</html>\205""", searchList=[dict(context)])206171def test_jinja():172 jinja_template.render(context)207 def test_cheetah():208 unicode(cheetah_template)209174def test_django():175 c = DjangoContext(context)176 c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]177 django_template.render(c)210try:211 import tenjin212except ImportError:213 test_tenjin = None214else:215 tenjin_template = tenjin.Template()216 tenjin_template.convert("""\217<!doctype html>218<html>219 <head>220 <title>${page_title}</title>221 </head>222 <body>223 <div class="header">224 <h1>${page_title}</h1>225 </div>226 <ul class="navigation">227<?py for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: ?>228 <li><a href="${href}">${caption}</a></li>229<?py #end ?>230 </ul>231 <div class="table">232 <table>233<?py for row in table: ?>234 <tr>235<?py for cell in row: ?>236 <td>#{cell}</td>237<?py #end ?>238 </tr>239<?py #end ?>240 </table>241 </div>242 </body>243</html>\244""")245179def test_mako():180 mako_template.render(**context)246 def test_tenjin():247 from tenjin.helpers import escape, to_str248 tenjin_template.render(context, locals())249182def test_genshi():183 genshi_template.generate(**context).render('html', strip_whitespace=False)184185def test_cheetah():186 unicode(cheetah_template)187188sys.stdout.write('\r%s\n%s\n%s\n' % (250sys.stdout.write('\r' + '\n'.join((251 '=' * 80,252 'Template Engine BigTable Benchmark'.center(80),253 '-' * 80,254 __doc__,255 '-' * 80192))193for test in 'jinja', 'mako', 'django', 'genshi', 'cheetah':256)) + '\n')257for test in 'jinja', 'tenjin', 'mako', 'django', 'genshi', 'cheetah':258 if locals()['test_' + test] is None:259 sys.stdout.write(' %-20s*not installed*\n' % test)260 continue261 t = Timer(setup='from __main__ import test_%s as bench' % test,262 stmt='bench()')263 sys.stdout.write('> %-20s<running>' % test)264 sys.stdout.flush()198 sys.stdout.write('\r %-20s%.4f ms\n' % (test, t.timeit(number=100) / 100))265 sys.stdout.write('\r %-20s%.4f ms\n' % (test, t.timeit(number=20) / 20))266sys.stdout.write('=' * 80 + '\n')
modified:jinja2/compiler.py+122 added-54 removed
8 unmodified lines
9 :license: GNU GPL.10"""11from copy import copy12from random import randrange13from keyword import iskeyword14from cStringIO import StringIO15from itertools import chain16from jinja2 import nodes17from jinja2.visitor import NodeVisitor, NodeTransformer18from jinja2.exceptions import TemplateAssertionError19from jinja2.runtime import StaticLoopContext, concat
144 unmodified lines
164 rv.identifiers = copy(self.identifiers)165 rv.name_overrides = self.name_overrides.copy()166 return rv167166 def inspect(self, nodes, hard_scope=False):167 """Walk the node and check for identifiers. If the scope168 is hard (eg: enforce on a python level) overrides from outer169 scopes are tracked differently.168 def inspect(self, nodes, with_depenencies=False, hard_scope=False):169 """Walk the node and check for identifiers. If the scope is hard (eg:170 enforce on a python level) overrides from outer scopes are tracked171 differently.172173 Per default filters and tests (dependencies) are not tracked. That's174 the case because filters and tests are absolutely immutable and so we175 can savely use them in closures too. The `Template` and `Block`176 visitor visits the frame with dependencies to collect them.177 """178 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)179 for node in nodes:173 visitor.visit(node)180 visitor.visit(node, True, with_depenencies)181182 def inner(self):183 """Return an inner frame."""184 return Frame(self)
14 unmodified lines
199 def __init__(self, identifiers, hard_scope):200 self.identifiers = identifiers201 self.hard_scope = hard_scope202196 def visit_Name(self, node):203 def visit_Name(self, node, visit_ident, visit_deps):204 """All assignments to names go through this function."""205 if visit_ident:198 if node.ctx in ('store', 'param'):199 self.identifiers.declared_locally.add(node.name)200 elif node.ctx == 'load':201 if not self.identifiers.is_declared(node.name, self.hard_scope):206 if node.ctx in ('store', 'param'):207 self.identifiers.declared_locally.add(node.name)208 elif node.ctx == 'load' and not \209 self.identifiers.is_declared(node.name, self.hard_scope):210 self.identifiers.undeclared.add(node.name)211204 def visit_Filter(self, node):205 self.generic_visit(node)206 self.identifiers.filters.add(node.name)212 def visit_Filter(self, node, visit_ident, visit_deps):213 if visit_deps:214 self.generic_visit(node, visit_ident, True)215 self.identifiers.filters.add(node.name)216208 def visit_Test(self, node):209 self.generic_visit(node)210 self.identifiers.tests.add(node.name)217 def visit_Test(self, node, visit_ident, visit_deps):218 if visit_deps:219 self.generic_visit(node, visit_ident, True)220 self.identifiers.tests.add(node.name)221212 def visit_Macro(self, node):213 self.identifiers.declared_locally.add(node.name)222 def visit_Macro(self, node, visit_ident, visit_deps):223 if visit_ident:224 self.identifiers.declared_locally.add(node.name)225215 def visit_Import(self, node):216 self.generic_visit(node)217 self.identifiers.declared_locally.add(node.target)226 def visit_Import(self, node, visit_ident, visit_deps):227 if visit_ident:228 self.generic_visit(node, True, visit_deps)229 self.identifiers.declared_locally.add(node.target)230219 def visit_FromImport(self, node):220 self.generic_visit(node)221 self.identifiers.declared_locally.update(node.names)231 def visit_FromImport(self, node, visit_ident, visit_deps):232 if visit_ident:233 self.generic_visit(node, True, visit_deps)234 for name in node.names:235 if isinstance(name, tuple):236 self.identifiers.declared_locally.add(name[1])237 else:238 self.identifiers.declared_locally.add(name)239223 def visit_Assign(self, node):240 def visit_Assign(self, node, visit_ident, visit_deps):241 """Visit assignments in the correct order."""225 self.visit(node.node)226 self.visit(node.target)242 self.visit(node.node, visit_ident, visit_deps)243 self.visit(node.target, visit_ident, visit_deps)244228 # stop traversing at instructions that have their own scope.229 visit_Block = visit_CallBlock = visit_FilterBlock = \230 visit_For = lambda s, n: None245 def visit_For(self, node, visit_ident, visit_deps):246 """Visiting stops at for blocks. However the block sequence247 is visited as part of the outer scope.248 """249 if visit_ident:250 self.visit(node.iter, True, visit_deps)251 if visit_deps:252 for child in node.iter_child_nodes(exclude=('iter',)):253 self.visit(child, False, True)254255 def ident_stop(self, node, visit_ident, visit_deps):256 if visit_deps:257 self.generic_visit(node, False, True)258 visit_CallBlock = visit_FilterBlock = ident_stop259 visit_Block = lambda s, n, a, b: None260261262class CompilerExit(Exception):263 """Raised if the compiler encountered a situation where it just264 doesn't make sense to further process the code. Any block that265 raises such an exception is not further processed.
106 unmodified lines
372373 def signature(self, node, frame, have_comma=True, extra_kwargs=None):374 """Writes a function call to the stream for the current node.375 Per default it will write a leading comma but this can be347 disabled by setting have_comma to False. If extra_kwargs is348 given it must be a string that represents a single keyword349 argument call that is inserted at the end of the regular350 keyword argument calls.376 disabled by setting have_comma to False. The extra keyword377 arguments may not include python keywords otherwise a syntax378 error could occour. The extra keyword arguments should be given379 as python dict.380 """381 have_comma = have_comma and [True] or []382 def touch_comma():383 if have_comma:384 self.write(', ')385 else:386 have_comma.append(True)387388 # if any of the given keyword arguments is a python keyword389 # we have to make sure that no invalid call is created.390 kwarg_workaround = False391 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):392 if iskeyword(kwarg):393 kwarg_workaround = True394 break395396 for arg in node.args:397 touch_comma()398 self.visit(arg, frame)399400 if not kwarg_workaround:362 for kwarg in node.kwargs:363 touch_comma()364 self.visit(kwarg, frame)365 if extra_kwargs is not None:366 touch_comma()367 self.write(extra_kwargs)401 for kwarg in node.kwargs:402 touch_comma()403 self.visit(kwarg, frame)404 if extra_kwargs is not None:405 for key, value in extra_kwargs.iteritems():406 touch_comma()407 self.write('%s=%s' % (key, value))408 if node.dyn_args:409 touch_comma()410 self.write('*')411 self.visit(node.dyn_args, frame)372 if node.dyn_kwargs:412413 if kwarg_workaround:414 touch_comma()415 if node.dyn_kwargs is not None:416 self.write('**dict({')417 else:418 self.write('**{')419 for kwarg in node.kwargs:420 self.write('%r: ' % kwarg.key)421 self.visit(kwarg.value, frame)422 self.write(', ')423 if extra_kwargs is not None:424 for key, value in extra_kwargs.iteritems():425 touch_comma()426 self.write('%r: %s, ' % (key, value))427 if node.dyn_kwargs is not None:428 self.write('}, **')429 self.visit(node.dyn_kwargs, frame)430 self.write(')')431 else:432 self.write('}')433434 elif node.dyn_kwargs is not None:435 touch_comma()436 self.write('**')437 self.visit(node.dyn_kwargs, frame)438439 def pull_locals(self, frame, indent=True):
69 unmodified lines
509 func_frame.accesses_varargs = False510 func_frame.accesses_caller = False511 func_frame.arguments = args = ['l_' + x.name for x in node.args]512513 if 'caller' in func_frame.identifiers.undeclared:514 func_frame.accesses_caller = True515 func_frame.identifiers.add_special('caller')516 args.append('l_caller')517 if 'kwargs' in func_frame.identifiers.undeclared:518 func_frame.accesses_kwargs = True519 func_frame.identifiers.add_special('kwargs')520 args.append('l_kwargs')521 if 'varargs' in func_frame.identifiers.undeclared:522 func_frame.accesses_varargs = True523 func_frame.identifiers.add_special('varargs')524 args.append('l_varargs')459 if 'caller' in func_frame.identifiers.undeclared:460 func_frame.accesses_caller = True461 func_frame.identifiers.add_special('caller')462 args.append('l_caller')525 return func_frame526527 # -- Visitors528529 def visit_Template(self, node, frame=None):530 assert frame is None, 'no root frame allowed'531 from jinja2.runtime import __all__ as exported469 self.writeline('from jinja2.runtime import *')532 self.writeline('from jinja2.runtime import ' + ', '.join(exported))533 self.writeline('name = %r' % self.name)534535 # do we have an extends tag at all? If not, we can save some536 # overhead by just not processing any inheritance code.
16 unmodified lines
553 self.outdent()554555 # process the root556 frame = Frame()494 frame.inspect(node.body)557 frame.inspect(node.body, with_depenencies=True)558 frame.toplevel = frame.rootlevel = True559 self.indent()560 self.pull_locals(frame, indent=False)561 self.blockvisit(node.body, frame, indent=False)
13 unmodified lines
575576 # at this point we now have the blocks collected and can visit them too.577 for name, block in self.blocks.iteritems():578 block_frame = Frame()516 block_frame.inspect(block.body)579 block_frame.inspect(block.body, with_depenencies=True)580 block_frame.block = name581 block_frame.identifiers.add_special('super')582 block_frame.name_overrides['super'] = 'context.super(%r, ' \583 'block_%s)' % (name, name)
105 unmodified lines
689 self.write('included_template = environment.get_template(')690 self.visit(node.template, frame)691 self.write(', %r).include(context)' % self.name)692 for name in node.names:693 if isinstance(name, tuple):694 name, alias = name695 else:696 alias = name697 self.writeline('l_%s = getattr(included_template, '631 '%r, missing)' % (name, name))632 self.writeline('if l_%s is missing:' % name)698 '%r, missing)' % (alias, name))699 self.writeline('if l_%s is missing:' % alias)700 self.indent()701 self.writeline('l_%s = environment.undefined(%r %% '702 'included_template.name)' %636 (name, 'the template %r does not export '703 (alias, 'the template %r does not export '704 'the requested name ' + repr(name)))705 self.outdent()706 if frame.toplevel:640 self.writeline('context[%r] = l_%s' % (name, name))707 self.writeline('context[%r] = l_%s' % (alias, alias))708709 def visit_For(self, node, frame):710 loop_frame = frame.inner()644 loop_frame.inspect(node.iter_child_nodes())711 loop_frame.inspect(node.iter_child_nodes(exclude=('iter',)))712 extended_loop = bool(node.else_) or \713 'loop' in loop_frame.identifiers.undeclared714 if extended_loop:715 loop_frame.identifiers.add_special('loop')
124 unmodified lines
840 if frame.buffer is None:841 self.writeline('yield ', node)842 else:843 self.writeline('%s.append(' % frame.buffer, node)777 self.visit_Call(node.call, call_frame, extra_kwargs='caller=caller')844 self.visit_Call(node.call, call_frame,845 extra_kwargs={'caller': 'caller'})846 if frame.buffer is not None:847 self.write(')')848849 def visit_FilterBlock(self, node, frame):
304 unmodified lines
modified:jinja2/environment.py+6 added-7 removed
393 unmodified lines
394class IncludedTemplate(object):395 """Represents an included template."""396397 def __init__(self, template, context):398 body = Markup(concat(template.root_render_func(context)))398 self._body_stream = tuple(template.root_render_func(context))399 self.__dict__.update(context.get_exported())400 self._name = template.name401 self._rendered_body = body400 self.__name__ = template.name401403 __html__ = lambda x: x._rendered_body404 __unicode__ = lambda x: unicode(x._rendered_body)402 __html__ = lambda x: Markup(concat(x._body_stream))403 __unicode__ = lambda x: unicode(concat(x._body_stream))404405 def __str__(self):407 return unicode(self._rendered_body).encode('utf-8')406 return unicode(self).encode('utf-8')407408 def __repr__(self):409 return '<%s %r>' % (410 self.__class__.__name__,412 self._name411 self.__name__412 )413414415class TemplateStream(object):
51 unmodified lines
modified:jinja2/ext.py+2 added-2 removed
11 unmodified lines
12"""13from collections import deque14from jinja2 import nodes15from jinja2.environment import get_spontaneous_environment16from jinja2.runtime import Undefined16from jinja2.runtime import Undefined, concat17from jinja2.parser import statement_end_tokens18from jinja2.exceptions import TemplateAssertionError19from jinja2.utils import import_string20
168 unmodified lines
189 parser.filename)190 else:191 assert False, 'internal parser error'192193 return referenced, u''.join(buf)193 return referenced, concat(buf)194195 def _make_node(self, singular, plural, variables, plural_expr):196 """Generates a useful node from the data provided."""197 # singular only:
97 unmodified lines
modified:jinja2/nodes.py+11 added-8 removed
90 unmodified lines
91 if kw:92 raise TypeError('unknown keyword argument %r' %93 iter(kw).next())9495 def iter_fields(self):95 def iter_fields(self, exclude=()):96 """Iterate over all fields."""97 for name in self.fields:98 if name not in exclude:98 try:99 yield name, getattr(self, name)100 except AttributeError:101 pass99 try:100 yield name, getattr(self, name)101 except AttributeError:102 pass103103 def iter_child_nodes(self):104 def iter_child_nodes(self, exclude=()):105 """Iterate over all child nodes."""105 for field, item in self.iter_fields():106 for field, item in self.iter_fields(exclude):107 if isinstance(item, list):108 for n in item:109 if isinstance(n, Node):110 yield n
132 unmodified lines
243244245class CallBlock(Stmt):246 """A node that represents am extended macro call."""246 fields = ('call', 'args', 'defaults', 'body')247 fields = ('call', 'body')248249250class Set(Stmt):251 """Allows defining own variables."""
27 unmodified lines
279 subscribe callback of the interface. As exported variables may not280 start with double underscores (which the parser asserts) this is not a281 problem for regular Jinja code, but if this node is used in an extension282 extra care must be taken.283284 The list of names may contain tuples if aliases are wanted.285 """286 fields = ('template', 'names')287288
331 unmodified lines
modified:jinja2/parser.py+11 added-2 removed
11 unmodified lines
12from jinja2 import nodes13from jinja2.exceptions import TemplateSyntaxError141516statement_end_tokens = set(['variable_end', 'block_end', 'in'])17_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',18 'macro', 'include', 'from', 'import'])19_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])19statement_end_tokens = set(['variable_end', 'block_end', 'in'])20_tuple_edge_tokens = set(['rparen']) | statement_end_tokens212223class Parser(object):
153 unmodified lines
177 raise TemplateAssertionError('names starting with two '178 'underscores can not be '179 'imported', target.lineno,180 self.filename)181 node.names.append(target.name)181 self.stream.next()182 if self.stream.current.test('name:as'):183 self.stream.next()184 alias = self.stream.expect('name')185 if not nodes.Name(alias.value, 'store').can_assign():186 raise TemplateSyntaxError('can\'t name imported '187 'object %r.' % alias.value,188 alias.lineno, self.filename)189 node.names.append((target.name, alias.value))190 else:191 node.names.append(target.name)192 if self.stream.current.type is not 'comma':193 break194 else:195 break
506 unmodified lines
modified:jinja2/runtime.py+21 added-14 removed
7 unmodified lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11from types import FunctionType12from itertools import izip13from jinja2.utils import Markup, partial14from jinja2.exceptions import UndefinedError151617# these variables are exported to the template runtime18__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17 'Macro', 'Markup', 'missing', 'concat']19 'Macro', 'Markup', 'missing', 'concat', 'izip']202122# special singleton representing missing values for the runtime23missing = object()
11 unmodified lines
35 """3637 def __init__(self, environment, parent, name, blocks):38 self.parent = parent37 self.vars = {}39 self.vars = vars = {}40 self.environment = environment41 self.exported_vars = set()42 self.name = name4344 # bind functions to the context of environment if required43 for name, obj in self.parent.iteritems():45 for name, obj in parent.iteritems():46 if type(obj) is FunctionType:47 if getattr(obj, 'contextfunction', 0):46 self.vars[name] = partial(obj, self)48 vars[name] = partial(obj, self)49 elif getattr(obj, 'environmentfunction', 0):48 self.vars[name] = partial(obj, environment)50 vars[name] = partial(obj, environment)5152 # create the initial mapping of blocks. Whenever template inheritance53 # takes place the runtime will update this mapping with the new blocks54 # from the template.
169 unmodified lines
224 self._environment = environment225 self._func = func226 self.name = name227 self.arguments = arguments228 self.argument_count = len(arguments)229 self.defaults = defaults230 self.catch_kwargs = catch_kwargs231 self.catch_varargs = catch_varargs232 self.caller = caller233234 def __call__(self, *args, **kwargs):232 arg_count = len(self.arguments)233 if not self.catch_varargs and len(args) > arg_count:235 self.argument_count = len(self.arguments)236 if not self.catch_varargs and len(args) > self.argument_count:237 raise TypeError('macro %r takes not more than %d argument(s)' %238 (self.name, len(self.arguments)))236 arguments = {}239 arguments = []240 for idx, name in enumerate(self.arguments):241 try:242 value = args[idx]243 except IndexError:244 try:245 value = kwargs.pop(name)246 except KeyError:247 try:245 value = self.defaults[idx - arg_count]248 value = self.defaults[idx - self.argument_count]249 except IndexError:250 value = self._environment.undefined(251 'parameter %r was not provided' % name)249 arguments['l_' + name] = value252 arguments.append(value)253254 # it's important that the order of these arguments does not change255 # if not also changed in the compiler's `function_scoping` method.256 # the order is caller, keyword arguments, positional arguments!257 if self.caller:258 caller = kwargs.pop('caller', None)259 if caller is None:260 caller = self._environment.undefined('No caller defined')254 arguments['l_caller'] = caller261 arguments.append(caller)262 if self.catch_kwargs:256 arguments['l_kwargs'] = kwargs263 arguments.append(kwargs)264 elif kwargs:265 raise TypeError('macro %r takes no keyword argument %r' %266 (self.name, iter(kwargs).next()))267 if self.catch_varargs:261 arguments['l_varargs'] = args[arg_count:]262 return self._func(**arguments)268 arguments.append(args[self.argument_count:])269 return self._func(*arguments)270271 def __repr__(self):272 return '<%s %s>' % (273 self.__class__.__name__,
83 unmodified lines