blob: bb5d9fdb18160082d6122fe7457c7a6c99d611d5 [file] [log] [blame]
Armin Ronachere791c2a2008-04-07 18:39:54 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.runtime
4 ~~~~~~~~~~~~~~
5
6 Runtime helpers.
7
8 :copyright: Copyright 2008 by Armin Ronacher.
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, \
14 concat, MethodType, FunctionType
Armin Ronacherd1342312008-04-28 12:20:12 +020015from jinja2.exceptions import UndefinedError, TemplateRuntimeError
Armin Ronachere791c2a2008-04-07 18:39:54 +020016
17
Armin Ronacher2feed1d2008-04-26 16:26:52 +020018# these variables are exported to the template runtime
Armin Ronacher19cf9c22008-05-01 12:49:53 +020019__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
20 'TemplateRuntimeError', 'missing', 'concat', 'escape',
Armin Ronacherd1342312008-04-28 12:20:12 +020021 'markup_join', 'unicode_join']
Armin Ronacher0611e492008-04-25 23:44:14 +020022
Armin Ronacher9a0078d2008-08-13 18:24:17 +020023
Armin Ronacherce677102008-08-17 19:43:22 +020024#: the types we support for context functions
25_context_function_types = (FunctionType, MethodType)
Armin Ronacher24b65582008-05-26 13:35:58 +020026
Armin Ronacher0611e492008-04-25 23:44:14 +020027
Armin Ronacherdc02b642008-05-15 22:47:27 +020028def markup_join(seq):
Armin Ronacherd1342312008-04-28 12:20:12 +020029 """Concatenation that escapes if necessary and converts to unicode."""
30 buf = []
Armin Ronacherdc02b642008-05-15 22:47:27 +020031 iterator = imap(soft_unicode, seq)
Armin Ronacherd1342312008-04-28 12:20:12 +020032 for arg in iterator:
33 buf.append(arg)
34 if hasattr(arg, '__html__'):
35 return Markup(u'').join(chain(buf, iterator))
36 return concat(buf)
37
38
Armin Ronacherdc02b642008-05-15 22:47:27 +020039def unicode_join(seq):
Armin Ronacherd1342312008-04-28 12:20:12 +020040 """Simple args to unicode conversion and concatenation."""
Armin Ronacherdc02b642008-05-15 22:47:27 +020041 return concat(imap(unicode, seq))
Armin Ronacherd1342312008-04-28 12:20:12 +020042
43
Armin Ronacher19cf9c22008-05-01 12:49:53 +020044class Context(object):
Armin Ronacher7259c762008-04-30 13:03:59 +020045 """The template context holds the variables of a template. It stores the
46 values passed to the template and also the names the template exports.
47 Creating instances is neither supported nor useful as it's created
48 automatically at various stages of the template evaluation and should not
49 be created by hand.
Armin Ronacherc9705c22008-04-27 21:28:03 +020050
Armin Ronacher7259c762008-04-30 13:03:59 +020051 The context is immutable. Modifications on :attr:`parent` **must not**
52 happen and modifications on :attr:`vars` are allowed from generated
53 template code only. Template filters and global functions marked as
54 :func:`contextfunction`\s get the active context passed as first argument
55 and are allowed to access the context read-only.
56
57 The template context supports read only dict operations (`get`,
Armin Ronacherf35e2812008-05-06 16:04:10 +020058 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
59 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
60 method that doesn't fail with a `KeyError` but returns an
61 :class:`Undefined` object for missing variables.
Armin Ronacher9706fab2008-04-08 18:49:56 +020062 """
Armin Ronacher771c7502008-05-18 23:14:14 +020063 __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',
Armin Ronacherdcc217c2008-09-18 18:38:58 +020064 'blocks', '__weakref__')
Armin Ronachere791c2a2008-04-07 18:39:54 +020065
Armin Ronacher203bfcb2008-04-24 21:54:44 +020066 def __init__(self, environment, parent, name, blocks):
67 self.parent = parent
Armin Ronacher2feed1d2008-04-26 16:26:52 +020068 self.vars = vars = {}
Armin Ronacherc63243e2008-04-14 22:53:58 +020069 self.environment = environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020070 self.exported_vars = set()
Armin Ronacher68f77672008-04-17 11:50:39 +020071 self.name = name
Armin Ronacher203bfcb2008-04-24 21:54:44 +020072
Armin Ronacher203bfcb2008-04-24 21:54:44 +020073 # create the initial mapping of blocks. Whenever template inheritance
74 # takes place the runtime will update this mapping with the new blocks
75 # from the template.
Armin Ronacher75cfb862008-04-11 13:47:22 +020076 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
Armin Ronacherf059ec12008-04-11 22:21:00 +020077
Armin Ronacher203bfcb2008-04-24 21:54:44 +020078 def super(self, name, current):
Armin Ronacher62f8a292008-04-13 23:18:05 +020079 """Render a parent block."""
Armin Ronacherc9705c22008-04-27 21:28:03 +020080 try:
81 blocks = self.blocks[name]
Armin Ronacher83fbc0f2008-05-15 12:22:28 +020082 block = blocks[blocks.index(current) + 1]
Armin Ronacherc9705c22008-04-27 21:28:03 +020083 except LookupError:
Armin Ronacher9a822052008-04-17 18:44:07 +020084 return self.environment.undefined('there is no parent block '
Armin Ronacher19cf9c22008-05-01 12:49:53 +020085 'called %r.' % name,
86 name='super')
Armin Ronacherd1342312008-04-28 12:20:12 +020087 wrap = self.environment.autoescape and Markup or (lambda x: x)
Armin Ronacher83fbc0f2008-05-15 12:22:28 +020088 render = lambda: wrap(concat(block(self)))
Armin Ronacherc9705c22008-04-27 21:28:03 +020089 render.__name__ = render.name = name
90 return render
Armin Ronachere791c2a2008-04-07 18:39:54 +020091
Armin Ronacher53042292008-04-26 18:30:19 +020092 def get(self, key, default=None):
Armin Ronacher7259c762008-04-30 13:03:59 +020093 """Returns an item from the template context, if it doesn't exist
94 `default` is returned.
95 """
Armin Ronacherf35e2812008-05-06 16:04:10 +020096 try:
97 return self[key]
98 except KeyError:
99 return default
100
101 def resolve(self, key):
102 """Looks up a variable like `__getitem__` or `get` but returns an
103 :class:`Undefined` object with the name of the name looked up.
104 """
Armin Ronacher53042292008-04-26 18:30:19 +0200105 if key in self.vars:
106 return self.vars[key]
107 if key in self.parent:
108 return self.parent[key]
Armin Ronacherf35e2812008-05-06 16:04:10 +0200109 return self.environment.undefined(name=key)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200110
Armin Ronacher9706fab2008-04-08 18:49:56 +0200111 def get_exported(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200112 """Get a new dict with the exported variables."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200113 return dict((k, self.vars[k]) for k in self.exported_vars)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200114
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200115 def get_all(self):
Armin Ronacher7259c762008-04-30 13:03:59 +0200116 """Return a copy of the complete context as dict including the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200117 exported variables.
Armin Ronacher7259c762008-04-30 13:03:59 +0200118 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200119 return dict(self.parent, **self.vars)
120
Armin Ronacherfd310492008-05-25 00:16:51 +0200121 def call(__self, __obj, *args, **kwargs):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200122 """Call the callable with the arguments and keyword arguments
123 provided but inject the active context or environment as first
124 argument if the callable is a :func:`contextfunction` or
125 :func:`environmentfunction`.
126 """
Armin Ronacher24b65582008-05-26 13:35:58 +0200127 if __debug__:
128 __traceback_hide__ = True
129 if isinstance(__obj, _context_function_types):
130 if getattr(__obj, 'contextfunction', 0):
131 args = (__self,) + args
132 elif getattr(__obj, 'environmentfunction', 0):
133 args = (__self.environment,) + args
Armin Ronacherfd310492008-05-25 00:16:51 +0200134 return __obj(*args, **kwargs)
135
Armin Ronacherf35e2812008-05-06 16:04:10 +0200136 def _all(meth):
Armin Ronachere9411b42008-05-15 16:22:07 +0200137 proxy = lambda self: getattr(self.get_all(), meth)()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200138 proxy.__doc__ = getattr(dict, meth).__doc__
139 proxy.__name__ = meth
140 return proxy
141
142 keys = _all('keys')
143 values = _all('values')
144 items = _all('items')
145 iterkeys = _all('iterkeys')
146 itervalues = _all('itervalues')
147 iteritems = _all('iteritems')
148 del _all
149
Armin Ronacherb5124e62008-04-25 00:36:14 +0200150 def __contains__(self, name):
151 return name in self.vars or name in self.parent
152
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200153 def __getitem__(self, key):
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200154 """Lookup a variable or raise `KeyError` if the variable is
155 undefined.
156 """
157 item = self.resolve(key)
158 if isinstance(item, Undefined):
159 raise KeyError(key)
160 return item
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200161
Armin Ronacherf059ec12008-04-11 22:21:00 +0200162 def __repr__(self):
163 return '<%s %s of %r>' % (
164 self.__class__.__name__,
Armin Ronacher963f97d2008-04-25 11:44:59 +0200165 repr(self.get_all()),
Armin Ronacher68f77672008-04-17 11:50:39 +0200166 self.name
Armin Ronacherf059ec12008-04-11 22:21:00 +0200167 )
168
169
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200170# register the context as mutable mapping if possible
171try:
172 from collections import MutableMapping
173 MutableMapping.register(Context)
174except ImportError:
175 pass
176
177
Armin Ronacherc9705c22008-04-27 21:28:03 +0200178class TemplateReference(object):
179 """The `self` in templates."""
Armin Ronacher62f8a292008-04-13 23:18:05 +0200180
Armin Ronacherc9705c22008-04-27 21:28:03 +0200181 def __init__(self, context):
182 self.__context = context
Armin Ronacher62f8a292008-04-13 23:18:05 +0200183
Armin Ronacherc9705c22008-04-27 21:28:03 +0200184 def __getitem__(self, name):
Armin Ronacher6df604e2008-05-23 22:18:38 +0200185 func = self.__context.blocks[name][0]
Armin Ronacherd1342312008-04-28 12:20:12 +0200186 wrap = self.__context.environment.autoescape and \
187 Markup or (lambda x: x)
188 render = lambda: wrap(concat(func(self.__context)))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200189 render.__name__ = render.name = name
190 return render
Armin Ronacher62f8a292008-04-13 23:18:05 +0200191
192 def __repr__(self):
193 return '<%s %r>' % (
194 self.__class__.__name__,
Armin Ronacherc9705c22008-04-27 21:28:03 +0200195 self._context.name
Armin Ronacher62f8a292008-04-13 23:18:05 +0200196 )
197
198
Armin Ronacher32a910f2008-04-26 23:21:03 +0200199class LoopContext(object):
200 """A loop context for dynamic iteration."""
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200201
Armin Ronacher547d0b62008-07-04 16:35:10 +0200202 def __init__(self, iterable, recurse=None):
203 self._iterator = iter(iterable)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200204 self._recurse = recurse
Armin Ronacher32a910f2008-04-26 23:21:03 +0200205 self.index0 = -1
Armin Ronacher547d0b62008-07-04 16:35:10 +0200206
207 # try to get the length of the iterable early. This must be done
208 # here because there are some broken iterators around where there
209 # __len__ is the number of iterations left (i'm looking at your
210 # listreverseiterator!).
211 try:
212 self._length = len(iterable)
213 except (TypeError, AttributeError):
214 self._length = None
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200215
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200216 def cycle(self, *args):
Armin Ronachered1e0d42008-05-18 20:25:28 +0200217 """Cycles among the arguments with the current loop index."""
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200218 if not args:
219 raise TypeError('no items for cycling given')
220 return args[self.index0 % len(args)]
221
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200222 first = property(lambda x: x.index0 == 0)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200223 last = property(lambda x: x.index0 + 1 == x.length)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200224 index = property(lambda x: x.index0 + 1)
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200225 revindex = property(lambda x: x.length - x.index0)
226 revindex0 = property(lambda x: x.length - x.index)
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200227
228 def __len__(self):
229 return self.length
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200230
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200231 def __iter__(self):
Armin Ronachered1e0d42008-05-18 20:25:28 +0200232 return LoopContextIterator(self)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200233
Armin Ronacher66a93442008-05-11 23:42:19 +0200234 def loop(self, iterable):
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200235 if self._recurse is None:
236 raise TypeError('Tried to call non recursive loop. Maybe you '
Armin Ronacher66a93442008-05-11 23:42:19 +0200237 "forgot the 'recursive' modifier.")
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200238 return self._recurse(iterable, self._recurse)
239
Armin Ronacher66a93442008-05-11 23:42:19 +0200240 # a nifty trick to enhance the error message if someone tried to call
241 # the the loop without or with too many arguments.
242 __call__ = loop; del loop
243
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200244 @property
245 def length(self):
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200246 if self._length is None:
Armin Ronacher547d0b62008-07-04 16:35:10 +0200247 # if was not possible to get the length of the iterator when
248 # the loop context was created (ie: iterating over a generator)
249 # we have to convert the iterable into a sequence and use the
250 # length of that.
251 iterable = tuple(self._iterator)
252 self._iterator = iter(iterable)
253 self._length = len(iterable) + self.index0 + 1
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200254 return self._length
255
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200256 def __repr__(self):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200257 return '<%s %r/%r>' % (
258 self.__class__.__name__,
259 self.index,
260 self.length
261 )
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200262
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200263
Armin Ronachered1e0d42008-05-18 20:25:28 +0200264class LoopContextIterator(object):
265 """The iterator for a loop context."""
266 __slots__ = ('context',)
267
268 def __init__(self, context):
269 self.context = context
270
271 def __iter__(self):
272 return self
273
274 def next(self):
275 ctx = self.context
276 ctx.index0 += 1
Armin Ronacher547d0b62008-07-04 16:35:10 +0200277 return ctx._iterator.next(), ctx
Armin Ronachered1e0d42008-05-18 20:25:28 +0200278
279
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200280class Macro(object):
Armin Ronacherd55ab532008-04-09 16:13:39 +0200281 """Wraps a macro."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200282
Armin Ronacher963f97d2008-04-25 11:44:59 +0200283 def __init__(self, environment, func, name, arguments, defaults,
284 catch_kwargs, catch_varargs, caller):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200285 self._environment = environment
Armin Ronacher71082072008-04-12 14:19:36 +0200286 self._func = func
Armin Ronacherd84ec462008-04-29 13:43:16 +0200287 self._argument_count = len(arguments)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200288 self.name = name
289 self.arguments = arguments
290 self.defaults = defaults
Armin Ronacher963f97d2008-04-25 11:44:59 +0200291 self.catch_kwargs = catch_kwargs
292 self.catch_varargs = catch_varargs
Armin Ronacher71082072008-04-12 14:19:36 +0200293 self.caller = caller
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200294
295 def __call__(self, *args, **kwargs):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200296 arguments = []
Armin Ronacher9706fab2008-04-08 18:49:56 +0200297 for idx, name in enumerate(self.arguments):
298 try:
299 value = args[idx]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200300 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200301 try:
302 value = kwargs.pop(name)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200303 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200304 try:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200305 value = self.defaults[idx - self._argument_count]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200306 except:
Armin Ronacher9a822052008-04-17 18:44:07 +0200307 value = self._environment.undefined(
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200308 'parameter %r was not provided' % name, name=name)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200309 arguments.append(value)
310
311 # it's important that the order of these arguments does not change
312 # if not also changed in the compiler's `function_scoping` method.
313 # the order is caller, keyword arguments, positional arguments!
Armin Ronacher71082072008-04-12 14:19:36 +0200314 if self.caller:
315 caller = kwargs.pop('caller', None)
316 if caller is None:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200317 caller = self._environment.undefined('No caller defined',
318 name='caller')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200319 arguments.append(caller)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200320 if self.catch_kwargs:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200321 arguments.append(kwargs)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200322 elif kwargs:
323 raise TypeError('macro %r takes no keyword argument %r' %
324 (self.name, iter(kwargs).next()))
325 if self.catch_varargs:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200326 arguments.append(args[self._argument_count:])
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200327 elif len(args) > self._argument_count:
328 raise TypeError('macro %r takes not more than %d argument(s)' %
329 (self.name, len(self.arguments)))
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200330 return self._func(*arguments)
Armin Ronacher71082072008-04-12 14:19:36 +0200331
332 def __repr__(self):
333 return '<%s %s>' % (
334 self.__class__.__name__,
335 self.name is None and 'anonymous' or repr(self.name)
336 )
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200337
338
339class Undefined(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200340 """The default undefined type. This undefined type can be printed and
341 iterated over, but every other access will raise an :exc:`UndefinedError`:
342
343 >>> foo = Undefined(name='foo')
344 >>> str(foo)
345 ''
346 >>> not foo
347 True
348 >>> foo + 42
349 Traceback (most recent call last):
350 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200351 UndefinedError: 'foo' is undefined
Armin Ronacherc63243e2008-04-14 22:53:58 +0200352 """
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200353 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
354 '_undefined_exception')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200355
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200356 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
Armin Ronacher9a822052008-04-17 18:44:07 +0200357 self._undefined_hint = hint
358 self._undefined_obj = obj
359 self._undefined_name = name
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200360 self._undefined_exception = exc
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200361
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200362 def _fail_with_undefined_error(self, *args, **kwargs):
363 """Regular callback function for undefined objects that raises an
364 `UndefinedError` on call.
365 """
366 if self._undefined_hint is None:
367 if self._undefined_obj is None:
368 hint = '%r is undefined' % self._undefined_name
369 elif not isinstance(self._undefined_name, basestring):
370 hint = '%r object has no element %r' % (
371 self._undefined_obj.__class__.__name__,
372 self._undefined_name
373 )
374 else:
375 hint = '%r object has no attribute %r' % (
376 self._undefined_obj.__class__.__name__,
377 self._undefined_name
378 )
379 else:
380 hint = self._undefined_hint
381 raise self._undefined_exception(hint)
382
Armin Ronacherc63243e2008-04-14 22:53:58 +0200383 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
384 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
385 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
Armin Ronacher53042292008-04-26 18:30:19 +0200386 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200387 __int__ = __float__ = __complex__ = _fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200388
389 def __str__(self):
390 return self.__unicode__().encode('utf-8')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200391
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200392 def __unicode__(self):
393 return u''
394
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200395 def __len__(self):
396 return 0
397
398 def __iter__(self):
399 if 0:
400 yield None
Armin Ronacherc63243e2008-04-14 22:53:58 +0200401
402 def __nonzero__(self):
403 return False
404
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200405 def __repr__(self):
406 return 'Undefined'
407
Armin Ronacherc63243e2008-04-14 22:53:58 +0200408
409class DebugUndefined(Undefined):
Armin Ronacherd1342312008-04-28 12:20:12 +0200410 """An undefined that returns the debug info when printed.
411
412 >>> foo = DebugUndefined(name='foo')
413 >>> str(foo)
414 '{{ foo }}'
415 >>> not foo
416 True
417 >>> foo + 42
418 Traceback (most recent call last):
419 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200420 UndefinedError: 'foo' is undefined
Armin Ronacherd1342312008-04-28 12:20:12 +0200421 """
Armin Ronacher53042292008-04-26 18:30:19 +0200422 __slots__ = ()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200423
424 def __unicode__(self):
Armin Ronacher9a822052008-04-17 18:44:07 +0200425 if self._undefined_hint is None:
426 if self._undefined_obj is None:
427 return u'{{ %s }}' % self._undefined_name
428 return '{{ no such element: %s[%r] }}' % (
429 self._undefined_obj.__class__.__name__,
430 self._undefined_name
431 )
432 return u'{{ undefined value printed: %s }}' % self._undefined_hint
Armin Ronacherc63243e2008-04-14 22:53:58 +0200433
434
435class StrictUndefined(Undefined):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200436 """An undefined that barks on print and iteration as well as boolean
Armin Ronacher53042292008-04-26 18:30:19 +0200437 tests and all kinds of comparisons. In other words: you can do nothing
438 with it except checking if it's defined using the `defined` test.
Armin Ronacherd1342312008-04-28 12:20:12 +0200439
440 >>> foo = StrictUndefined(name='foo')
441 >>> str(foo)
442 Traceback (most recent call last):
443 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200444 UndefinedError: 'foo' is undefined
Armin Ronacherd1342312008-04-28 12:20:12 +0200445 >>> not foo
446 Traceback (most recent call last):
447 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200448 UndefinedError: 'foo' is undefined
Armin Ronacherd1342312008-04-28 12:20:12 +0200449 >>> foo + 42
450 Traceback (most recent call last):
451 ...
Armin Ronacherabd36572008-06-27 08:45:19 +0200452 UndefinedError: 'foo' is undefined
Priit Laes4149a0e2008-04-17 19:04:44 +0200453 """
Armin Ronacher53042292008-04-26 18:30:19 +0200454 __slots__ = ()
455 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200456 Undefined._fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200457
Armin Ronacher53042292008-04-26 18:30:19 +0200458
459# remove remaining slots attributes, after the metaclass did the magic they
460# are unneeded and irritating as they contain wrong data for the subclasses.
461del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__