runtime.py
This file
Path
jinja2/runtime.py
537 lines · 17.7 KiB · Python
Last changed by
Improved error message for undefinedsArmin Ronacherbefore adoption98dbf5f
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 jinja2.runtime4 ~~~~~~~~~~~~~~56 Runtime helpers.78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD.10"""11import sys12from itertools import chain, imap13from jinja2.nodes import EvalContext14from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \15 concat, MethodType, FunctionType, internalcode, next, \16 object_type_repr17from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \18 TemplateNotFound192021# these variables are exported to the template runtime22__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',23 'TemplateRuntimeError', 'missing', 'concat', 'escape',24 'markup_join', 'unicode_join', 'to_string',25 'TemplateNotFound']262728#: the types we support for context functions29_context_function_types = (FunctionType, MethodType)3031#: the name of the function that is used to convert something into32#: a string. 2to3 will adopt that automatically and the generated33#: code can take advantage of it.34to_string = unicode353637def markup_join(seq):38 """Concatenation that escapes if necessary and converts to unicode."""39 buf = []40 iterator = imap(soft_unicode, seq)41 for arg in iterator:42 buf.append(arg)43 if hasattr(arg, '__html__'):44 return Markup(u'').join(chain(buf, iterator))45 return concat(buf)464748def unicode_join(seq):49 """Simple args to unicode conversion and concatenation."""50 return concat(imap(unicode, seq))515253def new_context(environment, template_name, blocks, vars=None,54 shared=None, globals=None, locals=None):55 """Internal helper to for context creation."""56 if vars is None:57 vars = {}58 if shared:59 parent = vars60 else:61 parent = dict(globals or (), **vars)62 if locals:63 # if the parent is shared a copy should be created because64 # we don't want to modify the dict passed65 if shared:66 parent = dict(parent)67 for key, value in locals.iteritems():68 if key[:2] == 'l_' and value is not missing:69 parent[key[2:]] = value70 return Context(environment, parent, template_name, blocks)717273class TemplateReference(object):74 """The `self` in templates."""7576 def __init__(self, context):77 self.__context = context7879 def __getitem__(self, name):80 blocks = self.__context.blocks[name]81 wrap = self.__context.eval_ctx.autoescape and \82 Markup or (lambda x: x)83 return BlockReference(name, self.__context, blocks, 0)8485 def __repr__(self):86 return '<%s %r>' % (87 self.__class__.__name__,88 self.__context.name89 )909192class Context(object):93 """The template context holds the variables of a template. It stores the94 values passed to the template and also the names the template exports.95 Creating instances is neither supported nor useful as it's created96 automatically at various stages of the template evaluation and should not97 be created by hand.9899 The context is immutable. Modifications on :attr:`parent` **must not**100 happen and modifications on :attr:`vars` are allowed from generated101 template code only. Template filters and global functions marked as102 :func:`contextfunction`\s get the active context passed as first argument103 and are allowed to access the context read-only.104105 The template context supports read only dict operations (`get`,106 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,107 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`108 method that doesn't fail with a `KeyError` but returns an109 :class:`Undefined` object for missing variables.110 """111 __slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',112 'name', 'blocks', '__weakref__')113114 def __init__(self, environment, parent, name, blocks):115 self.parent = parent116 self.vars = {}117 self.environment = environment118 self.eval_ctx = EvalContext(self.environment, name)119 self.exported_vars = set()120 self.name = name121122 # create the initial mapping of blocks. Whenever template inheritance123 # takes place the runtime will update this mapping with the new blocks124 # from the template.125 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())126127 def super(self, name, current):128 """Render a parent block."""129 try:130 blocks = self.blocks[name]131 index = blocks.index(current) + 1132 blocks[index]133 except LookupError:134 return self.environment.undefined('there is no parent block '135 'called %r.' % name,136 name='super')137 return BlockReference(name, self, blocks, index)138139 def get(self, key, default=None):140 """Returns an item from the template context, if it doesn't exist141 `default` is returned.142 """143 try:144 return self[key]145 except KeyError:146 return default147148 def resolve(self, key):149 """Looks up a variable like `__getitem__` or `get` but returns an150 :class:`Undefined` object with the name of the name looked up.151 """152 if key in self.vars:153 return self.vars[key]154 if key in self.parent:155 return self.parent[key]156 return self.environment.undefined(name=key)157158 def get_exported(self):159 """Get a new dict with the exported variables."""160 return dict((k, self.vars[k]) for k in self.exported_vars)161162 def get_all(self):163 """Return a copy of the complete context as dict including the164 exported variables.165 """166 return dict(self.parent, **self.vars)167168 @internalcode169 def call(__self, __obj, *args, **kwargs):170 """Call the callable with the arguments and keyword arguments171 provided but inject the active context or environment as first172 argument if the callable is a :func:`contextfunction` or173 :func:`environmentfunction`.174 """175 if __debug__:176 __traceback_hide__ = True177 if isinstance(__obj, _context_function_types):178 if getattr(__obj, 'contextfunction', 0):179 args = (__self,) + args180 elif getattr(__obj, 'evalcontextfunction', 0):181 args = (__self.eval_ctx,) + args182 elif getattr(__obj, 'environmentfunction', 0):183 args = (__self.environment,) + args184 return __obj(*args, **kwargs)185186 def derived(self, locals=None):187 """Internal helper function to create a derived context."""188 context = new_context(self.environment, self.name, {},189 self.parent, True, None, locals)190 context.eval_ctx = self.eval_ctx191 context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())192 return context193194 def _all(meth):195 proxy = lambda self: getattr(self.get_all(), meth)()196 proxy.__doc__ = getattr(dict, meth).__doc__197 proxy.__name__ = meth198 return proxy199200 keys = _all('keys')201 values = _all('values')202 items = _all('items')203204 # not available on python 3205 if hasattr(dict, 'iterkeys'):206 iterkeys = _all('iterkeys')207 itervalues = _all('itervalues')208 iteritems = _all('iteritems')209 del _all210211 def __contains__(self, name):212 return name in self.vars or name in self.parent213214 def __getitem__(self, key):215 """Lookup a variable or raise `KeyError` if the variable is216 undefined.217 """218 item = self.resolve(key)219 if isinstance(item, Undefined):220 raise KeyError(key)221 return item222223 def __repr__(self):224 return '<%s %s of %r>' % (225 self.__class__.__name__,226 repr(self.get_all()),227 self.name228 )229230231# register the context as mapping if possible232try:233 from collections import Mapping234 Mapping.register(Context)235except ImportError:236 pass237238239class BlockReference(object):240 """One block on a template reference."""241242 def __init__(self, name, context, stack, depth):243 self.name = name244 self._context = context245 self._stack = stack246 self._depth = depth247248 @property249 def super(self):250 """Super the block."""251 if self._depth + 1 >= len(self._stack):252 return self._context.environment. \253 undefined('there is no parent block called %r.' %254 self.name, name='super')255 return BlockReference(self.name, self._context, self._stack,256 self._depth + 1)257258 @internalcode259 def __call__(self):260 rv = concat(self._stack[self._depth](self._context))261 if self._context.eval_ctx.autoescape:262 rv = Markup(rv)263 return rv264265266class LoopContext(object):267 """A loop context for dynamic iteration."""268269 def __init__(self, iterable, recurse=None):270 self._iterator = iter(iterable)271 self._recurse = recurse272 self.index0 = -1273274 # try to get the length of the iterable early. This must be done275 # here because there are some broken iterators around where there276 # __len__ is the number of iterations left (i'm looking at your277 # listreverseiterator!).278 try:279 self._length = len(iterable)280 except (TypeError, AttributeError):281 self._length = None282283 def cycle(self, *args):284 """Cycles among the arguments with the current loop index."""285 if not args:286 raise TypeError('no items for cycling given')287 return args[self.index0 % len(args)]288289 first = property(lambda x: x.index0 == 0)290 last = property(lambda x: x.index0 + 1 == x.length)291 index = property(lambda x: x.index0 + 1)292 revindex = property(lambda x: x.length - x.index0)293 revindex0 = property(lambda x: x.length - x.index)294295 def __len__(self):296 return self.length297298 def __iter__(self):299 return LoopContextIterator(self)300301 @internalcode302 def loop(self, iterable):303 if self._recurse is None:304 raise TypeError('Tried to call non recursive loop. Maybe you '305 "forgot the 'recursive' modifier.")306 return self._recurse(iterable, self._recurse)307308 # a nifty trick to enhance the error message if someone tried to call309 # the the loop without or with too many arguments.310 __call__ = loop311 del loop312313 @property314 def length(self):315 if self._length is None:316 # if was not possible to get the length of the iterator when317 # the loop context was created (ie: iterating over a generator)318 # we have to convert the iterable into a sequence and use the319 # length of that.320 iterable = tuple(self._iterator)321 self._iterator = iter(iterable)322 self._length = len(iterable) + self.index0 + 1323 return self._length324325 def __repr__(self):326 return '<%s %r/%r>' % (327 self.__class__.__name__,328 self.index,329 self.length330 )331332333class LoopContextIterator(object):334 """The iterator for a loop context."""335 __slots__ = ('context',)336337 def __init__(self, context):338 self.context = context339340 def __iter__(self):341 return self342343 def next(self):344 ctx = self.context345 ctx.index0 += 1346 return next(ctx._iterator), ctx347348349class Macro(object):350 """Wraps a macro."""351352 def __init__(self, environment, func, name, arguments, defaults,353 catch_kwargs, catch_varargs, caller):354 self._environment = environment355 self._func = func356 self._argument_count = len(arguments)357 self.name = name358 self.arguments = arguments359 self.defaults = defaults360 self.catch_kwargs = catch_kwargs361 self.catch_varargs = catch_varargs362 self.caller = caller363364 @internalcode365 def __call__(self, *args, **kwargs):366 arguments = []367 for idx, name in enumerate(self.arguments):368 try:369 value = args[idx]370 except:371 try:372 value = kwargs.pop(name)373 except:374 try:375 value = self.defaults[idx - self._argument_count]376 except:377 value = self._environment.undefined(378 'parameter %r was not provided' % name, name=name)379 arguments.append(value)380381 # it's important that the order of these arguments does not change382 # if not also changed in the compiler's `function_scoping` method.383 # the order is caller, keyword arguments, positional arguments!384 if self.caller:385 caller = kwargs.pop('caller', None)386 if caller is None:387 caller = self._environment.undefined('No caller defined',388 name='caller')389 arguments.append(caller)390 if self.catch_kwargs:391 arguments.append(kwargs)392 elif kwargs:393 raise TypeError('macro %r takes no keyword argument %r' %394 (self.name, next(iter(kwargs))))395 if self.catch_varargs:396 arguments.append(args[self._argument_count:])397 elif len(args) > self._argument_count:398 raise TypeError('macro %r takes not more than %d argument(s)' %399 (self.name, len(self.arguments)))400 return self._func(*arguments)401402 def __repr__(self):403 return '<%s %s>' % (404 self.__class__.__name__,405 self.name is None and 'anonymous' or repr(self.name)406 )407408409class Undefined(object):410 """The default undefined type. This undefined type can be printed and411 iterated over, but every other access will raise an :exc:`UndefinedError`:412413 >>> foo = Undefined(name='foo')414 >>> str(foo)415 ''416 >>> not foo417 True418 >>> foo + 42419 Traceback (most recent call last):420 ...421 UndefinedError: 'foo' is undefined422 """423 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',424 '_undefined_exception')425426 def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):427 self._undefined_hint = hint428 self._undefined_obj = obj429 self._undefined_name = name430 self._undefined_exception = exc431432 @internalcode433 def _fail_with_undefined_error(self, *args, **kwargs):434 """Regular callback function for undefined objects that raises an435 `UndefinedError` on call.436 """437 if self._undefined_hint is None:438 if self._undefined_obj is missing:439 hint = '%r is undefined' % self._undefined_name440 elif not isinstance(self._undefined_name, basestring):441 hint = '%s has no element %r' % (442 object_type_repr(self._undefined_obj),443 self._undefined_name444 )445 else:446 hint = '%r has no attribute %r' % (447 object_type_repr(self._undefined_obj),448 self._undefined_name449 )450 else:451 hint = self._undefined_hint452 raise self._undefined_exception(hint)453454 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \455 __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \456 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \457 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \458 __int__ = __float__ = __complex__ = __pow__ = __rpow__ = \459 _fail_with_undefined_error460461 def __str__(self):462 return unicode(self).encode('utf-8')463464 # unicode goes after __str__ because we configured 2to3 to rename465 # __unicode__ to __str__. because the 2to3 tree is not designed to466 # remove nodes from it, we leave the above __str__ around and let467 # it override at runtime.468 def __unicode__(self):469 return u''470471 def __len__(self):472 return 0473474 def __iter__(self):475 if 0:476 yield None477478 def __nonzero__(self):479 return False480481 def __repr__(self):482 return 'Undefined'483484485class DebugUndefined(Undefined):486 """An undefined that returns the debug info when printed.487488 >>> foo = DebugUndefined(name='foo')489 >>> str(foo)490 '{{ foo }}'491 >>> not foo492 True493 >>> foo + 42494 Traceback (most recent call last):495 ...496 UndefinedError: 'foo' is undefined497 """498 __slots__ = ()499500 def __unicode__(self):501 if self._undefined_hint is None:502 if self._undefined_obj is missing:503 return u'{{ %s }}' % self._undefined_name504 return '{{ no such element: %s[%r] }}' % (505 object_type_repr(self._undefined_obj),506 self._undefined_name507 )508 return u'{{ undefined value printed: %s }}' % self._undefined_hint509510511class StrictUndefined(Undefined):512 """An undefined that barks on print and iteration as well as boolean513 tests and all kinds of comparisons. In other words: you can do nothing514 with it except checking if it's defined using the `defined` test.515516 >>> foo = StrictUndefined(name='foo')517 >>> str(foo)518 Traceback (most recent call last):519 ...520 UndefinedError: 'foo' is undefined521 >>> not foo522 Traceback (most recent call last):523 ...524 UndefinedError: 'foo' is undefined525 >>> foo + 42526 Traceback (most recent call last):527 ...528 UndefinedError: 'foo' is undefined529 """530 __slots__ = ()531 __iter__ = __unicode__ = __str__ = __len__ = __nonzero__ = __eq__ = \532 __ne__ = Undefined._fail_with_undefined_error533534535# remove remaining slots attributes, after the metaclass did the magic they536# are unneeded and irritating as they contain wrong data for the subclasses.537del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__