Skip to content
Myr

runtime.py

This file

Path

src/jinja2/runtime.py

1,062 lines · 33.3 KiB · Python

Last changed by

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

History of this file

Take it

The walk stopped after 200 commits: lines older than c580dd0 point at it.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1why, one step back
1"""The runtime functions and state used by compiled templates."""

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 2why, one step back
2

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 3why, one step back
3import functools

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 4why, one step back
4import sys

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

line 5why, one step back
5import typing as t

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 6–12why, one step back
6from collections import abc
7from itertools import chain89from markupsafe import escape # noqa: F40110from markupsafe import Markup11from markupsafe import soft_str12

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 13–14why, one step back
13from .async_utils import auto_aiter
14from .async_utils import auto_await # noqa: F401

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 15–18why, one step back
15from .exceptions import TemplateNotFound # noqa: F401
16from .exceptions import TemplateRuntimeError # noqa: F40117from .exceptions import UndefinedError18from .nodes import EvalContext

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 19why, one step back
19from .utils import _PassArg

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 20–24why, one step back
20from .utils import concat
21from .utils import internalcode22from .utils import missing23from .utils import Namespace # noqa: F40124from .utils import object_type_repr

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 25why, one step back
25from .utils import pass_eval_context

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 26why, one step back
26

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 27–29why, one step back
27V = t.TypeVar("V")
28F = t.TypeVar("F", bound=t.Callable[..., t.Any])29

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 30why, one step back
30if t.TYPE_CHECKING:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 31why, one step back
31 import logging

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 32why, one step back
32

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 33why, one step back
33 import typing_extensions as te

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 34why, one step back
34

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 35–36why, one step back
35 from .environment import Environment
36

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 37–42why, one step back
37 class LoopRenderFunc(te.Protocol):
38 def __call__(39 self,40 reciter: t.Iterable[V],41 loop_render_func: "LoopRenderFunc",42 depth: int = 0,

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 43why, one step back
43 ) -> str: ...

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 44–45why, one step back
44
45

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 46–60why, one step back
46# these variables are exported to the template runtime
47exported = [48 "LoopContext",49 "TemplateReference",50 "Macro",51 "Markup",52 "TemplateRuntimeError",53 "missing",54 "escape",55 "markup_join",56 "str_join",57 "identity",58 "TemplateNotFound",59 "Namespace",60 "Undefined",

Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e

line 61why, one step back
61 "internalcode",

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 62why, one step back
62]

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 63–67why, one step back
63async_exported = [
64 "AsyncLoopContext",65 "auto_aiter",66 "auto_await",67]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 68–69why, one step back
68
69

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 70why, one step back
70def identity(x: V) -> V:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 71–76why, one step back
71 """Returns its argument. Useful for certain things in the
72 environment.73 """74 return x7576

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 77why, one step back
77def markup_join(seq: t.Iterable[t.Any]) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 78–87why, one step back
78 """Concatenation that escapes if necessary and converts to string."""
79 buf = []80 iterator = map(soft_str, seq)81 for arg in iterator:82 buf.append(arg)83 if hasattr(arg, "__html__"):84 return Markup("").join(chain(buf, iterator))85 return concat(buf)8687

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 88why, one step back
88def str_join(seq: t.Iterable[t.Any]) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 89–93why, one step back
89 """Simple args to string conversion and concatenation."""
90 return concat(map(str, seq))919293def new_context(

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 94why, one step back
94 environment: "Environment",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 95why, one step back
95 template_name: str | None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 96why, one step back
96 blocks: dict[str, t.Callable[["Context"], t.Iterator[str]]],

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 97why, one step back
97 vars: dict[str, t.Any] | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 98why, one step back
98 shared: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 99–100why, one step back
99 globals: t.MutableMapping[str, t.Any] | None = None,
100 locals: t.Mapping[str, t.Any] | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 101why, one step back
101) -> "Context":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 102–124why, one step back
102 """Internal helper for context creation."""
103 if vars is None:104 vars = {}105 if shared:106 parent = vars107 else:108 parent = dict(globals or (), **vars)109 if locals:110 # if the parent is shared a copy should be created because111 # we don't want to modify the dict passed112 if shared:113 parent = dict(parent)114 for key, value in locals.items():115 if value is not missing:116 parent[key] = value117 return environment.context_class(118 environment, parent, template_name, blocks, globals=globals119 )120121122class TemplateReference:123 """The `self` in templates."""124

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 125why, one step back
125 def __init__(self, context: "Context") -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 126–127why, one step back
126 self.__context = context
127

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 128why, one step back
128 def __getitem__(self, name: str) -> t.Any:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 129–131why, one step back
129 blocks = self.__context.blocks[name]
130 return BlockReference(name, self.__context, blocks, 0)131

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 132–133why, one step back
132 def __repr__(self) -> str:
133 return f"<{type(self).__name__} {self.__context.name!r}>"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 134–135why, one step back
134
135

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 136–139why, one step back
136def _dict_method_all(dict_method: F) -> F:
137 @functools.wraps(dict_method)138 def f_all(self: "Context") -> t.Any:139 return dict_method(self.get_all())

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

