runtime.py
This file
Path
jinja2/runtime.py
517 lines · 16.9 KiB · Python
Last changed by
Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
History of this fileTake it
The walk stopped after 200 commits: lines older than b217886 point at it.
added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 1–7why, one step back1# -*- coding: utf-8 -*-2"""3 jinja2.runtime4 ~~~~~~~~~~~~~~56 Runtime helpers.7Copyright switch to "The Jinja Team".Armin Ronacherbefore adoption62ccd1b
line 8why, one step back8 :copyright: (c) 2009 by the Jinja Team.fixed a few broken license declarations. should have been BSD not GPLArmin Ronacherbefore adoptiond776437
line 9why, one step back9 :license: BSD.added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 10–12why, one step back10"""11import sys12from itertools import chain, imapMore work on the ironpython supportArmin Ronacherbefore adoptionce67710
line 13why, one step back13from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
line 14why, one step back14 concat, MethodType, FunctionType, internalcodeInclude statements can now be marked with ``ignore missing`` to skipArmin Ronacherbefore adoption37f58ce
lines 15–16why, one step back15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFoundadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 17–19why, one step back171819# these variables are exported to the template runtimeAdded support for optional `scoped` modifier to blocks.Armin Ronacherbefore adoption74a0cd9
line 20why, one step back20__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 21why, one step back21 'TemplateRuntimeError', 'missing', 'concat', 'escape',Include statements can now be marked with ``ignore missing`` to skipArmin Ronacherbefore adoption37f58ce
line 22why, one step back22 'markup_join', 'unicode_join', 'TemplateNotFound']added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 23why, one step back23Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d
line 24why, one step back24More work on the ironpython supportArmin Ronacherbefore adoptionce67710
lines 25–26why, one step back25#: the types we support for context functions26_context_function_types = (FunctionType, MethodType)added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 27why, one step back27added attr filterArmin Ronacherbefore adoption24b6558
line 28why, one step back28added a semi realworld benchmark (jinja2 and mako)Armin Ronacherbefore adoptiondc02b64
line 29why, one step back29def markup_join(seq):added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 30–31why, one step back30 """Concatenation that escapes if necessary and converts to unicode."""31 buf = []added a semi realworld benchmark (jinja2 and mako)Armin Ronacherbefore adoptiondc02b64
line 32why, one step back32 iterator = imap(soft_unicode, seq)added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 33–39why, one step back33 for arg in iterator:34 buf.append(arg)35 if hasattr(arg, '__html__'):36 return Markup(u'').join(chain(buf, iterator))37 return concat(buf)3839added a semi realworld benchmark (jinja2 and mako)Armin Ronacherbefore adoptiondc02b64
line 40why, one step back40def unicode_join(seq):added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 41why, one step back41 """Simple args to unicode conversion and concatenation."""added a semi realworld benchmark (jinja2 and mako)Armin Ronacherbefore adoptiondc02b64
line 42why, one step back42 return concat(imap(unicode, seq))added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 43–44why, one step back4344Added support for optional `scoped` modifier to blocks.Armin Ronacherbefore adoption74a0cd9
lines 45–83why, one step back45def new_context(environment, template_name, blocks, vars=None,46 shared=None, globals=None, locals=None):47 """Internal helper to for context creation."""48 if vars is None:49 vars = {}50 if shared:51 parent = vars52 else:53 parent = dict(globals or (), **vars)54 if locals:55 # if the parent is shared a copy should be created because56 # we don't want to modify the dict passed57 if shared:58 parent = dict(parent)59 for key, value in locals.iteritems():60 if key[:2] == 'l_' and value is not missing:61 parent[key[2:]] = value62 return Context(environment, parent, template_name, blocks)636465class TemplateReference(object):66 """The `self` in templates."""6768 def __init__(self, context):69 self.__context = context7071 def __getitem__(self, name):72 blocks = self.__context.blocks[name]73 wrap = self.__context.environment.autoescape and \74 Markup or (lambda x: x)75 return BlockReference(name, self.__context, blocks, 0)7677 def __repr__(self):78 return '<%s %r>' % (79 self.__class__.__name__,80 self.__context.name81 )8283added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 84–97why, one step back84class Context(object):85 """The template context holds the variables of a template. It stores the86 values passed to the template and also the names the template exports.87 Creating instances is neither supported nor useful as it's created88 automatically at various stages of the template evaluation and should not89 be created by hand.9091 The context is immutable. Modifications on :attr:`parent` **must not**92 happen and modifications on :attr:`vars` are allowed from generated93 template code only. Template filters and global functions marked as94 :func:`contextfunction`\s get the active context passed as first argument95 and are allowed to access the context read-only.9697 The template context supports read only dict operations (`get`,some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281
lines 98–101why, one step back98 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,99 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`100 method that doesn't fail with a `KeyError` but returns an101 :class:`Undefined` object for missing variables.added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 102why, one step back102 """some more cleaning upArmin Ronacherbefore adoption771c750
line 103why, one step back103 __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',It's now possible to create weak references to template contexts.Armin Ronacherbefore adoptiondcc217c
line 104why, one step back104 'blocks', '__weakref__')added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 105–121why, one step back105106 def __init__(self, environment, parent, name, blocks):107 self.parent = parent108 self.vars = vars = {}109 self.environment = environment110 self.exported_vars = set()111 self.name = name112113 # create the initial mapping of blocks. Whenever template inheritance114 # takes place the runtime will update this mapping with the new blocks115 # from the template.116 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())117118 def super(self, name, current):119 """Render a parent block."""120 try:121 blocks = self.blocks[name]Unified some code in the super/template reference system.Armin Ronacherbefore adoptionc347ed0
lines 122–123why, one step back122 index = blocks.index(current) + 1123 blocks[index]added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 124–127why, one step back124 except LookupError:125 return self.environment.undefined('there is no parent block '126 'called %r.' % name,127 name='super')Unified some code in the super/template reference system.Armin Ronacherbefore adoptionc347ed0
line 128why, one step back128 return BlockReference(name, self, blocks, index)added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 129–133why, one step back129130 def get(self, key, default=None):131 """Returns an item from the template context, if it doesn't exist132 `default` is returned.133 """some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281
lines 134–142why, one step back134 try:135 return self[key]136 except KeyError:137 return default138139 def resolve(self, key):140 """Looks up a variable like `__getitem__` or `get` but returns an141 :class:`Undefined` object with the name of the name looked up.142 """added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 143–146why, one step back143 if key in self.vars:144 return self.vars[key]145 if key in self.parent:146 return self.parent[key]some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281
line 147why, one step back147 return self.environment.undefined(name=key)added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 148–154why, one step back148149 def get_exported(self):150 """Get a new dict with the exported variables."""151 return dict((k, self.vars[k]) for k in self.exported_vars)152153 def get_all(self):154 """Return a copy of the complete context as dict including theeven more tests, fixed severe bug with autoescaping.Armin Ronacherbefore adoption5411ce7
line 155why, one step back155 exported variables.added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 156–157why, one step back156 """157 return dict(self.parent, **self.vars)all calls are proxied by context.call now so that we can inject environment and context as first arguments. This slows calls down a bit but is a lot more user friendly. Added first draft of FAQArmin Ronacherbefore adoptionfd31049
line 158why, one step back158Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
line 159why, one step back159 @internalcodeall calls are proxied by context.call now so that we can inject environment and context as first arguments. This slows calls down a bit but is a lot more user friendly. Added first draft of FAQArmin Ronacherbefore adoptionfd31049
line 160why, one step back160 def call(__self, __obj, *args, **kwargs):some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
lines 161–165why, one step back161 """Call the callable with the arguments and keyword arguments162 provided but inject the active context or environment as first163 argument if the callable is a :func:`contextfunction` or164 :func:`environmentfunction`.165 """added attr filterArmin Ronacherbefore adoption24b6558
lines 166–172why, one step back166 if __debug__:167 __traceback_hide__ = True168 if isinstance(__obj, _context_function_types):169 if getattr(__obj, 'contextfunction', 0):170 args = (__self,) + args171 elif getattr(__obj, 'environmentfunction', 0):172 args = (__self.environment,) + argsall calls are proxied by context.call now so that we can inject environment and context as first arguments. This slows calls down a bit but is a lot more user friendly. Added first draft of FAQArmin Ronacherbefore adoptionfd31049
line 173why, one step back173 return __obj(*args, **kwargs)added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 174why, one step back174Added support for optional `scoped` modifier to blocks.Armin Ronacherbefore adoption74a0cd9
lines 175–176why, one step back175 def derived(self, locals=None):176 """Internal helper function to create a derived context."""Added proper super() support for scoped blocks.Armin Ronacherbefore adoption3f1d8f1
lines 177–180why, one step back177 context = new_context(self.environment, self.name, {},178 self.parent, True, None, locals)179 context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())180 return contextAdded support for optional `scoped` modifier to blocks.Armin Ronacherbefore adoption74a0cd9
line 181why, one step back181some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281
line 182why, one step back182 def _all(meth):fixed bug with parameter parsingArmin Ronacherbefore adoptione9411b4
line 183why, one step back183 proxy = lambda self: getattr(self.get_all(), meth)()some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281
lines 184–195why, one step back184 proxy.__doc__ = getattr(dict, meth).__doc__185 proxy.__name__ = meth186 return proxy187188 keys = _all('keys')189 values = _all('values')190 items = _all('items')191 iterkeys = _all('iterkeys')192 itervalues = _all('itervalues')193 iteritems = _all('iteritems')194 del _all195added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 196–199why, one step back196 def __contains__(self, name):197 return name in self.vars or name in self.parent198199 def __getitem__(self, key):fixed an embarrassing mistake in the documentationArmin Ronacherbefore adoptionbbbe062
lines 200–206why, one step back200 """Lookup a variable or raise `KeyError` if the variable is201 undefined.202 """203 item = self.resolve(key)204 if isinstance(item, Undefined):205 raise KeyError(key)206 return itemadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 207–215why, one step back207208 def __repr__(self):209 return '<%s %s of %r>' % (210 self.__class__.__name__,211 repr(self.get_all()),212 self.name213 )214215Various cleanups and added custom cycler.Armin Ronacherbefore adoptionccae055
line 216why, one step back216# register the context as mapping if possiblesome more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
line 217why, one step back217try:Various cleanups and added custom cycler.Armin Ronacherbefore adoptionccae055
lines 218–219why, one step back218 from collections import Mapping219 Mapping.register(Context)some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
lines 220–221why, one step back220except ImportError:221 passUnified some code in the super/template reference system.Armin Ronacherbefore adoptionc347ed0
lines 222–242why, one step back222223224class BlockReference(object):225 """One block on a template reference."""226227 def __init__(self, name, context, stack, depth):228 self.name = name229 self._context = context230 self._stack = stack231 self._depth = depth232233 @property234 def super(self):235 """Super the block."""236 if self._depth + 1 >= len(self._stack):237 return self._context.environment. \238 undefined('there is no parent block called %r.' %239 self.name, name='super')240 return BlockReference(self.name, self._context, self._stack,241 self._depth + 1)242Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
line 243why, one step back243 @internalcodeUnified some code in the super/template reference system.Armin Ronacherbefore adoptionc347ed0
lines 244–248why, one step back244 def __call__(self):245 rv = concat(self._stack[self._depth](self._context))246 if self._context.environment.autoescape:247 rv = Markup(rv)248 return rvadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 249–253why, one step back249250251class LoopContext(object):252 """A loop context for dynamic iteration."""253Fixed a bug with the loop context of a for loop if the iterator passed has a volatile `__len__` like the listreverseiterator. `else` in inline if-expressions is optional now.Armin Ronacherbefore adoption547d0b6
lines 254–255why, one step back254 def __init__(self, iterable, recurse=None):255 self._iterator = iter(iterable)readded support for recursive for-loopsArmin Ronacherbefore adoption1e1e890
line 256why, one step back256 self._recurse = recurseadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 257–258why, one step back257 self.index0 = -1258Fixed a bug with the loop context of a for loop if the iterator passed has a volatile `__len__` like the listreverseiterator. `else` in inline if-expressions is optional now.Armin Ronacherbefore adoption547d0b6
lines 259–267why, one step back259 # try to get the length of the iterable early. This must be done260 # here because there are some broken iterators around where there261 # __len__ is the number of iterations left (i'm looking at your262 # listreverseiterator!).263 try:264 self._length = len(iterable)265 except (TypeError, AttributeError):266 self._length = None267added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 268why, one step back268 def cycle(self, *args):small refactoringArmin Ronacherbefore adoptioned1e0d4
line 269why, one step back269 """Cycles among the arguments with the current loop index."""added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 270–274why, one step back270 if not args:271 raise TypeError('no items for cycling given')272 return args[self.index0 % len(args)]273274 first = property(lambda x: x.index0 == 0)Fixed a bug with the loop context of a for loop if the iterator passed has a volatile `__len__` like the listreverseiterator. `else` in inline if-expressions is optional now.Armin Ronacherbefore adoption547d0b6
line 275why, one step back275 last = property(lambda x: x.index0 + 1 == x.length)added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 276–283why, one step back276 index = property(lambda x: x.index0 + 1)277 revindex = property(lambda x: x.length - x.index0)278 revindex0 = property(lambda x: x.length - x.index)279280 def __len__(self):281 return self.length282283 def __iter__(self):small refactoringArmin Ronacherbefore adoptioned1e0d4
line 284why, one step back284 return LoopContextIterator(self)readded support for recursive for-loopsArmin Ronacherbefore adoption1e1e890
line 285why, one step back285Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
line 286why, one step back286 @internalcodeadded unittest for recursive for loopArmin Ronacherbefore adoption66a9344
line 287why, one step back287 def loop(self, iterable):readded support for recursive for-loopsArmin Ronacherbefore adoption1e1e890
lines 288–289why, one step back288 if self._recurse is None:289 raise TypeError('Tried to call non recursive loop. Maybe you 'added unittest for recursive for loopArmin Ronacherbefore adoption66a9344
line 290why, one step back290 "forgot the 'recursive' modifier.")readded support for recursive for-loopsArmin Ronacherbefore adoption1e1e890
line 291why, one step back291 return self._recurse(iterable, self._recurse)added unittest for recursive for loopArmin Ronacherbefore adoption66a9344
lines 292–295why, one step back292293 # a nifty trick to enhance the error message if someone tried to call294 # the the loop without or with too many arguments.295 __call__ = loop; del loopadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 296–299why, one step back296297 @property298 def length(self):299 if self._length is None:Fixed a bug with the loop context of a for loop if the iterator passed has a volatile `__len__` like the listreverseiterator. `else` in inline if-expressions is optional now.Armin Ronacherbefore adoption547d0b6
lines 300–306why, one step back300 # if was not possible to get the length of the iterator when301 # the loop context was created (ie: iterating over a generator)302 # we have to convert the iterable into a sequence and use the303 # length of that.304 iterable = tuple(self._iterator)305 self._iterator = iter(iterable)306 self._length = len(iterable) + self.index0 + 1added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 307–314why, one step back307 return self._length308309 def __repr__(self):310 return '<%s %r/%r>' % (311 self.__class__.__name__,312 self.index,313 self.length314 )small refactoringArmin Ronacherbefore adoptioned1e0d4
lines 315–329why, one step back315316317class LoopContextIterator(object):318 """The iterator for a loop context."""319 __slots__ = ('context',)320321 def __init__(self, context):322 self.context = context323324 def __iter__(self):325 return self326327 def next(self):328 ctx = self.context329 ctx.index0 += 1Fixed a bug with the loop context of a for loop if the iterator passed has a volatile `__len__` like the listreverseiterator. `else` in inline if-expressions is optional now.Armin Ronacherbefore adoption547d0b6
line 330why, one step back330 return ctx._iterator.next(), ctxadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 331–347why, one step back331332333class Macro(object):334 """Wraps a macro."""335336 def __init__(self, environment, func, name, arguments, defaults,337 catch_kwargs, catch_varargs, caller):338 self._environment = environment339 self._func = func340 self._argument_count = len(arguments)341 self.name = name342 self.arguments = arguments343 self.defaults = defaults344 self.catch_kwargs = catch_kwargs345 self.catch_varargs = catch_varargs346 self.caller = caller347Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
line 348why, one step back348 @internalcodeadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 349–404why, one step back349 def __call__(self, *args, **kwargs):350 arguments = []351 for idx, name in enumerate(self.arguments):352 try:353 value = args[idx]354 except:355 try:356 value = kwargs.pop(name)357 except:358 try:359 value = self.defaults[idx - self._argument_count]360 except:361 value = self._environment.undefined(362 'parameter %r was not provided' % name, name=name)363 arguments.append(value)364365 # it's important that the order of these arguments does not change366 # if not also changed in the compiler's `function_scoping` method.367 # the order is caller, keyword arguments, positional arguments!368 if self.caller:369 caller = kwargs.pop('caller', None)370 if caller is None:371 caller = self._environment.undefined('No caller defined',372 name='caller')373 arguments.append(caller)374 if self.catch_kwargs:375 arguments.append(kwargs)376 elif kwargs:377 raise TypeError('macro %r takes no keyword argument %r' %378 (self.name, iter(kwargs).next()))379 if self.catch_varargs:380 arguments.append(args[self._argument_count:])381 elif len(args) > self._argument_count:382 raise TypeError('macro %r takes not more than %d argument(s)' %383 (self.name, len(self.arguments)))384 return self._func(*arguments)385386 def __repr__(self):387 return '<%s %s>' % (388 self.__class__.__name__,389 self.name is None and 'anonymous' or repr(self.name)390 )391392393class Undefined(object):394 """The default undefined type. This undefined type can be printed and395 iterated over, but every other access will raise an :exc:`UndefinedError`:396397 >>> foo = Undefined(name='foo')398 >>> str(foo)399 ''400 >>> not foo401 True402 >>> foo + 42403 Traceback (most recent call last):404 ...Added non-babel output mode to extract_from_ast, integreated jinja2 doctests directly into the py.test suite (ugh, that's an ugly hack)Armin Ronacherbefore adoptionabd3657
line 405why, one step back405 UndefinedError: 'foo' is undefinedadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 406why, one step back406 """documentation updateArmin Ronacherbefore adoption5cdc1ac
lines 407–408why, one step back407 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',408 '_undefined_exception')added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 409why, one step back409documentation updateArmin Ronacherbefore adoption5cdc1ac
line 410why, one step back410 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 411–413why, one step back411 self._undefined_hint = hint412 self._undefined_obj = obj413 self._undefined_name = namedocumentation updateArmin Ronacherbefore adoption5cdc1ac
line 414why, one step back414 self._undefined_exception = excadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 415why, one step back415Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97
line 416why, one step back416 @internalcodesome more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
lines 417–437why, one step back417 def _fail_with_undefined_error(self, *args, **kwargs):418 """Regular callback function for undefined objects that raises an419 `UndefinedError` on call.420 """421 if self._undefined_hint is None:422 if self._undefined_obj is None:423 hint = '%r is undefined' % self._undefined_name424 elif not isinstance(self._undefined_name, basestring):425 hint = '%r object has no element %r' % (426 self._undefined_obj.__class__.__name__,427 self._undefined_name428 )429 else:430 hint = '%r object has no attribute %r' % (431 self._undefined_obj.__class__.__name__,432 self._undefined_name433 )434 else:435 hint = self._undefined_hint436 raise self._undefined_exception(hint)437added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 438why, one step back438 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \Fixed a small bug with the undefined object: the error message on divisions with undefined objects was misleading.Armin Ronacherbefore adoption9efe081
line 439why, one step back439 __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 440–441why, one step back440 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \441 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \Fixed a small bug with the undefined object: the error message on divisions with undefined objects was misleading.Armin Ronacherbefore adoption9efe081
lines 442–443why, one step back442 __int__ = __float__ = __complex__ = __pow__ = __rpow__ = \443 _fail_with_undefined_erroradded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 444–445why, one step back444445 def __str__(self):Various cleanups and added custom cycler.Armin Ronacherbefore adoptionccae055
line 446why, one step back446 return unicode(self).encode('utf-8')added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 447–460why, one step back447448 def __unicode__(self):449 return u''450451 def __len__(self):452 return 0453454 def __iter__(self):455 if 0:456 yield None457458 def __nonzero__(self):459 return False460some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
lines 461–462why, one step back461 def __repr__(self):462 return 'Undefined'added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
line 463why, one step back463some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
line 464why, one step back464added author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 465–475why, one step back465class DebugUndefined(Undefined):466 """An undefined that returns the debug info when printed.467468 >>> foo = DebugUndefined(name='foo')469 >>> str(foo)470 '{{ foo }}'471 >>> not foo472 True473 >>> foo + 42474 Traceback (most recent call last):475 ...Added non-babel output mode to extract_from_ast, integreated jinja2 doctests directly into the py.test suite (ugh, that's an ugly hack)Armin Ronacherbefore adoptionabd3657
line 476why, one step back476 UndefinedError: 'foo' is undefinedadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 477–499why, one step back477 """478 __slots__ = ()479480 def __unicode__(self):481 if self._undefined_hint is None:482 if self._undefined_obj is None:483 return u'{{ %s }}' % self._undefined_name484 return '{{ no such element: %s[%r] }}' % (485 self._undefined_obj.__class__.__name__,486 self._undefined_name487 )488 return u'{{ undefined value printed: %s }}' % self._undefined_hint489490491class StrictUndefined(Undefined):492 """An undefined that barks on print and iteration as well as boolean493 tests and all kinds of comparisons. In other words: you can do nothing494 with it except checking if it's defined using the `defined` test.495496 >>> foo = StrictUndefined(name='foo')497 >>> str(foo)498 Traceback (most recent call last):499 ...Added non-babel output mode to extract_from_ast, integreated jinja2 doctests directly into the py.test suite (ugh, that's an ugly hack)Armin Ronacherbefore adoptionabd3657
line 500why, one step back500 UndefinedError: 'foo' is undefinedadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 501–503why, one step back501 >>> not foo502 Traceback (most recent call last):503 ...Added non-babel output mode to extract_from_ast, integreated jinja2 doctests directly into the py.test suite (ugh, that's an ugly hack)Armin Ronacherbefore adoptionabd3657
line 504why, one step back504 UndefinedError: 'foo' is undefinedadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 505–507why, one step back505 >>> foo + 42506 Traceback (most recent call last):507 ...Added non-babel output mode to extract_from_ast, integreated jinja2 doctests directly into the py.test suite (ugh, that's an ugly hack)Armin Ronacherbefore adoptionabd3657
line 508why, one step back508 UndefinedError: 'foo' is undefinedadded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 509–511why, one step back509 """510 __slots__ = ()511 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47
line 512why, one step back512 Undefined._fail_with_undefined_erroradded author information and fixed small off-by-one bugArmin Ronacherbefore adoptionb217886
lines 513–517why, one step back513514515# remove remaining slots attributes, after the metaclass did the magic they516# are unneeded and irritating as they contain wrong data for the subclasses.517del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__