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
Provenance
- Commit
19133d4- Tree
a92f5b2- Author
Étienne Pelletier <EtiennePelletier@users.noreply.github.com>- Committer
David Lord <davidism@gmail.com>- Parent
9766c17
7 files changed+69 added−9 removed
modified:docs/api.rst+3 added-1 removed
320 unmodified lines321 unable to look up a name or access an attribute one of those objects is322 created and returned. Some operations on undefined values are then allowed,323 others fail.324 325-The closest to regular Python behavior is the `StrictUndefined` which325+The closest to regular Python behavior is the :class:`StrictUndefined` which326 disallows all operations beside testing if it's an undefined object.327 328 .. autoclass:: jinja2.Undefined()329 22 unmodified lines352 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.355 356+.. autoclass:: jinja2.ChainableUndefined()357+358 .. autoclass:: jinja2.DebugUndefined()359 360 .. autoclass:: jinja2.StrictUndefined()361 573 unmodified linesmodified:jinja2/__init__.py+2 added-2 removed
40 unmodified lines41 from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache43 44 # undefined types45-from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46- make_logging_undefined45+from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46+ StrictUndefined, make_logging_undefined47 48 # exceptions49 from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \22 unmodified linesmodified:jinja2/filters.py+6 added
366 unmodified lines367 368 .. sourcecode:: jinja369 370 {{ ''|default('the string was empty', true) }}371+372+ .. 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 value830 unmodified linesmodified:jinja2/runtime.py+30 added-3 removed
584 unmodified lines585 586 @implements_to_string587 class 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`:590 591 >>> foo = Undefined(name='foo')592 >>> str(foo)593 ''15 unmodified lines609 610 @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_name131 unmodified lines749 750 return LoggingUndefined751 752 753+# 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.756+class ChainableUndefined(Undefined):757+ """An undefined that is chainable, where both758+ __getattr__ and __getitem__ return itself rather than759+ raising an :exc:`UndefinedError`:760+761+ >>> 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 undefined768+769+ .. versionadded:: 2.11770+ """771+ __slots__ = ()772+773+ def __getattr__(self, _):774+ return self775+776+ __getitem__ = __getattr__777+778+779 @implements_to_string780 class DebugUndefined(Undefined):781 """An undefined that returns the debug info when printed.782 47 unmodified lines830 831 832 # remove remaining slots attributes, after the metaclass did the magic they833 # are unneeded and irritating as they contain wrong data for the subclasses.808-del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__834+del Undefined.__slots__, ChainableUndefined.__slots__, \835+ DebugUndefined.__slots__, StrictUndefined.__slots__modified:tests/test_api.py+23 added-2 removed
11 unmodified lines12 import tempfile13 import shutil14 15 import pytest16-from jinja2 import Environment, Undefined, DebugUndefined, \17- StrictUndefined, UndefinedError, meta, \16+from jinja2 import Environment, Undefined, ChainableUndefined, \17+ DebugUndefined, StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19 from jinja2.compiler import CodeGenerator20 from jinja2.runtime import Context21 from jinja2.utils import Cycler235 unmodified lines257 assert env.from_string('{{ not missing }}').render() == 'True'258 pytest.raises(UndefinedError,259 env.from_string('{{ missing - 1}}').render)260 261+ 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)272+273+ # 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'281+282 def test_debug_undefined(self):283 env = Environment(undefined=DebugUndefined)284 assert env.from_string('{{ missing }}').render() == '{{ missing }}'285 pytest.raises(UndefinedError,76 unmodified linesmodified:.gitignore+1 added
8 unmodified lines9 .DS_Store10 .tox/11 .cache/12 .idea/13+env/14 venv/15 venv-*/16 .coverage17 .coverage.*2 unmodified linesmodified:CHANGES.rst+4 added-1 removed
11 unmodified lines12 - 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`_)19 20 .. _#765: https://github.com/pallets/jinja/issues/76521+.. _#977: https://github.com/pallets/jinja/issues/97722 23 24 Version 2.10.125 --------------600 unmodified lines