line 140why, one step back
140

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 141why, one step back
141 return t.cast(F, f_all)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 142–144why, one step back
142
143144@abc.Mapping.register

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 145why, one step back
145class Context:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 146–154why, one step back
146 """The template context holds the variables of a template. It stores the
147 values passed to the template and also the names the template exports.148 Creating instances is neither supported nor useful as it's created149 automatically at various stages of the template evaluation and should not150 be created by hand.151152 The context is immutable. Modifications on :attr:`parent` **must not**153 happen and modifications on :attr:`vars` are allowed from generated154 template code only. Template filters and global functions marked as

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 155why, one step back
155 :func:`pass_context` get the active context passed as first argument

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 156–164why, one step back
156 and are allowed to access the context read-only.
157158 The template context supports read only dict operations (`get`,159 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,160 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`161 method that doesn't fail with a `KeyError` but returns an162 :class:`Undefined` object for missing variables.163 """164

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 165–167why, one step back
165 def __init__(
166 self,167 environment: "Environment",

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 168why, one step back
168 parent: dict[str, t.Any],

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 169why, one step back
169 name: str | None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 170why, one step back
170 blocks: dict[str, t.Callable[["Context"], t.Iterator[str]]],

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 171why, one step back
171 globals: t.MutableMapping[str, t.Any] | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 172why, one step back
172 ):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 173why, one step back
173 self.parent = parent

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 174why, one step back
174 self.vars: dict[str, t.Any] = {}

