deprecate legacy resolve mode
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 9d4689b · Browse files · 4 files·+74 added−56 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+74 added−56 removed
- tests:+7 added−5 removed
- other:+67 added−51 removed
Provenance
- Commit
912e59d- Tree
3e761bf- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9d4689b
4 files changed+74 added−56 removed
modified:docs/api.rst+1 added-1 removed
362 unmodified lines363 The Context364 -----------365 366 .. autoclass:: jinja2.runtime.Context()367- :members: resolve, get_exported, get_all367+ :members: get, resolve, resolve_or_missing, get_exported, get_all368 369 .. attribute:: parent370 371 A dict of read only, global variables the template looks up. These560 unmodified linesmodified:src/jinja2/runtime.py+64 added-50 removed
1 unmodified line2 import sys3 import typing as t4 from collections import abc5 from itertools import chain6-from types import MethodType6 7 from markupsafe import escape # noqa: F4018 from markupsafe import Markup9 from markupsafe import soft_str117 unmodified lines127 def __repr__(self):128 return f"<{self.__class__.__name__} {self.__context.name!r}>"129 130 132-def _get_func(x):133- return getattr(x, "__func__", x)134-135-131 class ContextMeta(type):132 def __new__(mcs, name, bases, d):133 rv = type.__new__(mcs, name, bases, d)139- if bases == ():134+135+ if not bases:136 return rv137 142- resolve = _get_func(rv.resolve)143- default_resolve = _get_func(Context.resolve)144- resolve_or_missing = _get_func(rv.resolve_or_missing)145- default_resolve_or_missing = _get_func(Context.resolve_or_missing)138+ if "resolve_or_missing" in d:139+ # If the subclass overrides resolve_or_missing it opts in to140+ # modern mode no matter what.141+ rv._legacy_resolve_mode = False142+ elif "resolve" in d or rv._legacy_resolve_mode:143+ # If the subclass overrides resolve, or if its base is144+ # already in legacy mode, warn about legacy behavior.145+ import warnings146 147- # If we have a changed resolve but no changed default or missing148- # resolve we invert the call logic.149- if (150- resolve is not default_resolve151- and resolve_or_missing is default_resolve_or_missing152- ):147+ warnings.warn(148+ "Overriding 'resolve' is deprecated and will not have"149+ " the expected behavior in Jinja 3.1. Override"150+ " 'resolve_or_missing' instead ",151+ DeprecationWarning,152+ stacklevel=2,153+ )154 rv._legacy_resolve_mode = True154- elif (155- resolve is default_resolve156- and resolve_or_missing is default_resolve_or_missing157- ):158- rv._fast_resolve_mode = True155 156 return rv157 158 163-def resolve_or_missing(context, key, missing=missing):164- if key in context.vars:165- return context.vars[key]166- if key in context.parent:167- return context.parent[key]168- return missing169-170-159 @abc.Mapping.register160 class Context(metaclass=ContextMeta):161 """The template context holds the variables of a template. It stores the162 values passed to the template and also the names the template exports.13 unmodified lines176 method that doesn't fail with a `KeyError` but returns an177 :class:`Undefined` object for missing variables.178 """179 192- # XXX: we want to eventually make this be a deprecation warning and193- # remove it.180 _legacy_resolve_mode = False195- _fast_resolve_mode = False181 182 def __init__(self, environment, parent, name, blocks, globals=None):183 self.parent = parent184 self.vars = {}7 unmodified lines192 # takes place the runtime will update this mapping with the new blocks193 # from the template.194 self.blocks = {k: [v] for k, v in blocks.items()}195 211- # In case we detect the fast resolve mode we can set up an alias212- # here that bypasses the legacy code logic.213- if self._fast_resolve_mode:214- self.resolve_or_missing = MethodType(resolve_or_missing, self)215-196 def super(self, name, current):197 """Render a parent block."""198 try:199 blocks = self.blocks[name]5 unmodified lines205 )206 return BlockReference(name, self, blocks, index)207 208 def get(self, key, default=None):229- """Returns an item from the template context, if it doesn't exist230- `default` is returned.209+ """Look up a variable by name, or return a default if the key is210+ not found.211+212+ :param key: The variable name to look up.213+ :param default: The value to return if the key is not found.214 """215 try:216 return self[key]217 except KeyError:218 return default219 220 def resolve(self, key):238- """Looks up a variable like `__getitem__` or `get` but returns an239- :class:`Undefined` object with the name of the name looked up.221+ """Look up a variable by name, or return an :class:`Undefined`222+ object if the key is not found.223+224+ If you need to add custom behavior, override225+ :meth:`resolve_or_missing`, not this method. The various lookup226+ functions use that method, not this one.227+228+ :param key: The variable name to look up.229 """230 if self._legacy_resolve_mode:242- rv = resolve_or_missing(self, key)243- else:244- rv = self.resolve_or_missing(key)231+ if key in self.vars:232+ return self.vars[key]233+234+ if key in self.parent:235+ return self.parent[key]236+237+ return self.environment.undefined(name=key)238+239+ rv = self.resolve_or_missing(key)240+241 if rv is missing:242 return self.environment.undefined(name=key)243+244 return rv245 246 def resolve_or_missing(self, key):250- """Resolves a variable like :meth:`resolve` but returns the251- special `missing` value if it cannot be found.247+ """Look up a variable by name, or return a ``missing`` sentinel248+ if the key is not found.249+250+ Override this method to add custom lookup behavior.251+ :meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this252+ method. Don't call this method directly.253+254+ :param key: The variable name to look up.255 """256 if self._legacy_resolve_mode:257 rv = self.resolve(key)258+259 if isinstance(rv, Undefined):256- rv = missing260+ return missing261+262 return rv258- return resolve_or_missing(self, key)263 264+ if key in self.vars:265+ return self.vars[key]266+267+ if key in self.parent:268+ return self.parent[key]269+270+ return missing271+272 def get_exported(self):273 """Get a new dict with the exported variables."""274 return {k: self.vars[k] for k in self.exported_vars}275 80 unmodified lines356 def __contains__(self, name):357 return name in self.vars or name in self.parent358 359 def __getitem__(self, key):348- """Lookup a variable or raise `KeyError` if the variable is349- undefined.360+ """Look up a variable by name with ``[]`` syntax, or raise a361+ ``KeyError`` if the key is not found.362 """363 item = self.resolve_or_missing(key)364+365 if item is missing:366 raise KeyError(key)367+368 return item369 370 def __repr__(self):371 return f"<{self.__class__.__name__} {self.get_all()!r} of {self.name!r}>"678 unmodified linesmodified:tests/test_regression.py+7 added-5 removed
592 unmodified lines593 594 def test_legacy_custom_context(self, env):595 from jinja2.runtime import Context, missing596 597- class MyContext(Context):598- def resolve(self, name):599- if name == "foo":600- return 42601- return super().resolve(name)597+ with pytest.deprecated_call():598 599+ class MyContext(Context):600+ def resolve(self, name):601+ if name == "foo":602+ return 42603+ return super().resolve(name)604+605 x = MyContext(env, parent={"bar": 23}, name="foo", blocks={})606 assert x._legacy_resolve_mode607 assert x.resolve_or_missing("foo") == 42608 assert x.resolve_or_missing("bar") == 23146 unmodified linesmodified:CHANGES.rst+2 added
71 unmodified lines72 73 - Async support no longer requires Jinja to patch itself. It must74 still be enabled with ``Environment(enable_async=True)``.75 :issue:`1390`76+- Overriding ``Context.resolve`` is deprecated, override77+ ``resolve_or_missing`` instead. :issue:`1380`78 79 80 Version 2.11.381 --------------780 unmodified lines