Skip to content
Myr

Add ChainableUndefined allowing getattr & getitem (#997)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add ChainableUndefined allowing getattr & getitem Allows using default values with chains of items or attributes that may contain undefined values without raising a jinja2.exceptions.UndefinedError. >>> import jinja2 >>> env = jinja2.Environment(undefined=jinja2.ChainableUndefined) >>> env.from_string("{{ foo.bar['baz'] | default('val') }}").render() 'val' * Remove class decorator from ChainableUndefined

authored by Étienne Pelletier · committed by David Lord · parent 9766c17 · Browse files · 7 files+69 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+69 added−9 removed

  • tests:+23 added−2 removed
  • other:+46 added−7 removed

7 files+69 added−9 removed

modified:docs/api.rst+3 added-1 removed
320 unmodified lines
321unable to look up a name or access an attribute one of those objects is322created and returned. Some operations on undefined values are then allowed,323others fail.324325The closest to regular Python behavior is the `StrictUndefined` which325The closest to regular Python behavior is the :class:`StrictUndefined` which326disallows all operations beside testing if it's an undefined object.327328.. autoclass:: jinja2.Undefined()329
22 unmodified lines
352 When called with any arguments this method raises353 :attr:`_undefined_exception` with an error message generated354 from the undefined hints stored on the undefined object.355356.. autoclass:: jinja2.ChainableUndefined()357358.. autoclass:: jinja2.DebugUndefined()359360.. autoclass:: jinja2.StrictUndefined()361
573 unmodified lines
modified:jinja2/__init__.py+2 added-2 removed
40 unmodified lines
41from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache4344# undefined types45from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46 make_logging_undefined45from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46 StrictUndefined, make_logging_undefined4748# exceptions49from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \
22 unmodified lines
modified:jinja2/filters.py+6 added
366 unmodified lines
367368 .. sourcecode:: jinja369370 {{ ''|default('the string was empty', true) }}371372 .. versionchanged:: 2.11373 It's now possible to configure the :class:`~jinja2.Environment` with374 :class:`~jinja2.ChainableUndefined` to make the `default` filter work375 on nested elements and attributes that may contain undefined values376 in the chain without getting an :exc:`~jinja2.UndefinedError`.377 """378 if isinstance(value, Undefined) or (boolean and not value):379 return default_value380 return value
830 unmodified lines
modified:jinja2/runtime.py+30 added-3 removed
584 unmodified lines
585586@implements_to_string587class Undefined(object):588 """The default undefined type. This undefined type can be printed and589 iterated over, but every other access will raise an :exc:`jinja2.exceptions.UndefinedError`:589 iterated over, but every other access will raise an :exc:`UndefinedError`:590591 >>> foo = Undefined(name='foo')592 >>> str(foo)593 ''
15 unmodified lines
609610 @internalcode611 def _fail_with_undefined_error(self, *args, **kwargs):612 """Regular callback function for undefined objects that raises an613 `jinja2.exceptions.UndefinedError` on call.613 `UndefinedError` on call.614 """615 if self._undefined_hint is None:616 if self._undefined_obj is missing:617 hint = '%r is undefined' % self._undefined_name
131 unmodified lines
749750 return LoggingUndefined751752753# No @implements_to_string decorator here because __str__754# is not overwritten from Undefined in this class.755# This would cause a recursion error in Python 2.756class ChainableUndefined(Undefined):757 """An undefined that is chainable, where both758 __getattr__ and __getitem__ return itself rather than759 raising an :exc:`UndefinedError`:760761 >>> foo = ChainableUndefined(name='foo')762 >>> str(foo.bar['baz'])763 ''764 >>> foo.bar['baz'] + 42765 Traceback (most recent call last):766 ...767 jinja2.exceptions.UndefinedError: 'foo' is undefined768769 .. versionadded:: 2.11770 """771 __slots__ = ()772773 def __getattr__(self, _):774 return self775776 __getitem__ = __getattr__777778779@implements_to_string780class DebugUndefined(Undefined):781 """An undefined that returns the debug info when printed.782
47 unmodified lines
830831832# remove remaining slots attributes, after the metaclass did the magic they833# are unneeded and irritating as they contain wrong data for the subclasses.808del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__834del Undefined.__slots__, ChainableUndefined.__slots__, \835 DebugUndefined.__slots__, StrictUndefined.__slots__
modified:tests/test_api.py+23 added-2 removed
11 unmodified lines
12import tempfile13import shutil1415import pytest16from jinja2 import Environment, Undefined, DebugUndefined, \17 StrictUndefined, UndefinedError, meta, \16from jinja2 import Environment, Undefined, ChainableUndefined, \17 DebugUndefined, StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19from jinja2.compiler import CodeGenerator20from jinja2.runtime import Context21from jinja2.utils import Cycler
235 unmodified lines
257 assert env.from_string('{{ not missing }}').render() == 'True'258 pytest.raises(UndefinedError,259 env.from_string('{{ missing - 1}}').render)260261 def test_chainable_undefined(self):262 env = Environment(undefined=ChainableUndefined)263 # The following tests are copied from test_default_undefined264 assert env.from_string('{{ missing }}').render() == u''265 assert env.from_string('{{ missing|list }}').render() == '[]'266 assert env.from_string('{{ missing is not defined }}').render() \267 == 'True'268 assert env.from_string('{{ foo.missing }}').render(foo=42) == ''269 assert env.from_string('{{ not missing }}').render() == 'True'270 pytest.raises(UndefinedError,271 env.from_string('{{ missing - 1}}').render)272273 # The following tests ensure subclass functionality works as expected274 assert env.from_string('{{ missing.bar["baz"] }}').render() == u''275 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() \276 == u'foo'277 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(278 foo=42) == u'bar'279 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(280 foo={'bar': 42}) == u'baz'281282 def test_debug_undefined(self):283 env = Environment(undefined=DebugUndefined)284 assert env.from_string('{{ missing }}').render() == '{{ missing }}'285 pytest.raises(UndefinedError,
76 unmodified lines
modified:.gitignore+1 added
8 unmodified lines
9.DS_Store10.tox/11.cache/12.idea/13env/14venv/15venv-*/16.coverage17.coverage.*
2 unmodified lines
modified:CHANGES.rst+4 added-1 removed
11 unmodified lines
12- Async support is only loaded the first time an13 :class:`~environment.Environment` enables it, in order to avoid a14 slow initial import. (`#765`_)15- Python 2.6 and 3.3 are not supported anymore.16- The `map` filter in async mode now automatically awaits16- The ``map`` filter in async mode now automatically awaits17- Added a new ``ChainableUndefined`` class to support getitem18 and getattr on an undefined object. (`#977`_)1920.. _#765: https://github.com/pallets/jinja/issues/76521.. _#977: https://github.com/pallets/jinja/issues/977222324Version 2.10.125--------------
600 unmodified lines