Skip to content
Myr

small performance improvements

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 7259c76 · Browse files · 6 files+59 added−44 removed
This commit

State

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

Diff stats

6 files+59 added−44 removed

  • other:+59 added−44 removed

6 files+59 added−44 removed

modified:docs/api.rst+3 added-3 removed
121 unmodified lines
122123The Context124-----------125126.. autoclass:: jinja2.runtime.TemplateContext126.. autoclass:: jinja2.runtime.Context127 :members: super, get, get_exported, get_all128129 .. attribute:: parent130131 A dict of read only, global variables the template looks up. These132 can either come from another :class:`TemplateContext`, from the132 can either come from another :class:`Context`, from the133 :attr:`Environment.globals` or :attr:`Template.globals`. It must not134 be altered.135136 .. attribute:: vars
141 unmodified lines
278 result = Markup(result)279 return result280281Context filters work the same just that the first argument is the current282active :class:`TemplateContext` rather then the environment.282active :class:`Context` rather then the environment.283284285.. _writing-tests:286
48 unmodified lines
modified:docs/templates.rst+13 added
795 unmodified lines
796 When step is given, it specifies the increment (or decrement).797 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!798 These are exactly the valid indices for a list of 4 elements.799800 This is useful to repeat a template block multiple times for example801 to fill a list. Imagine you have 7 users in the list but you want to802 render three empty items to enforce a height with CSS::803804 <ul>805 {% for user in users %}806 <li>{{ user.username }}</li>807 {% endfor %}808 {% for number in range(10 - users|count) %}809 <li class="empty"><span>...</span></li>810 {% endfor %}811 </ul>812813.. function:: lipsum(n=5, html=True, min=20, max=100)814815 Generates some lorem ipsum for the template. Per default five paragraphs816 with HTML are generated each paragraph between 20 and 100 words. If html
2 unmodified lines
modified:examples/bench.py+1 added-1 removed
303 unmodified lines
304 t = Timer(setup='from __main__ import test_%s as bench' % test,305 stmt='bench()')306 sys.stdout.write(' >> %-20s<running>' % test)307 sys.stdout.flush()308 sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=20) / 20))308 sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50))309sys.stdout.write('-' * 80 + '\n')310sys.stdout.write('''\311 WARNING: The results of this benchmark are useless to compare the312 performance of template engines and should not be taken seriously in any
4 unmodified lines
modified:jinja2/compiler.py+7 added-6 removed
738 unmodified lines
739 '%r, missing)' % (alias, name))740 self.writeline('if l_%s is missing:' % alias)741 self.indent()742 self.writeline('l_%s = environment.undefined(%r %% '743 'included_template.name)' %743 'included_template.name, '744 'name=included_template.name)' %745 (alias, 'the template %r does not export '746 'the requested name ' + repr(name)))747 self.outdent()748 if frame.toplevel:
21 unmodified lines
770771 # the expression pointing to the parent loop. We make the772 # undefined a bit more debug friendly at the same time.773 parent_loop = 'loop' in aliases and aliases['loop'] \773 or "environment.undefined(%r)" % "'loop' is undefined. " \774 'the filter section of a loop as well as the ' \775 'else block doesn\'t have access to the special ' \776 "'loop' variable of the current loop. Because " \777 'there is no parent loop it\'s undefined.'774 or "environment.undefined(%r, name='loop')" % "'loop' " \775 'is undefined. "the filter section of a loop as well ' \776 'as the else block doesn\'t have access to the ' \777 "special 'loop' variable of the current loop. " \778 "Because there is no parent loop it's undefined."779780 # if we have an extened loop and a node test, we filter in the781 # "outer frame".782 if extended_loop and node.test is not None:
447 unmodified lines
modified:jinja2/environment.py+21 added-22 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~~56 Provides a class that holds runtime and parsing time options.78 :copyright: 2007 by Armin Ronacher.8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import sys12from jinja2.defaults import *13from jinja2.lexer import Lexer14from jinja2.parser import Parser15from jinja2.optimizer import optimize16from jinja2.compiler import generate17from jinja2.runtime import Undefined, TemplateContext, concat17from jinja2.runtime import Undefined, Context, concat18from jinja2.debug import translate_exception19from jinja2.utils import import_string, LRUCache, Markup, missing2021
45 unmodified lines
67 assert environment.block_start_string != \68 environment.variable_start_string != \69 environment.comment_start_string, 'block, variable and comment ' \70 'start strings must be different'71 return environment727374class Environment(object):75 """The core component of Jinja is the `Environment`. It contains
72 unmodified lines
148149 #: True if the environment is just an overlay150 overlay = False151152 #: the environment this environment is linked to if it is an overlay153 linked_to = None154155 #: shared environments have this set to `True`. A shared environment156 #: must not be modified157 shared = False158
94 unmodified lines
253 rv.extensions.append(extension.bind(self))254 if extensions is not missing:255 rv.extensions.extend(load_extensions(extensions))256253 _environment_sanity_check(rv)254 return rv257 return _environment_sanity_check(rv)258259 @property260 def lexer(self):261 """Return a fresh lexer for the environment."""
196 unmodified lines
458459 This will return the rendered template as unicode string.460 """461 try:459 return concat(self.generate(*args, **kwargs))462 return concat(self._generate(*args, **kwargs))463 except:461 # hide the `generate` frame462 exc_type, exc_value, tb = sys.exc_info()463 raise exc_type, exc_value, tb.tb_next464 exc_type, exc_value, tb = translate_exception(sys.exc_info())465 raise exc_type, exc_value, tb466467 def stream(self, *args, **kwargs):468 """Works exactly like :meth:`generate` but returns a469 :class:`TemplateStream`.470 """469 try:470 return TemplateStream(self.generate(*args, **kwargs))471 return TemplateStream(self.generate(*args, **kwargs))471 except:472 # hide the `generate` frame473 exc_type, exc_value, tb = sys.exc_info()474 raise exc_type, exc_value, tb.tb_next472473 def generate(self, *args, **kwargs):474 """For very large templates it can be useful to not render the whole475 template at once but evaluate each statement after another and yield
1 unmodified line
477 a generator that yields one item after another as unicode strings.478479 It accepts the same arguments as :meth:`render`.480 """481 try:482 for item in self._generate(*args, **kwargs):483 yield item484 except:485 exc_type, exc_value, tb = translate_exception(sys.exc_info())486 raise exc_type, exc_value, tb487488 def _generate(self, *args, **kwargs):489 # assemble the context490 context = dict(*args, **kwargs)491492 # if the environment is using the optimizer locals may never
9 unmodified lines
502 'With an enabled optimizer this '503 'will lead to unexpected results.' %504 (plural, ', '.join(overrides), plural or ' a', plural))505501 try:502 for event in self.root_render_func(self.new_context(context)):503 yield event504 except:505 exc_type, exc_value, tb = translate_exception(sys.exc_info())506 raise exc_type, exc_value, tb506 return self.root_render_func(self.new_context(context))507508 def new_context(self, vars=None, shared=False):509 """Create a new template context for this template. The vars510 provided will be passed to the template. Per default the globals
7 unmodified lines
518 if shared:519 parent = vars520 else:521 parent = dict(self.globals, **vars)522 return TemplateContext(self.environment, parent, self.name,523 self.blocks)522 return Context(self.environment, parent, self.name, self.blocks)523524 @property525 def module(self):526 """The template as module. This is used for imports in the
126 unmodified lines
modified:jinja2/runtime.py+14 added-12 removed
14 unmodified lines
15from jinja2.exceptions import UndefinedError, TemplateRuntimeError161718# these variables are exported to the template runtime19__all__ = ['LoopContext', 'TemplateContext', 'TemplateReference', 'Macro',20 'TemplateRuntimeError', 'Markup', 'missing', 'concat', 'escape',19__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',20 'TemplateRuntimeError', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']222324# concatenate a list of strings and convert them to unicode.
32 unmodified lines
57 """Simple args to unicode conversion and concatenation."""58 return concat(imap(unicode, args))596061class TemplateContext(object):61class Context(object):62 """The template context holds the variables of a template. It stores the63 values passed to the template and also the names the template exports.64 Creating instances is neither supported nor useful as it's created65 automatically at various stages of the template evaluation and should not
38 unmodified lines
104 if pos < 0:105 raise IndexError()106 except LookupError:107 return self.environment.undefined('there is no parent block '108 'called %r.' % name)108 'called %r.' % name,109 name='super')110 wrap = self.environment.autoescape and Markup or (lambda x: x)111 render = lambda: wrap(concat(blocks[pos](self)))112 render.__name__ = render.name = name113 return render
125 unmodified lines
239 self.catch_varargs = catch_varargs240 self.caller = caller241242 def __call__(self, *args, **kwargs):242 if not self.catch_varargs and len(args) > self._argument_count:243 raise TypeError('macro %r takes not more than %d argument(s)' %244 (self.name, len(self.arguments)))243 arguments = []244 for idx, name in enumerate(self.arguments):245 try:246 value = args[idx]249 except IndexError:247 except:248 try:249 value = kwargs.pop(name)252 except KeyError:250 except:251 try:252 value = self.defaults[idx - self._argument_count]255 except IndexError:253 except:254 value = self._environment.undefined(257 'parameter %r was not provided' % name)255 'parameter %r was not provided' % name, name=name)256 arguments.append(value)257258 # it's important that the order of these arguments does not change259 # if not also changed in the compiler's `function_scoping` method.260 # the order is caller, keyword arguments, positional arguments!261 if self.caller:262 caller = kwargs.pop('caller', None)263 if caller is None:266 caller = self._environment.undefined('No caller defined')264 caller = self._environment.undefined('No caller defined',265 name='caller')266 arguments.append(caller)267 if self.catch_kwargs:268 arguments.append(kwargs)269 elif kwargs:270 raise TypeError('macro %r takes no keyword argument %r' %271 (self.name, iter(kwargs).next()))272 if self.catch_varargs:273 arguments.append(args[self._argument_count:])274 elif len(args) > self._argument_count:275 raise TypeError('macro %r takes not more than %d argument(s)' %276 (self.name, len(self.arguments)))277 return self._func(*arguments)278279 def __repr__(self):280 return '<%s %s>' % (
127 unmodified lines