Undefined Types

These classes can be used as undefined types. The Environmentconstructor 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:
  1. >>> foo = Undefined(name='foo')
  2. >>> str(foo)
  3. ''
  4. >>> not foo
  5. True
  6. >>> foo + 42
  7. Traceback (most recent call last):
  8. ...
  9. jinja2.exceptions.UndefinedError: 'foo' is undefined
  • _undefined_hint
  • Either None or an unicode string with the error message forthe undefined object.

  • _undefined_obj

  • Either None or the owner object that caused the undefined objectto be created (for example because an attribute does not exist).

  • _undefined_name

  • The name for the undefined variable / attribute or just _None_if no such information exists.

  • _undefined_exception

  • The exception that the undefined object wants to raise. Thisis usually one of UndefinedError or SecurityError.

  • fail_with_undefined_error(args, *kwargs_)

  • When called with any arguments this method raises_undefined_exception with an error message generatedfrom the undefined hints stored on the undefined object.
  • class jinja2.DebugUndefined
  • An undefined that returns the debug info when printed.
  1. >>> foo = DebugUndefined(name='foo')
  2. >>> str(foo)
  3. '{{ foo }}'
  4. >>> not foo
  5. True
  6. >>> foo + 42
  7. Traceback (most recent call last):
  8. ...
  9. 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.
  1. >>> foo = StrictUndefined(name='foo')
  2. >>> str(foo)
  3. Traceback (most recent call last):
  4. ...
  5. jinja2.exceptions.UndefinedError: 'foo' is undefined
  6. >>> not foo
  7. Traceback (most recent call last):
  8. ...
  9. jinja2.exceptions.UndefinedError: 'foo' is undefined
  10. >>> foo + 42
  11. Traceback (most recent call last):
  12. ...
  13. 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:

  1. logger = logging.getLogger(__name__)
  2. LoggingUndefined = make_logging_undefined(
  3. logger=logger,
  4. base=Undefined
  5. )

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 Undefinedclass 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:

  1. class NullUndefined(Undefined):
  2. def __int__(self):
  3. return 0
  4. def __float__(self):
  5. 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 Undefinedbut chokes on iteration:

  1. class NonIterableUndefined(Undefined):
  2. __iter__ = Undefined._fail_with_undefined_error