Skip to content
Myr

preserve `__slots__` on Undefined classes

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

authored by Matt Davis · committed by David Lord · parent 39d9fff · Browse files · 4 files+69 added−21 removed
This commit

State

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

Diff stats

4 files+69 added−21 removed

  • tests:+50 added−8 removed
  • other:+19 added−13 removed

4 files+69 added−21 removed

modified:src/jinja2/runtime.py+17 added-13 removed
858 unmodified lines
859 raise self._undefined_exception(self._undefined_message)860861 @internalcode862 def __getattr__(self, name: str) -> t.Any:863 if name[:2] == "__":863 # Raise AttributeError on requests for names that appear to be unimplemented864 # dunder methods to keep Python's internal protocol probing behaviors working865 # properly in cases where another exception type could cause unexpected or866 # difficult-to-diagnose failures.867 if name[:2] == "__" and name[-2:] == "__":868 raise AttributeError(name)869870 return self._fail_with_undefined_error()871
115 unmodified lines
987988 def __html__(self) -> str:989 return str(self)990987 def __getattr__(self, _: str) -> "ChainableUndefined":991 def __getattr__(self, name: str) -> "ChainableUndefined":992 # Raise AttributeError on requests for names that appear to be unimplemented993 # dunder methods to avoid confusing Python with truthy non-method objects that994 # do not implement the protocol being probed for. e.g., copy.copy(Undefined())995 # fails spectacularly if getattr(Undefined(), '__setstate__') returns an996 # Undefined object instead of raising AttributeError to signal that it does not997 # support that style of object initialization.998 if name[:2] == "__" and name[-2:] == "__":999 raise AttributeError(name)10001001 return self1002990 __getitem__ = __getattr__ # type: ignore1003 def __getitem__(self, _name: str) -> "ChainableUndefined": # type: ignore[override]1004 return self100510061007class DebugUndefined(Undefined):1008 """An undefined that returns the debug info when printed.
50 unmodified lines
1059 __slots__ = ()1060 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error1061 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1062 __contains__ = Undefined._fail_with_undefined_error104910501051# Remove slots attributes, after the metaclass is applied they are1052# unneeded and contain wrong data for subclasses.1053del (1054 Undefined.__slots__,1055 ChainableUndefined.__slots__,1056 DebugUndefined.__slots__,1057 StrictUndefined.__slots__,1058)
modified:tests/test_api.py-8 removed
321 unmodified lines
322 und2 = Undefined(name="y")323 assert und1 == und2324 assert und1 != 42325 assert hash(und1) == hash(und2) == hash(Undefined())326 with pytest.raises(AttributeError):327 getattr(Undefined, "__slots__") # noqa: B009326327 def test_chainable_undefined(self):328 env = Environment(undefined=ChainableUndefined)329 # The following tests are copied from test_default_undefined
2 unmodified lines
332 assert env.from_string("{{ missing is not defined }}").render() == "True"333 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""334 assert env.from_string("{{ not missing }}").render() == "True"335 pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)338 with pytest.raises(AttributeError):339 getattr(ChainableUndefined, "__slots__") # noqa: B009336337 # The following tests ensure subclass functionality works as expected338 assert env.from_string('{{ missing.bar["baz"] }}').render() == ""339 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"
23 unmodified lines
363 assert (364 str(DebugUndefined(hint=undefined_hint))365 == f"{{{{ undefined value printed: {undefined_hint} }}}}"366 )371 with pytest.raises(AttributeError):372 getattr(DebugUndefined, "__slots__") # noqa: B009367368 def test_strict_undefined(self):369 env = Environment(undefined=StrictUndefined)370 pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)
8 unmodified lines
379 assert (380 env.from_string('{{ missing|default("default", true) }}').render()381 == "default"382 )389 with pytest.raises(AttributeError):390 getattr(StrictUndefined, "__slots__") # noqa: B009383 assert env.from_string('{{ "foo" if false }}').render() == ""384385 def test_indexing_gives_undefined(self):386 t = Template("{{ var[42].foo }}")
41 unmodified lines
modified:tests/test_runtime.py+50 added
1import copy2import itertools3import pickle45import pytest67from jinja2 import ChainableUndefined8from jinja2 import DebugUndefined9from jinja2 import StrictUndefined10from jinja2 import Template11from jinja2 import TemplateRuntimeError12from jinja2 import Undefined13from jinja2.runtime import LoopContext1415TEST_IDX_TEMPLATE_STR_1 = (16 "[{% for i in lst|reverse %}(len={{ loop.length }},"
64 unmodified lines
81 t = Template("{{ calc() }}")82 out = t.render(calc=Calc())83 # Would be "1" if context argument was passed.84 assert out == "0"858687_undefined_types = (Undefined, ChainableUndefined, DebugUndefined, StrictUndefined)888990@pytest.mark.parametrize("undefined_type", _undefined_types)91def test_undefined_copy(undefined_type):92 undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)93 copied = copy.copy(undef)9495 assert copied is not undef96 assert copied._undefined_hint is undef._undefined_hint97 assert copied._undefined_obj is undef._undefined_obj98 assert copied._undefined_name is undef._undefined_name99 assert copied._undefined_exception is undef._undefined_exception100101102@pytest.mark.parametrize("undefined_type", _undefined_types)103def test_undefined_deepcopy(undefined_type):104 undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)105 copied = copy.deepcopy(undef)106107 assert copied._undefined_hint is undef._undefined_hint108 assert copied._undefined_obj is not undef._undefined_obj109 assert copied._undefined_obj == undef._undefined_obj110 assert copied._undefined_name is undef._undefined_name111 assert copied._undefined_exception is undef._undefined_exception112113114@pytest.mark.parametrize("undefined_type", _undefined_types)115def test_undefined_pickle(undefined_type):116 undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)117 copied = pickle.loads(pickle.dumps(undef))118119 assert copied._undefined_hint is not undef._undefined_hint120 assert copied._undefined_hint == undef._undefined_hint121 assert copied._undefined_obj is not undef._undefined_obj122 assert copied._undefined_obj == undef._undefined_obj123 assert copied._undefined_name is not undef._undefined_name124 assert copied._undefined_name == undef._undefined_name125 assert copied._undefined_exception is undef._undefined_exception
modified:CHANGES.rst+2 added
20 unmodified lines
21- ``|int`` filter handles ``OverflowError`` from scientific notation.22 :issue:`1921`23- Make compiling deterministic for tuple unpacking in a ``{% set ... %}``24 call. :issue:`2021`25- Fix dunder protocol (`copy`/`pickle`/etc) interaction with ``Undefined``26 objects. :issue:`2025`272829Version 3.1.430-------------
994 unmodified lines