Skip to content
Myr

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

4 files+74 added−56 removed

modified:docs/api.rst+1 added-1 removed
362 unmodified lines
363The Context364-----------365366.. autoclass:: jinja2.runtime.Context()367 :members: resolve, get_exported, get_all367 :members: get, resolve, resolve_or_missing, get_exported, get_all368369 .. attribute:: parent370371 A dict of read only, global variables the template looks up. These
560 unmodified lines
modified:src/jinja2/runtime.py+64 added-50 removed
1 unmodified line
2import sys3import typing as t4from collections import abc5from itertools import chain6from types import MethodType67from markupsafe import escape # noqa: F4018from markupsafe import Markup9from markupsafe import soft_str
117 unmodified lines
127 def __repr__(self):128 return f"<{self.__class__.__name__} {self.__context.name!r}>"129130132def _get_func(x):133 return getattr(x, "__func__", x)134135131class ContextMeta(type):132 def __new__(mcs, name, bases, d):133 rv = type.__new__(mcs, name, bases, d)139 if bases == ():134135 if not bases:136 return rv137142 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 warnings146147 # 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 = True155156 return rv157158163def 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 missing169170159@abc.Mapping.register160class 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 lines
176 method that doesn't fail with a `KeyError` but returns an177 :class:`Undefined` object for missing variables.178 """179192 # XXX: we want to eventually make this be a deprecation warning and193 # remove it.180 _legacy_resolve_mode = False195 _fast_resolve_mode = False181182 def __init__(self, environment, parent, name, blocks, globals=None):183 self.parent = parent184 self.vars = {}
7 unmodified lines
192 # 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()}195211 # 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)215196 def super(self, name, current):197 """Render a parent block."""198 try:199 blocks = self.blocks[name]
5 unmodified lines
205 )206 return BlockReference(name, self, blocks, index)207208 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.211212 :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 default219220 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.223224 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.227228 :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]233234 if key in self.parent:235 return self.parent[key]236237 return self.environment.undefined(name=key)238239 rv = self.resolve_or_missing(key)240241 if rv is missing:242 return self.environment.undefined(name=key)243244 return rv245246 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.249250 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.253254 :param key: The variable name to look up.255 """256 if self._legacy_resolve_mode:257 rv = self.resolve(key)258259 if isinstance(rv, Undefined):256 rv = missing260 return missing261262 return rv258 return resolve_or_missing(self, key)263264 if key in self.vars:265 return self.vars[key]266267 if key in self.parent:268 return self.parent[key]269270 return missing271272 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 lines
356 def __contains__(self, name):357 return name in self.vars or name in self.parent358359 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)364365 if item is missing:366 raise KeyError(key)367368 return item369370 def __repr__(self):371 return f"<{self.__class__.__name__} {self.get_all()!r} of {self.name!r}>"
678 unmodified lines
modified:tests/test_regression.py+7 added-5 removed
592 unmodified lines
593594 def test_legacy_custom_context(self, env):595 from jinja2.runtime import Context, missing596597 class MyContext(Context):598 def resolve(self, name):599 if name == "foo":600 return 42601 return super().resolve(name)597 with pytest.deprecated_call():598599 class MyContext(Context):600 def resolve(self, name):601 if name == "foo":602 return 42603 return super().resolve(name)604605 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") == 23
146 unmodified lines
modified:CHANGES.rst+2 added
71 unmodified lines
7273- 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`787980Version 2.11.381--------------
780 unmodified lines