blob: 669ff2100faf9c8a8b64584c656eef03f5501f6e [file] [log] [blame]
Armin Ronachere791c2a2008-04-07 18:39:54 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.runtime
4 ~~~~~~~~~~~~~~
5
6 Runtime helpers.
7
Armin Ronacher62ccd1b2009-01-04 14:26:19 +01008 :copyright: (c) 2009 by the Jinja Team.
Armin Ronacherd7764372008-07-15 00:11:14 +02009 :license: BSD.
Armin Ronachere791c2a2008-04-07 18:39:54 +020010"""
Armin Ronacher1ae4fdf2008-04-28 20:49:51 +020011import sys
Armin Ronacherd1342312008-04-28 12:20:12 +020012from itertools import chain, imap
Armin Ronacherce677102008-08-17 19:43:22 +020013from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
Armin Ronacherd416a972009-02-24 22:58:00 +010014 concat, MethodType, FunctionType, internalcode
Armin Ronacher37f58ce2008-12-27 13:10:38 +010015from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
16 TemplateNotFound
Armin Ronachere791c2a2008-04-07 18:39:54 +020017
18
Armin Ronacher2feed1d2008-04-26 16:26:52 +020019# these variables are exported to the template runtime
Armin Ronacher74a0cd92009-02-19 15:56:53 +010020__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
Armin Ronacher19cf9c22008-05-01 12:49:53 +020021 'TemplateRuntimeError', 'missing', 'concat', 'escape',
Armin Ronacher37f58ce2008-12-27 13:10:38 +010022 'markup_join', 'unicode_join', 'TemplateNotFound']
Armin Ronacher0611e492008-04-25 23:44:14 +020023
Armin Ronacher9a0078d2008-08-13 18:24:17 +020024
Armin Ronacherce677102008-08-17 19:43:22 +020025#: the types we support for context functions
26_context_function_types = (FunctionType, MethodType)
Armin Ronacher24b65582008-05-26 13:35:58 +020027
Armin Ronacher0611e492008-04-25 23:44:14 +020028
Armin Ronacherdc02b642008-05-15 22:47:27 +020029def markup_join(seq):
Armin Ronacherd1342312008-04-28 12:20:12 +020030 """Concatenation that escapes if necessary and converts to unicode."""
31 buf = []
Armin Ronacherdc02b642008-05-15 22:47:27 +020032 iterator = imap(soft_unicode, seq)
Armin Ronacherd1342312008-04-28 12:20:12 +020033 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)
38
39
Armin Ronacherdc02b642008-05-15 22:47:27 +020040def unicode_join(seq):
Armin Ronacherd1342312008-04-28 12:20:12 +020041 """Simple args to unicode conversion and concatenation."""
Armin Ronacherdc02b642008-05-15 22:47:27 +020042 return concat(imap(unicode, seq))
Armin Ronacherd1342312008-04-28 12:20:12 +020043
44
Armin Ronacher74a0cd92009-02-19 15:56:53 +010045def 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 = vars
52 else:
53 parent = dict(globals or (), **vars)
54 if locals:
55 # if the parent is shared a copy should be created because
56 # we don't want to modify the dict passed
57 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:]] = value
62 return Context(environment, parent, template_name, blocks)
63
64
65class TemplateReference(object):
66 """The `self` in templates."""
67
68 def __init__(self, context):
69 self.__context = context
70
71 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)
76
77 def __repr__(self):
78 return '<%s %r>' % (
79 self.__class__.__name__,
80 self.__context.name
81 )
82
83
Armin Ronacher19cf9c22008-05-01 12:49:53 +020084class Context(object):
Armin Ronacher7259c762008-04-30 13:03:59 +020085 """The template context holds the variables of a template. It stores the
86 values passed to the template and also the names the template exports.
87 Creating instances is neither supported nor useful as it's created
88 automatically at various stages of the template evaluation and should not
89 be created by hand.
Armin Ronacherc9705c22008-04-27 21:28:03 +020090
Armin Ronacher7259c762008-04-30 13:03:59 +020091 The context is immutable. Modifications on :attr:`parent` **must not**
92 happen and modifications on :attr:`vars` are allowed from generated
93 template code only. Template filters and global functions marked as
94 :func:`contextfunction`\s get the active context passed as first argument
95 and are allowed to access the context read-only.
96
97 The template context supports read only dict operations (`get`,
Armin Ronacherf35e2812008-05-06 16:04:10 +020098 `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 an
101 :class:`Undefined` object for missing variables.
Armin Ronacher9706fab2008-04-08 18:49:56 +0200102 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200103 __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',
Armin Ronacherdcc217c2008-09-18 18:38:58 +0200104 'blocks', '__weakref__')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200105
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200106 def __init__(self, environment, parent, name, blocks):
107 self.parent = parent
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200108 self.vars = vars = {}
Armin Ronacherc63243e2008-04-14 22:53:58 +0200109 self.environment = environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200110 self.exported_vars = set()
Armin Ronacher68f77672008-04-17 11:50:39 +0200111 self.name = name
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200112
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200113 # create the initial mapping of blocks. Whenever template inheritance
114 # takes place the runtime will update this mapping with the new blocks
115 # from the template.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200116 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
Armin Ronacherf059ec12008-04-11 22:21:00 +0200117
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200118 def super(self, name, current):
Armin Ronacher62f8a292008-04-13 23:18:05 +0200119 """Render a parent block."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200120 try:
121 blocks = self.blocks[name]
Armin Ronacherc347ed02008-09-20 12:04:53 +0200122 index = blocks.index(current) + 1
123 blocks[index]
Armin Ronacherc9705c22008-04-27 21:28:03 +0200124 except LookupError:
Armin Ronacher9a822052008-04-17 18:44:07 +0200125 return self.environment.undefined('there is no parent block '
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200126 'called %r.' % name,
127 name='super')
Armin Ronacherc347ed02008-09-20 12:04:53 +0200128 return BlockReference(name, self, blocks, index)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200129
Armin Ronacher53042292008-04-26 18:30:19 +0200130 def get(self, key, default=None):
Armin Ronacher7259c762008-04-30 13:03:59 +0200131 """Returns an item from the template context, if it doesn't exist
132 `default` is returned.
133 """
Armin Ronacherf35e2812008-05-06 16:04:10 +0200134 try:
135 return self[key]
136 except KeyError:
137 return default
138
139 def resolve(self, key):
140 """Looks up a variable like `__getitem__` or `get` but returns an
141 :class:`Undefined` object with the name of the name looked up.
142 """
Armin Ronacher53042292008-04-26 18:30:19 +0200143 if key in self.vars:
144 return self.vars[key]
145 if key in self.parent:
146 return self.parent[key]
Armin Ronacherf35e2812008-05-06 16:04:10 +0200147 return self.environment.undefined(name=key)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200148
Armin Ronacher9706fab2008-04-08 18:49:56 +0200149 def get_exported(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200150 """Get a new dict with the exported variables."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200151 return dict((k, self.vars[k]) for k in self.exported_vars)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200152
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200153 def get_all(self):
Armin Ronacher7259c762008-04-30 13:03:59 +0200154 """Return a copy of the complete context as dict including the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200155 exported variables.
Armin Ronacher7259c762008-04-30 13:03:59 +0200156 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200157 return dict(self.parent, **self.vars)
158
Armin Ronacherd416a972009-02-24 22:58:00 +0100159 @internalcode
Armin Ronacherfd310492008-05-25 00:16:51 +0200160 def call(__self, __obj, *args, **kwargs):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200161 """Call the callable with the arguments and keyword arguments
162 provided but inject the active context or environment as first
163 argument if the callable is a :func:`contextfunction` or
164 :func:`environmentfunction`.
165 """
Armin Ronacher24b65582008-05-26 13:35:58 +0200166 if __debug__:
167 __traceback_hide__ = True
168 if isinstance(__obj, _context_function_types):
169 if getattr(__obj, 'contextfunction', 0):
170 args = (__self,) + args
171 elif getattr(__obj, 'environmentfunction', 0):
172 args = (__self.environment,) + args
Armin Ronacherfd310492008-05-25 00:16:51 +0200173 return __obj(*args, **kwargs)
174
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100175 def derived(self, locals=None):
176 """Internal helper function to create a derived context."""
Armin Ronacher3f1d8f12009-02-19 16:11:11 +0100177 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 context
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100181
Armin Ronacherf35e2812008-05-06 16:04:10 +0200182 def _all(meth):
Armin Ronachere9411b42008-05-15 16:22:07 +0200183 proxy = lambda self: getattr(self.get_all(), meth)()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200184 proxy.__doc__ = getattr(dict, meth).__doc__
185 proxy.__name__ = meth
186 return proxy
187
188 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 _all
195
Armin Ronacherb5124e62008-04-25 00:36:14 +0200196 def __contains__(self, name):
197 return name in self.vars or name in self.parent
198
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200199 def __getitem__(self, key):
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200200 """Lookup a variable or raise `KeyError` if the variable is
201 undefined.
202 """
203 item = self.resolve(key)
204 if isinstance(item, Undefined):
205 raise KeyError(key)
206 return item
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200207
Armin Ronacherf059ec12008-04-11 22:21:00 +0200208 def __repr__(self):
209 return '<%s %s of %r>' % (
210 self.__class__.__name__,
Armin Ronacher963f97d2008-04-25 11:44:59 +0200211 repr(self.get_all()),
Armin Ronacher68f77672008-04-17 11:50:39 +0200212 self.name
Armin Ronacherf059ec12008-04-11 22:21:00 +0200213 )
214
215
Armin Ronacherccae0552008-10-05 23:08:58 +0200216# register the context as mapping if possible
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200217try:
Armin Ronacherccae0552008-10-05 23:08:58 +0200218 from collections import Mapping
219 Mapping.register(Context)
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200220except ImportError:
221 pass
222
223
Armin Ronacherc347ed02008-09-20 12:04:53 +0200224class BlockReference(object):
225 """One block on a template reference."""
226
227 def __init__(self, name, context, stack, depth):
228 self.name = name
229 self._context = context
230 self._stack = stack
231 self._depth = depth
232
233 @property
234 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)
242
Armin Ronacherd416a972009-02-24 22:58:00 +0100243 @internalcode
Armin Ronacherc347ed02008-09-20 12:04:53 +0200244 def __call__(self):
245 rv = concat(self._stack[self._depth](self._context))
246 if self._context.environment.autoescape:
247 rv = Markup(rv)
248 return rv
249
250
Armin Ronacher32a910f2008-04-26 23:21:03 +0200251class LoopContext(object):
252 """A loop context for dynamic iteration."""
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200253
Armin Ronacher547d0b62008-07-04 16:35:10 +0200254 def __init__(self, iterable, recurse=None):
255 self._iterator = iter(iterable)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200256 self._recurse = recurse
Armin Ronacher32a910f2008-04-26 23:21:03 +0200257 self.index0 = -1
Armin Ronacher547d0b62008-07-04 16:35:10 +0200258
259 # try to get the length of the iterable early. This must be done
260 # here because there are some broken iterators around where there
261 # __len__ is the number of iterations left (i'm looking at your
262 # listreverseiterator!).
263 try:
264 self._length = len(iterable)
265 except (TypeError, AttributeError):
266 self._length = None
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200267
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200268 def cycle(self, *args):
Armin Ronachered1e0d42008-05-18 20:25:28 +0200269 """Cycles among the arguments with the current loop index."""
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200270 if not args:
271 raise TypeError('no items for cycling given')
272 return args[self.index0 % len(args)]
273
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200274 first = property(lambda x: x.index0 == 0)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200275 last = property(lambda x: x.index0 + 1 == x.length)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200276 index = property(lambda x: x.index0 + 1)
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200277 revindex = property(lambda x: x.length - x.index0)
278 revindex0 = property(lambda x: x.length - x.index)
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200279
280 def __len__(self):
281 return self.length
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200282
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200283 def __iter__(self):
Armin Ronachered1e0d42008-05-18 20:25:28 +0200284 return LoopContextIterator(self)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200285
Armin Ronacherd416a972009-02-24 22:58:00 +0100286 @internalcode
Armin Ronacher66a93442008-05-11 23:42:19 +0200287 def loop(self, iterable):
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200288 if self._recurse is None:
289 raise TypeError('Tried to call non recursive loop. Maybe you '
Armin Ronacher66a93442008-05-11 23:42:19 +0200290 "forgot the 'recursive' modifier.")
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200291 return self._recurse(iterable, self._recurse)
292
Armin Ronacher66a93442008-05-11 23:42:19 +0200293 # a nifty trick to enhance the error message if someone tried to call
294 # the the loop without or with too many arguments.
295 __call__ = loop; del loop
296
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200297 @property
298 def length(self):
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200299 if self._length is None:
Armin Ronacher547d0b62008-07-04 16:35:10 +0200300 # if was not possible to get the length of the iterator when
301 # the loop context was created (ie: iterating over a generator)
302 # we have to convert the iterable into a sequence and use the
303 # length of that.
304 iterable = tuple(self._iterator)
305 self._iterator = iter(iterable)
306 self._length = len(iterable) + self.index0 + 1
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200307 return self._length
308
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200309 def __repr__(self):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200310 return '<%s %r/%r>' % (
311 self.__class__.__name__,
312 self.index,
313 self.length
314 )
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200315
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200316
Armin Ronachered1e0d42008-05-18 20:25:28 +0200317class LoopContextIterator(object):
318 """The iterator for a loop context."""
319 __slots__ = ('context',)
320
321 def __init__(self, context):
322 self.context = context
323
324 def __iter__(self):
325 return self
326
327 def next(self):
328 ctx = self.context
329 ctx.index0 += 1
Armin Ronacher547d0b62008-07-04 16:35:10 +0200330 return ctx._iterator.next(), ctx
Armin Ronachered1e0d42008-05-18 20:25:28 +0200331
332
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200333class Macro(object):
Armin Ronacherd55ab532008-04-09 16:13:39 +0200334 """Wraps a macro."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200335
Armin Ronacher963f97d2008-04-25 11:44:59 +0200336 def __init__(self, environment, func, name, arguments, defaults,
337 catch_kwargs, catch_varargs, caller):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200338 self._environment = environment
Armin Ronacher71082072008-04-12 14:19:36 +0200339 self._func = func
Armin Ronacherd84ec462008-04-29 13:43:16 +0200340 self._argument_count = len(arguments)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200341 self.name = name
342 self.arguments = arguments
343 self.defaults = defaults
Armin Ronacher963f97d2008-04-25 11:44:59 +0200344 self.catch_kwargs = catch_kwargs
345 self.catch_varargs = catch_varargs
Armin Ronacher71082072008-04-12 14:19:36 +0200346 self.caller = caller
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200347
Armin Ronacherd416a972009-02-24 22:58:00 +0100348 @internalcode
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200349 def __call__(self, *args, **kwargs):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200350 arguments = []
Armin Ronacher9706fab2008-04-08 18:49:56 +0200351 for idx, name in enumerate(self.arguments):
352 try:
353 value = args[idx]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200354 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200355 try:
356 value = kwargs.pop(name)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200357 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200358 try:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200359 value = self.defaults[idx - self._argument_count]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200360 except:
Armin Ronacher9a822052008-04-17 18:44:07 +0200361 value = self._environment.undefined(
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200362 'parameter %r was not provided' % name, name=name)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200363 arguments.append(value)
364
365 # it's important that the order of these arguments does not change
366 # if not also changed in the compiler's `function_scoping` method.
367 # the order is caller, keyword arguments, positional arguments!
Armin Ronacher71082072008-04-12 14:19:36 +0200368 if self.caller:
369 caller = kwargs.pop('caller', None)
370 if caller is None:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200371 caller = self._environment.undefined('No caller defined',
372 name='caller')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200373 arguments.append(caller)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200374 if self.catch_kwargs:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200375 arguments.append(kwargs)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200376 elif kwargs:
377 raise TypeError('macro %r takes no keyword argument %r' %
378 (self.name, iter(kwargs).next()))
379 if self.catch_varargs:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200380 arguments.append(args[self._argument_count:])
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200381 elif len(args) > self._argument_count:
382 raise TypeError('macro %r takes not more than %d argument(s)' %
383 (self.name, len(self.arguments)))
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200384 return self._func(*arguments)
Armin Ronacher71082072008-04-12 14:19:36 +0200385
386 def __repr__(self):
387 return '<%s %s>' % (
388 self.__class__.__name__,
389 self.name is None and 'anonymous' or repr(self.name)
390 )
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200391
392
393class Undefined(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200394 """The default undefined type. This undefined type can be printed and
395 iterated over, but every other access will raise an :exc:`UndefinedError`:
396
397 >>> foo = Undefined(name='foo')
398 >>> str(foo)
399 ''
400 >>> not foo
401 True
402 >>> foo + 42
403 Traceback (most recent call last):
404 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200405 UndefinedError: 'foo' is undefined
Armin Ronacherc63243e2008-04-14 22:53:58 +0200406 """
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200407 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
408 '_undefined_exception')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200409
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200410 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
Armin Ronacher9a822052008-04-17 18:44:07 +0200411 self._undefined_hint = hint
412 self._undefined_obj = obj
413 self._undefined_name = name
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200414 self._undefined_exception = exc
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200415
Armin Ronacherd416a972009-02-24 22:58:00 +0100416 @internalcode
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200417 def _fail_with_undefined_error(self, *args, **kwargs):
418 """Regular callback function for undefined objects that raises an
419 `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_name
424 elif not isinstance(self._undefined_name, basestring):
425 hint = '%r object has no element %r' % (
426 self._undefined_obj.__class__.__name__,
427 self._undefined_name
428 )
429 else:
430 hint = '%r object has no attribute %r' % (
431 self._undefined_obj.__class__.__name__,
432 self._undefined_name
433 )
434 else:
435 hint = self._undefined_hint
436 raise self._undefined_exception(hint)
437
Armin Ronacherc63243e2008-04-14 22:53:58 +0200438 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
Armin Ronacher9efe0812008-11-02 12:22:00 +0100439 __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
Armin Ronacherc63243e2008-04-14 22:53:58 +0200440 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
Armin Ronacher53042292008-04-26 18:30:19 +0200441 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
Armin Ronacher9efe0812008-11-02 12:22:00 +0100442 __int__ = __float__ = __complex__ = __pow__ = __rpow__ = \
443 _fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200444
445 def __str__(self):
Armin Ronacherccae0552008-10-05 23:08:58 +0200446 return unicode(self).encode('utf-8')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200447
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200448 def __unicode__(self):
449 return u''
450
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200451 def __len__(self):
452 return 0
453
454 def __iter__(self):
455 if 0:
456 yield None
Armin Ronacherc63243e2008-04-14 22:53:58 +0200457
458 def __nonzero__(self):
459 return False
460
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200461 def __repr__(self):
462 return 'Undefined'
463
Armin Ronacherc63243e2008-04-14 22:53:58 +0200464
465class DebugUndefined(Undefined):
Armin Ronacherd1342312008-04-28 12:20:12 +0200466 """An undefined that returns the debug info when printed.
467
468 >>> foo = DebugUndefined(name='foo')
469 >>> str(foo)
470 '{{ foo }}'
471 >>> not foo
472 True
473 >>> foo + 42
474 Traceback (most recent call last):
475 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200476 UndefinedError: 'foo' is undefined
Armin Ronacherd1342312008-04-28 12:20:12 +0200477 """
Armin Ronacher53042292008-04-26 18:30:19 +0200478 __slots__ = ()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200479
480 def __unicode__(self):
Armin Ronacher9a822052008-04-17 18:44:07 +0200481 if self._undefined_hint is None:
482 if self._undefined_obj is None:
483 return u'{{ %s }}' % self._undefined_name
484 return '{{ no such element: %s[%r] }}' % (
485 self._undefined_obj.__class__.__name__,
486 self._undefined_name
487 )
488 return u'{{ undefined value printed: %s }}' % self._undefined_hint
Armin Ronacherc63243e2008-04-14 22:53:58 +0200489
490
491class StrictUndefined(Undefined):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200492 """An undefined that barks on print and iteration as well as boolean
Armin Ronacher53042292008-04-26 18:30:19 +0200493 tests and all kinds of comparisons. In other words: you can do nothing
494 with it except checking if it's defined using the `defined` test.
Armin Ronacherd1342312008-04-28 12:20:12 +0200495
496 >>> foo = StrictUndefined(name='foo')
497 >>> str(foo)
498 Traceback (most recent call last):
499 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200500 UndefinedError: 'foo' is undefined
Armin Ronacherd1342312008-04-28 12:20:12 +0200501 >>> not foo
502 Traceback (most recent call last):
503 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200504 UndefinedError: 'foo' is undefined
Armin Ronacherd1342312008-04-28 12:20:12 +0200505 >>> foo + 42
506 Traceback (most recent call last):
507 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200508 UndefinedError: 'foo' is undefined
Priit Laes4149a0e2008-04-17 19:04:44 +0200509 """
Armin Ronacher53042292008-04-26 18:30:19 +0200510 __slots__ = ()
511 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200512 Undefined._fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200513
Armin Ronacher53042292008-04-26 18:30:19 +0200514
515# remove remaining slots attributes, after the metaclass did the magic they
516# are unneeded and irritating as they contain wrong data for the subclasses.
517del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__