[pre-commit.ci] pre-commit autoupdate (#1993)David Lordbefore adoption9c6c319

line 175why, one step back
175 self.environment: Environment = environment

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 176why, one step back
176 self.eval_ctx = EvalContext(self.environment, name)

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 177why, one step back
177 self.exported_vars: set[str] = set()

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 178–185why, one step back
178 self.name = name
179 self.globals_keys = set() if globals is None else set(globals)180181 # create the initial mapping of blocks. Whenever template inheritance182 # takes place the runtime will update this mapping with the new blocks183 # from the template.184 self.blocks = {k: [v] for k, v in blocks.items()}185

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 186–188why, one step back
186 def super(
187 self, name: str, current: t.Callable[["Context"], t.Iterator[str]]188 ) -> t.Union["BlockReference", "Undefined"]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 189–199why, one step back
189 """Render a parent block."""
190 try:191 blocks = self.blocks[name]192 index = blocks.index(current) + 1193 blocks[index]194 except LookupError:195 return self.environment.undefined(196 f"there is no parent block called {name!r}.", name="super"197 )198 return BlockReference(name, self, blocks, index)199

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 200why, one step back
200 def get(self, key: str, default: t.Any = None) -> t.Any:

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

lines 201–205why, one step back
201 """Look up a variable by name, or return a default if the key is
202 not found.203204 :param key: The variable name to look up.205 :param default: The value to return if the key is not found.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 206–211why, one step back
206 """
207 try:208 return self[key]209 except KeyError:210 return default211

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 212why, one step back
212 def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

lines 213–220why, one step back
213 """Look up a variable by name, or return an :class:`Undefined`
214 object if the key is not found.215216 If you need to add custom behavior, override217 :meth:`resolve_or_missing`, not this method. The various lookup218 functions use that method, not this one.219220 :param key: The variable name to look up.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 221why, one step back
221 """

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

lines 222–223why, one step back
222 rv = self.resolve_or_missing(key)
223

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 224–225why, one step back
224 if rv is missing:
225 return self.environment.undefined(name=key)

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

line 226why, one step back
226

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 227–228why, one step back
227 return rv
228

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 229why, one step back
229 def resolve_or_missing(self, key: str) -> t.Any:

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

lines 230–237why, one step back
230 """Look up a variable by name, or return a ``missing`` sentinel
231 if the key is not found.232233 Override this method to add custom lookup behavior.234 :meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this235 method. Don't call this method directly.236237 :param key: The variable name to look up.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 238why, one step back
238 """

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

lines 239–246why, one step back
239 if key in self.vars:
240 return self.vars[key]241242 if key in self.parent:243 return self.parent[key]244245 return missing246

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 247why, one step back
247 def get_exported(self) -> dict[str, t.Any]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 248–250why, one step back
248 """Get a new dict with the exported variables."""
249 return {k: self.vars[k] for k in self.exported_vars}250

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 251why, one step back
251 def get_all(self) -> dict[str, t.Any]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 252–262why, one step back
252 """Return the complete context as dict including the exported
253 variables. For optimizations reasons this might not return an254 actual copy so be careful with using it.255 """256 if not self.vars:257 return self.parent258 if not self.parent:259 return self.vars260 return dict(self.parent, **self.vars)261262 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 263why, one step back
263 def call(

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

lines 264–267why, one step back
264 __self, # noqa: B902
265 __obj: t.Callable[..., t.Any],266 *args: t.Any,267 **kwargs: t.Any,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 268why, one step back
268 ) -> t.Union[t.Any, "Undefined"]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 269–270why, one step back
269 """Call the callable with the arguments and keyword arguments
270 provided but inject the active context or environment as first

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 271–272why, one step back
271 argument if the callable has :func:`pass_context` or
272 :func:`pass_environment`.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 273–277why, one step back
273 """
274 if __debug__:275 __traceback_hide__ = True # noqa276277 # Allow callable classes to take a context

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 278–279why, one step back
278 if (
279 hasattr(__obj, "__call__") # noqa: B004

Merge branch '3.1.x'David Lordbefore adoption36b601f

line 280why, one step back
280 and _PassArg.from_obj(__obj.__call__) is not None

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 281why, one step back
281 ):

Merge branch '3.1.x'David Lordbefore adoption36b601f

line 282why, one step back
282 __obj = __obj.__call__

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 283why, one step back
283

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 284why, one step back
284 pass_arg = _PassArg.from_obj(__obj)

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 285why, one step back
285

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 286–297why, one step back
286 if pass_arg is _PassArg.context:
287 # the active context should have access to variables set in288 # loops and blocks without mutating the context itself289 if kwargs.get("_loop_vars"):290 __self = __self.derived(kwargs["_loop_vars"])291 if kwargs.get("_block_vars"):292 __self = __self.derived(kwargs["_block_vars"])293 args = (__self,) + args294 elif pass_arg is _PassArg.eval_context:295 args = (__self.eval_ctx,) + args296 elif pass_arg is _PassArg.environment:297 args = (__self.environment,) + args

Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb

lines 298–300why, one step back
298
299 kwargs.pop("_block_vars", None)300 kwargs.pop("_loop_vars", None)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 301why, one step back
301

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 302–309why, one step back
302 try:
303 return __obj(*args, **kwargs)304 except StopIteration:305 return __self.environment.undefined(306 "value was undefined because a callable raised a"307 " StopIteration exception"308 )309

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 310why, one step back
310 def derived(self, locals: dict[str, t.Any] | None = None) -> "Context":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 311–321why, one step back
311 """Internal helper function to create a derived context. This is
312 used in situations where the system needs a new context in the same313 template that is independent.314 """315 context = new_context(316 self.environment, self.name, {}, self.get_all(), True, None, locals317 )318 context.eval_ctx = self.eval_ctx319 context.blocks.update((k, list(v)) for k, v in self.blocks.items())320 return context321

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 322–324why, one step back
322 keys = _dict_method_all(dict.keys)
323 values = _dict_method_all(dict.values)324 items = _dict_method_all(dict.items)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 325why, one step back
325

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 326why, one step back
326 def __contains__(self, name: str) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 327–328why, one step back
327 return name in self.vars or name in self.parent
328

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 329why, one step back
329 def __getitem__(self, key: str) -> t.Any:

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

lines 330–331why, one step back
330 """Look up a variable by name with ``[]`` syntax, or raise a
331 ``KeyError`` if the key is not found.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 332–333why, one step back
332 """
333 item = self.resolve_or_missing(key)

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

line 334why, one step back
334

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 335–336why, one step back
335 if item is missing:
336 raise KeyError(key)

Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0

line 337why, one step back
337

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 338–339why, one step back
338 return item
339

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 340–341why, one step back
340 def __repr__(self) -> str:
341 return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 342–346why, one step back
342
343344class BlockReference:345 """One block on a template reference."""346

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 347–350why, one step back
347 def __init__(
348 self,349 name: str,350 context: "Context",

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 351why, one step back
351 stack: list[t.Callable[["Context"], t.Iterator[str]]],

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 352–353why, one step back
352 depth: int,
353 ) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 354–359why, one step back
354 self.name = name
355 self._context = context356 self._stack = stack357 self._depth = depth358359 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 360why, one step back
360 def super(self) -> t.Union["BlockReference", "Undefined"]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 361–368why, one step back
361 """Super the block."""
362 if self._depth + 1 >= len(self._stack):363 return self._context.environment.undefined(364 f"there is no parent block called {self.name!r}.", name="super"365 )366 return BlockReference(self.name, self._context, self._stack, self._depth + 1)367368 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 369why, one step back
369 async def _async_call(self) -> str:

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 370why, one step back
370 rv = self._context.environment.concat( # type: ignore

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 371–372why, one step back
371 [x async for x in self._stack[self._depth](self._context)] # type: ignore
372 )

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 373–379why, one step back
373
374 if self._context.eval_ctx.autoescape:375 return Markup(rv)376377 return rv378379 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 380why, one step back
380 def __call__(self) -> str:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 381why, one step back
381 if self._context.environment.is_async:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 382why, one step back
382 return self._async_call() # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 383why, one step back
383

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 384–386why, one step back
384 rv = self._context.environment.concat( # type: ignore
385 self._stack[self._depth](self._context)386 )

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 387why, one step back
387

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 388why, one step back
388 if self._context.eval_ctx.autoescape:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 389–390why, one step back
389 return Markup(rv)
390

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 391–401why, one step back
391 return rv
392393394class LoopContext:395 """A wrapper iterable for dynamic ``for`` loops, with information396 about the loop and iteration.397 """398399 #: Current iteration of the loop, starting at 0.400 index0 = -1401

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 402why, one step back
402 _length: int | None = None

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 403–406why, one step back
403 _after: t.Any = missing
404 _current: t.Any = missing405 _before: t.Any = missing406 _last_changed_value: t.Any = missing

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 407why, one step back
407

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 408–410why, one step back
408 def __init__(
409 self,410 iterable: t.Iterable[V],

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 411why, one step back
411 undefined: type["Undefined"],

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 412–414why, one step back
412 recurse: t.Optional["LoopRenderFunc"] = None,
413 depth0: int = 0,414 ) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 415–430why, one step back
415 """
416 :param iterable: Iterable to wrap.417 :param undefined: :class:`Undefined` class to use for next and418 previous items.419 :param recurse: The function to render the loop body when the420 loop is marked recursive.421 :param depth0: Incremented when looping recursively.422 """423 self._iterable = iterable424 self._iterator = self._to_iterator(iterable)425 self._undefined = undefined426 self._recurse = recurse427 #: How many levels deep a recursive loop currently is, starting at 0.428 self.depth0 = depth0429430 @staticmethod

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 431why, one step back
431 def _to_iterator(iterable: t.Iterable[V]) -> t.Iterator[V]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 432–434why, one step back
432 return iter(iterable)
433434 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 435why, one step back
435 def length(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 436–444why, one step back
436 """Length of the iterable.
437438 If the iterable is a generator or otherwise does not have a439 size, it is eagerly evaluated to get a size.440 """441 if self._length is not None:442 return self._length443444 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 445why, one step back
445 self._length = len(self._iterable) # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 446–452why, one step back
446 except TypeError:
447 iterable = list(self._iterator)448 self._iterator = self._to_iterator(iterable)449 self._length = len(iterable) + self.index + (self._after is not missing)450451 return self._length452

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 453why, one step back
453 def __len__(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 454–456why, one step back
454 return self.length
455456 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 457why, one step back
457 def depth(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 458–461why, one step back
458 """How many levels deep a recursive loop currently is, starting at 1."""
459 return self.depth0 + 1460461 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 462why, one step back
462 def index(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 463–466why, one step back
463 """Current iteration of the loop, starting at 1."""
464 return self.index0 + 1465466 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 467why, one step back
467 def revindex0(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 468–474why, one step back
468 """Number of iterations from the end of the loop, ending at 0.
469470 Requires calculating :attr:`length`.471 """472 return self.length - self.index473474 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 475why, one step back
475 def revindex(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 476–482why, one step back
476 """Number of iterations from the end of the loop, ending at 1.
477478 Requires calculating :attr:`length`.479 """480 return self.length - self.index0481482 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 483why, one step back
483 def first(self) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 484–486why, one step back
484 """Whether this is the first iteration of the loop."""
485 return self.index0 == 0486

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 487why, one step back
487 def _peek_next(self) -> t.Any:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 488–499why, one step back
488 """Return the next element in the iterable, or :data:`missing`
489 if the iterable is exhausted. Only peeks one item ahead, caching490 the result in :attr:`_last` for use in subsequent checks. The491 cache is reset when :meth:`__next__` is called.492 """493 if self._after is not missing:494 return self._after495496 self._after = next(self._iterator, missing)497 return self._after498499 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 500why, one step back
500 def last(self) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 501–509why, one step back
501 """Whether this is the last iteration of the loop.
502503 Causes the iterable to advance early. See504 :func:`itertools.groupby` for issues this can cause.505 The :func:`groupby` filter avoids that issue.506 """507 return self._peek_next() is missing508509 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 510why, one step back
510 def previtem(self) -> t.Union[t.Any, "Undefined"]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 511–519why, one step back
511 """The item in the previous iteration. Undefined during the
512 first iteration.513 """514 if self.first:515 return self._undefined("there is no previous item")516517 return self._before518519 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 520why, one step back
520 def nextitem(self) -> t.Union[t.Any, "Undefined"]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 521–525why, one step back
521 """The item in the next iteration. Undefined during the last
522 iteration.523524 Causes the iterable to advance early. See525 :func:`itertools.groupby` for issues this can cause.

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 526why, one step back
526 The :func:`jinja-filters.groupby` filter avoids that issue.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 527–534why, one step back
527 """
528 rv = self._peek_next()529530 if rv is missing:531 return self._undefined("there is no next item")532533 return rv534

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 535why, one step back
535 def cycle(self, *args: V) -> V:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 536–545why, one step back
536 """Return a value from the given args, cycling through based on
537 the current :attr:`index0`.538539 :param args: One or more values to cycle through.540 """541 if not args:542 raise TypeError("no items for cycling given")543544 return args[self.index0 % len(args)]545

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 546why, one step back
546 def changed(self, *value: t.Any) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 547–557why, one step back
547 """Return ``True`` if previously called with a different value
548 (including when called for the first time).549550 :param value: One or more values to compare to the last call.551 """552 if self._last_changed_value != value:553 self._last_changed_value = value554 return True555556 return False557

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 558why, one step back
558 def __iter__(self) -> "LoopContext":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 559–560why, one step back
559 return self
560

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 561why, one step back
561 def __next__(self) -> tuple[t.Any, "LoopContext"]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 562–573why, one step back
562 if self._after is not missing:
563 rv = self._after564 self._after = missing565 else:566 rv = next(self._iterator)567568 self.index0 += 1569 self._before = self._current570 self._current = rv571 return rv, self572573 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 574why, one step back
574 def __call__(self, iterable: t.Iterable[V]) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 575–586why, one step back
575 """When iterating over nested data, render the body of the loop
576 recursively with the given inner iterable data.577578 The loop must have the ``recursive`` marker for this to work.579 """580 if self._recurse is None:581 raise TypeError(582 "The loop must have the 'recursive' marker to be called recursively."583 )584585 return self._recurse(iterable, self._recurse, depth=self.depth)586

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 587–588why, one step back
587 def __repr__(self) -> str:
588 return f"<{type(self).__name__} {self.index}/{self.length}>"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 589–590why, one step back
589
590

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 591why, one step back
591class AsyncLoopContext(LoopContext):

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 592–593why, one step back
592 _iterator: t.AsyncIterator[t.Any] # type: ignore
593

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 594why, one step back
594 @staticmethod

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 595why, one step back
595 def _to_iterator( # type: ignore

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 596why, one step back
596 iterable: t.Iterable[V] | t.AsyncIterable[V],

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 597why, one step back
597 ) -> t.AsyncIterator[V]:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 598–600why, one step back
598 return auto_aiter(iterable)
599600 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 601why, one step back
601 async def length(self) -> int: # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 602–605why, one step back
602 if self._length is not None:
603 return self._length604605 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 606why, one step back
606 self._length = len(self._iterable) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 607–614why, one step back
607 except TypeError:
608 iterable = [x async for x in self._iterator]609 self._iterator = self._to_iterator(iterable)610 self._length = len(iterable) + self.index + (self._after is not missing)611612 return self._length613614 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 615why, one step back
615 async def revindex0(self) -> int: # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 616–618why, one step back
616 return await self.length - self.index
617618 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 619why, one step back
619 async def revindex(self) -> int: # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 620–621why, one step back
620 return await self.length - self.index0
621

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 622why, one step back
622 async def _peek_next(self) -> t.Any:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 623–633why, one step back
623 if self._after is not missing:
624 return self._after625626 try:627 self._after = await self._iterator.__anext__()628 except StopAsyncIteration:629 self._after = missing630631 return self._after632633 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 634why, one step back
634 async def last(self) -> bool: # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 635–637why, one step back
635 return await self._peek_next() is missing
636637 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 638why, one step back
638 async def nextitem(self) -> t.Union[t.Any, "Undefined"]:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 639–645why, one step back
639 rv = await self._peek_next()
640641 if rv is missing:642 return self._undefined("there is no next item")643644 return rv645

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 646why, one step back
646 def __aiter__(self) -> "AsyncLoopContext":

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 647–648why, one step back
647 return self
648

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 649why, one step back
649 async def __anext__(self) -> tuple[t.Any, "AsyncLoopContext"]:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 650–661why, one step back
650 if self._after is not missing:
651 rv = self._after652 self._after = missing653 else:654 rv = await self._iterator.__anext__()655656 self.index0 += 1657 self._before = self._current658 self._current = rv659 return rv, self660661

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 662–666why, one step back
662class Macro:
663 """Wraps a macro function."""664665 def __init__(666 self,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 667–669why, one step back
667 environment: "Environment",
668 func: t.Callable[..., str],669 name: str,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 670why, one step back
670 arguments: list[str],

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 671–673why, one step back
671 catch_kwargs: bool,
672 catch_varargs: bool,673 caller: bool,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 674why, one step back
674 default_autoescape: bool | None = None,

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 675–684why, one step back
675 ):
676 self._environment = environment677 self._func = func678 self._argument_count = len(arguments)679 self.name = name680 self.arguments = arguments681 self.catch_kwargs = catch_kwargs682 self.catch_varargs = catch_varargs683 self.caller = caller684 self.explicit_caller = "caller" in arguments

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 685why, one step back
685

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 686why, one step back
686 if default_autoescape is None:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 687–691why, one step back
687 if callable(environment.autoescape):
688 default_autoescape = environment.autoescape(None)689 else:690 default_autoescape = environment.autoescape691

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 692–694why, one step back
692 self._default_autoescape = default_autoescape
693694 @internalcode

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 695why, one step back
695 @pass_eval_context

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 696why, one step back
696 def __call__(self, *args: t.Any, **kwargs: t.Any) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 697–771why, one step back
697 # This requires a bit of explanation, In the past we used to
698 # decide largely based on compile-time information if a macro is699 # safe or unsafe. While there was a volatile mode it was largely700 # unused for deciding on escaping. This turns out to be701 # problematic for macros because whether a macro is safe depends not702 # on the escape mode when it was defined, but rather when it was used.703 #704 # Because however we export macros from the module system and705 # there are historic callers that do not pass an eval context (and706 # will continue to not pass one), we need to perform an instance707 # check here.708 #709 # This is considered safe because an eval context is not a valid710 # argument to callables otherwise anyway. Worst case here is711 # that if no eval context is passed we fall back to the compile712 # time autoescape flag.713 if args and isinstance(args[0], EvalContext):714 autoescape = args[0].autoescape715 args = args[1:]716 else:717 autoescape = self._default_autoescape718719 # try to consume the positional arguments720 arguments = list(args[: self._argument_count])721 off = len(arguments)722723 # For information why this is necessary refer to the handling724 # of caller in the `macro_body` handler in the compiler.725 found_caller = False726727 # if the number of arguments consumed is not the number of728 # arguments expected we start filling in keyword arguments729 # and defaults.730 if off != self._argument_count:731 for name in self.arguments[len(arguments) :]:732 try:733 value = kwargs.pop(name)734 except KeyError:735 value = missing736 if name == "caller":737 found_caller = True738 arguments.append(value)739 else:740 found_caller = self.explicit_caller741742 # it's important that the order of these arguments does not change743 # if not also changed in the compiler's `function_scoping` method.744 # the order is caller, keyword arguments, positional arguments!745 if self.caller and not found_caller:746 caller = kwargs.pop("caller", None)747 if caller is None:748 caller = self._environment.undefined("No caller defined", name="caller")749 arguments.append(caller)750751 if self.catch_kwargs:752 arguments.append(kwargs)753 elif kwargs:754 if "caller" in kwargs:755 raise TypeError(756 f"macro {self.name!r} was invoked with two values for the special"757 " caller argument. This is most likely a bug."758 )759 raise TypeError(760 f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"761 )762 if self.catch_varargs:763 arguments.append(args[self._argument_count :])764 elif len(args) > self._argument_count:765 raise TypeError(766 f"macro {self.name!r} takes not more than"767 f" {len(self.arguments)} argument(s)"768 )769770 return self._invoke(arguments, autoescape)771

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 772why, one step back
772 async def _async_invoke(self, arguments: list[t.Any], autoescape: bool) -> str:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 773why, one step back
773 rv = await self._func(*arguments) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 774–777why, one step back
774
775 if autoescape:776 return Markup(rv)777

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 778why, one step back
778 return rv # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 779why, one step back
779

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 780why, one step back
780 def _invoke(self, arguments: list[t.Any], autoescape: bool) -> str:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 781why, one step back
781 if self._environment.is_async:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 782why, one step back
782 return self._async_invoke(arguments, autoescape) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 783why, one step back
783

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 784why, one step back
784 rv = self._func(*arguments)

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 785why, one step back
785

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 786–787why, one step back
786 if autoescape:
787 rv = Markup(rv)

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 788why, one step back
788

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 789–790why, one step back
789 return rv
790

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 791why, one step back
791 def __repr__(self) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 792why, one step back
792 name = "anonymous" if self.name is None else repr(self.name)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 793why, one step back
793 return f"<{type(self).__name__} {name}>"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 794–796why, one step back
794
795796class Undefined:

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 797–798why, one step back
797 """The default undefined type. This can be printed, iterated, and treated as
798 a boolean. Any other operation will raise an :exc:`UndefinedError`.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 799–817why, one step back
799
800 >>> foo = Undefined(name='foo')801 >>> str(foo)802 ''803 >>> not foo804 True805 >>> foo + 42806 Traceback (most recent call last):807 ...808 jinja2.exceptions.UndefinedError: 'foo' is undefined809 """810811 __slots__ = (812 "_undefined_hint",813 "_undefined_obj",814 "_undefined_name",815 "_undefined_exception",816 )817

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 818–819why, one step back
818 def __init__(
819 self,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 820why, one step back
820 hint: str | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 821why, one step back
821 obj: t.Any = missing,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 822why, one step back
822 name: str | None = None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 823why, one step back
823 exc: type[TemplateRuntimeError] = UndefinedError,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 824why, one step back
824 ) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 825–830why, one step back
825 self._undefined_hint = hint
826 self._undefined_obj = obj827 self._undefined_name = name828 self._undefined_exception = exc829830 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 831why, one step back
831 def _undefined_message(self) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 832–852why, one step back
832 """Build a message about the undefined value based on how it was
833 accessed.834 """835 if self._undefined_hint:836 return self._undefined_hint837838 if self._undefined_obj is missing:839 return f"{self._undefined_name!r} is undefined"840841 if not isinstance(self._undefined_name, str):842 return (843 f"{object_type_repr(self._undefined_obj)} has no"844 f" element {self._undefined_name!r}"845 )846847 return (848 f"{object_type_repr(self._undefined_obj)!r} has no"849 f" attribute {self._undefined_name!r}"850 )851852 @internalcode

Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0

lines 853–855why, one step back
853 def _fail_with_undefined_error(
854 self, *args: t.Any, **kwargs: t.Any855 ) -> "te.NoReturn":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 856–861why, one step back
856 """Raise an :exc:`UndefinedError` when operations are performed
857 on the undefined value.858 """859 raise self._undefined_exception(self._undefined_message)860861 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 862why, one step back
862 def __getattr__(self, name: str) -> t.Any:

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 863–867why, one step back
863 # Raise AttributeError on requests for names that appear to be unimplemented
864 # 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:] == "__":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 868why, one step back
868 raise AttributeError(name)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 869why, one step back
869

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 870–877why, one step back
870 return self._fail_with_undefined_error()
871872 __add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error873 __mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error874 __truediv__ = __rtruediv__ = _fail_with_undefined_error875 __floordiv__ = __rfloordiv__ = _fail_with_undefined_error876 __mod__ = __rmod__ = _fail_with_undefined_error877 __pos__ = __neg__ = _fail_with_undefined_error

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoption35c69e9

line 878why, one step back
878 __call__ = __getitem__ = _fail_with_undefined_error

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 879–882why, one step back
879 __lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
880 __int__ = __float__ = __complex__ = _fail_with_undefined_error881 __pow__ = __rpow__ = _fail_with_undefined_error882

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 883why, one step back
883 def __eq__(self, other: t.Any) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 884–885why, one step back
884 return type(self) is type(other)
885

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 886why, one step back
886 def __ne__(self, other: t.Any) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 887–888why, one step back
887 return not self.__eq__(other)
888

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 889why, one step back
889 def __hash__(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 890–891why, one step back
890 return id(type(self))
891

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 892why, one step back
892 def __str__(self) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 893–894why, one step back
893 return ""
894

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 895why, one step back
895 def __len__(self) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 896–897why, one step back
896 return 0
897

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 898why, one step back
898 def __iter__(self) -> t.Iterator[t.Any]:

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

line 899why, one step back
899 yield from ()

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 900why, one step back
900

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 901why, one step back
901 async def __aiter__(self) -> t.AsyncIterator[t.Any]:

Merge pull request #1294 from Jafnee/chainableundefined-aiter-bugDavid Lordbefore adoption06c7c6f

lines 902–904why, one step back
902 for _ in ():
903 yield904

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 905why, one step back
905 def __bool__(self) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 906–907why, one step back
906 return False
907

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 908why, one step back
908 def __repr__(self) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 909–911why, one step back
909 return "Undefined"
910911

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 912why, one step back
912def make_logging_undefined(

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

lines 913–914why, one step back
913 logger: t.Optional["logging.Logger"] = None, base: type[Undefined] = Undefined
914) -> type[Undefined]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 915–939why, one step back
915 """Given a logger object this returns a new undefined class that will
916 log certain failures. It will log iterations and printing. If no917 logger is given a default logger is created.918919 Example::920921 logger = logging.getLogger(__name__)922 LoggingUndefined = make_logging_undefined(923 logger=logger,924 base=Undefined925 )926927 .. versionadded:: 2.8928929 :param logger: the logger to use. If not provided, a default logger930 is created.931 :param base: the base class to add logging functionality to. This932 defaults to :class:`Undefined`.933 """934 if logger is None:935 import logging936937 logger = logging.getLogger(__name__)938 logger.addHandler(logging.StreamHandler(sys.stderr))939

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 940why, one step back
940 def _log_message(undef: Undefined) -> None:

Merge branch '3.1.x'David Lordbefore adoptionc0e4f69

line 941why, one step back
941 logger.warning("Template variable warning: %s", undef._undefined_message)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 942why, one step back
942

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 943–947why, one step back
943 class LoggingUndefined(base): # type: ignore
944 __slots__ = ()945946 def _fail_with_undefined_error( # type: ignore947 self, *args: t.Any, **kwargs: t.Any

Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0

line 948why, one step back
948 ) -> "te.NoReturn":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 949why, one step back
949 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 950why, one step back
950 super()._fail_with_undefined_error(*args, **kwargs)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 951why, one step back
951 except self._undefined_exception as e:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 952why, one step back
952 logger.error("Template variable error: %s", e) # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 953–954why, one step back
953 raise e
954

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 955why, one step back
955 def __str__(self) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 956why, one step back
956 _log_message(self)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 957why, one step back
957 return super().__str__() # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 958why, one step back
958

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 959why, one step back
959 def __iter__(self) -> t.Iterator[t.Any]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 960why, one step back
960 _log_message(self)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 961why, one step back
961 return super().__iter__() # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 962why, one step back
962

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 963why, one step back
963 def __bool__(self) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 964why, one step back
964 _log_message(self)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 965why, one step back
965 return super().__bool__() # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 966–987why, one step back
966
967 return LoggingUndefined968969970class ChainableUndefined(Undefined):971 """An undefined that is chainable, where both ``__getattr__`` and972 ``__getitem__`` return itself rather than raising an973 :exc:`UndefinedError`.974975 >>> foo = ChainableUndefined(name='foo')976 >>> str(foo.bar['baz'])977 ''978 >>> foo.bar['baz'] + 42979 Traceback (most recent call last):980 ...981 jinja2.exceptions.UndefinedError: 'foo' is undefined982983 .. versionadded:: 2.11.0984 """985986 __slots__ = ()987

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 988–989why, one step back
988 def __html__(self) -> str:
989 return str(self)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 990why, one step back
990

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 991–1000why, one step back
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)1000

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1001–1002why, one step back
1001 return self
1002

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 1003–1004why, one step back
1003 def __getitem__(self, _name: str) -> "ChainableUndefined": # type: ignore[override]
1004 return self

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1005–1022why, one step back
1005
10061007class DebugUndefined(Undefined):1008 """An undefined that returns the debug info when printed.10091010 >>> foo = DebugUndefined(name='foo')1011 >>> str(foo)1012 '{{ foo }}'1013 >>> not foo1014 True1015 >>> foo + 421016 Traceback (most recent call last):1017 ...1018 jinja2.exceptions.UndefinedError: 'foo' is undefined1019 """10201021 __slots__ = ()1022

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1023why, one step back
1023 def __str__(self) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1024–1027why, one step back
1024 if self._undefined_hint:
1025 message = f"undefined value printed: {self._undefined_hint}"10261027 elif self._undefined_obj is missing:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1028why, one step back
1028 message = self._undefined_name # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1029–1061why, one step back
1029
1030 else:1031 message = (1032 f"no such element: {object_type_repr(self._undefined_obj)}"1033 f"[{self._undefined_name!r}]"1034 )10351036 return f"{{{{ {message} }}}}"103710381039class StrictUndefined(Undefined):1040 """An undefined that barks on print and iteration as well as boolean1041 tests and all kinds of comparisons. In other words: you can do nothing1042 with it except checking if it's defined using the `defined` test.10431044 >>> foo = StrictUndefined(name='foo')1045 >>> str(foo)1046 Traceback (most recent call last):1047 ...1048 jinja2.exceptions.UndefinedError: 'foo' is undefined1049 >>> not foo1050 Traceback (most recent call last):1051 ...1052 jinja2.exceptions.UndefinedError: 'foo' is undefined1053 >>> foo + 421054 Traceback (most recent call last):1055 ...1056 jinja2.exceptions.UndefinedError: 'foo' is undefined1057 """10581059 __slots__ = ()1060 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error1061 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoption35c69e9

line 1062why, one step back
1062 __contains__ = Undefined._fail_with_undefined_error