Undefined Types
These classes can be used as undefined types. The Environment
constructor takes an undefined parameter that can be one of those classesor a custom subclass of Undefined
. Whenever the template engine isunable to look up a name or access an attribute one of those objects iscreated and returned. Some operations on undefined values are then allowed,others fail.
The closest to regular Python behavior is the StrictUndefined whichdisallows all operations beside testing if it’s an undefined object.
- class
jinja2.
Undefined
- The default undefined type. This undefined type can be printed anditerated over, but every other access will raise an
jinja2.exceptions.UndefinedError
:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
_undefined_hint
Either None or an unicode string with the error message forthe undefined object.
Either None or the owner object that caused the undefined objectto be created (for example because an attribute does not exist).
The name for the undefined variable / attribute or just _None_if no such information exists.
The exception that the undefined object wants to raise. Thisis usually one of
UndefinedError
orSecurityError
.- When called with any arguments this method raises
_undefined_exception
with an error message generatedfrom the undefined hints stored on the undefined object.
>>> foo = DebugUndefined(name='foo')
>>> str(foo)
'{{ foo }}'
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
- class
jinja2.
StrictUndefined
- An undefined that barks on print and iteration as well as booleantests and all kinds of comparisons. In other words: you can do nothingwith it except checking if it’s defined using the defined test.
>>> foo = StrictUndefined(name='foo')
>>> str(foo)
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
>>> not foo
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
>>> foo + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
There is also a factory function that can decorate undefined objects toimplement logging on failures:
jinja2.
makelogging_undefined
(_logger=None, base=None)- Given a logger object this returns a new undefined class that willlog certain failures. It will log iterations and printing. If nologger is given a default logger is created.
Example:
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=logger,
base=Undefined
)
Changelog
New in version 2.8.
- Parameters
logger – the logger to use. If not provided, a default loggeris created.
base – the base class to add logging functionality to. Thisdefaults to
Undefined
.
Undefined objects are created by calling undefined
.
Implementation
Undefined
objects are implemented by overriding the specialunderscore methods. For example the default Undefined
class implements unicode in a way that it returns an emptystring, however int and others still fail with an exception. Toallow conversion to int by returning 0
you can implement your own:
class NullUndefined(Undefined):
def __int__(self):
return 0
def __float__(self):
return 0.0
To disallow a method, just override it and raise_undefined_exception
. Because this is a very commonidom in undefined objects there is the helper method_fail_with_undefined_error()
that does the error raisingautomatically. Here a class that works like the regular Undefined
but chokes on iteration:
class NonIterableUndefined(Undefined):
__iter__ = Undefined._fail_with_undefined_error