Skip to content
Myr

runtime.py

This file

Path

src/jinja2/runtime.py

1,053 lines · 32.7 KiB · Python

Last changed by

Merge pull request #1511 from mkrizek/issue-1510David Lordbefore adoption7d72eb7

History of this file

Take it

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 2why, one step back
2import functools

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 3why, one step back
3import sys

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 5why, one step back
5from collections import abc

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 6–9why, one step back
6from itertools import chain
78from markupsafe import escape # noqa: F4019from markupsafe import Markup

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 10why, one step back
10from markupsafe import soft_str

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 11why, one step back
11

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 14–17why, one step back
14from .exceptions import TemplateNotFound # noqa: F401
15from .exceptions import TemplateRuntimeError # noqa: F40116from .exceptions import UndefinedError17from .nodes import EvalContext

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 19–23why, one step back
19from .utils import concat
20from .utils import internalcode21from .utils import missing22from .utils import Namespace # noqa: F40123from .utils import object_type_repr

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 25why, one step back
25

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 30–31why, one step back
30 import logging
31 import typing_extensions as te

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

lines 32–33why, one step back
32 from .environment import Environment
33

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 34–43why, one step back
34 class LoopRenderFunc(te.Protocol):
35 def __call__(36 self,37 reciter: t.Iterable[V],38 loop_render_func: "LoopRenderFunc",39 depth: int = 0,40 ) -> str:41 ...4243

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 44–53why, one step back
44# these variables are exported to the template runtime
45exported = [46 "LoopContext",47 "TemplateReference",48 "Macro",49 "Markup",50 "TemplateRuntimeError",51 "missing",52 "escape",53 "markup_join",

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 54why, one step back
54 "str_join",

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 55–58why, one step back
55 "identity",
56 "TemplateNotFound",57 "Namespace",58 "Undefined",

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 60why, one step back
60]

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 66–67why, one step back
66
67

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 69–74why, one step back
69 """Returns its argument. Useful for certain things in the
70 environment.71 """72 return x7374

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 76why, one step back
76 """Concatenation that escapes if necessary and converts to string."""

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 77why, one step back
77 buf = []

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 78why, one step back
78 iterator = map(soft_str, seq)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 79–81why, one step back
79 for arg in iterator:
80 buf.append(arg)81 if hasattr(arg, "__html__"):

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 82why, one step back
82 return Markup("").join(chain(buf, iterator))

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 83–85why, one step back
83 return concat(buf)
8485

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 87–90why, one step back
87 """Simple args to string conversion and concatenation."""
88 return concat(map(str, seq))8990

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 91why, one step back
91def new_context(

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 92–99why, one step back
92 environment: "Environment",
93 template_name: t.Optional[str],94 blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],95 vars: t.Optional[t.Dict[str, t.Any]] = None,96 shared: bool = False,97 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,98 locals: t.Optional[t.Mapping[str, t.Any]] = None,99) -> "Context":

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 100–111why, one step back
100 """Internal helper for context creation."""
101 if vars is None:102 vars = {}103 if shared:104 parent = vars105 else:106 parent = dict(globals or (), **vars)107 if locals:108 # if the parent is shared a copy should be created because109 # we don't want to modify the dict passed110 if shared:111 parent = dict(parent)

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 112why, one step back
112 for key, value in locals.items():

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 113–114why, one step back
113 if value is not missing:
114 parent[key] = value

Merge pull request #1241 from MLH-Fellowship/macros_with_globalsDavid Lordbefore adoption9b718ed

lines 115–117why, one step back
115 return environment.context_class(
116 environment, parent, template_name, blocks, globals=globals117 )

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 118–119why, one step back
118
119

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 120why, one step back
120class TemplateReference:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 121–122why, one step back
121 """The `self` in templates."""
122

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 124–125why, one step back
124 self.__context = context
125

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 132–133why, one step back
132
133

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 138why, one step back
138

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 140–141why, one step back
140
141

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 142why, one step back
142@abc.Mapping.register

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 143why, one step back
143class Context:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 163–170why, one step back
163 def __init__(
164 self,165 environment: "Environment",166 parent: t.Dict[str, t.Any],167 name: t.Optional[str],168 blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],169 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,170 ):

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 176why, one step back
176 self.name = name

Merge pull request #1241 from MLH-Fellowship/macros_with_globalsDavid Lordbefore adoption9b718ed

line 177why, one step back
177 self.globals_keys = set() if globals is None else set(globals)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 178–181why, one step back
178
179 # create the initial mapping of blocks. Whenever template inheritance180 # takes place the runtime will update this mapping with the new blocks181 # from the template.

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 182why, one step back
182 self.blocks = {k: [v] for k, v in blocks.items()}

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 183why, one step back
183

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 187–193why, one step back
187 """Render a parent block."""
188 try:189 blocks = self.blocks[name]190 index = blocks.index(current) + 1191 blocks[index]192 except LookupError:193 return self.environment.undefined(

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 194why, one step back
194 f"there is no parent block called {name!r}.", name="super"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 195–197why, one step back
195 )
196 return BlockReference(name, self, blocks, index)197

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 199–203why, one step back
199 """Look up a variable by name, or return a default if the key is
200 not found.201202 :param key: The variable name to look up.203 :param default: The value to return if the key is not found.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 204–209why, one step back
204 """
205 try:206 return self[key]207 except KeyError:208 return default209

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 211–218why, one step back
211 """Look up a variable by name, or return an :class:`Undefined`
212 object if the key is not found.213214 If you need to add custom behavior, override215 :meth:`resolve_or_missing`, not this method. The various lookup216 functions use that method, not this one.217218 :param key: The variable name to look up.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 219why, one step back
219 """

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

lines 220–221why, one step back
220 rv = self.resolve_or_missing(key)
221

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

line 224why, one step back
224

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 225–226why, one step back
225 return rv
226

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 228–235why, one step back
228 """Look up a variable by name, or return a ``missing`` sentinel
229 if the key is not found.230231 Override this method to add custom lookup behavior.232 :meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this233 method. Don't call this method directly.234235 :param key: The variable name to look up.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 236why, one step back
236 """

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

lines 237–244why, one step back
237 if key in self.vars:
238 return self.vars[key]239240 if key in self.parent:241 return self.parent[key]242243 return missing244

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 246why, one step back
246 """Get a new dict with the exported variables."""

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 247why, one step back
247 return {k: self.vars[k] for k in self.exported_vars}

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 248why, one step back
248

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 250–260why, one step back
250 """Return the complete context as dict including the exported
251 variables. For optimizations reasons this might not return an252 actual copy so be careful with using it.253 """254 if not self.vars:255 return self.parent256 if not self.parent:257 return self.vars258 return dict(self.parent, **self.vars)259260 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 261–263why, one step back
261 def call(
262 __self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902263 ) -> t.Union[t.Any, "Undefined"]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 268–272why, one step back
268 """
269 if __debug__:270 __traceback_hide__ = True # noqa271272 # Allow callable classes to take a context

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

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 275why, one step back
275 and _PassArg.from_obj(__obj.__call__) is not None # type: ignore

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

line 276why, one step back
276 ):

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 277why, one step back
277 __obj = __obj.__call__ # type: ignore

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 278why, one step back
278

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 280why, one step back
280

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 281–292why, one step back
281 if pass_arg is _PassArg.context:
282 # the active context should have access to variables set in283 # loops and blocks without mutating the context itself284 if kwargs.get("_loop_vars"):285 __self = __self.derived(kwargs["_loop_vars"])286 if kwargs.get("_block_vars"):287 __self = __self.derived(kwargs["_block_vars"])288 args = (__self,) + args289 elif pass_arg is _PassArg.eval_context:290 args = (__self.eval_ctx,) + args291 elif pass_arg is _PassArg.environment:292 args = (__self.environment,) + args

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

lines 293–295why, one step back
293
294 kwargs.pop("_block_vars", None)295 kwargs.pop("_loop_vars", None)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 296why, one step back
296

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 297–300why, one step back
297 try:
298 return __obj(*args, **kwargs)299 except StopIteration:300 return __self.environment.undefined(

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 301–302why, one step back
301 "value was undefined because a callable raised a"
302 " StopIteration exception"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 303–304why, one step back
303 )
304

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 306–313why, one step back
306 """Internal helper function to create a derived context. This is
307 used in situations where the system needs a new context in the same308 template that is independent.309 """310 context = new_context(311 self.environment, self.name, {}, self.get_all(), True, None, locals312 )313 context.eval_ctx = self.eval_ctx

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 314why, one step back
314 context.blocks.update((k, list(v)) for k, v in self.blocks.items())

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 315–316why, one step back
315 return context
316

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 317–319why, one step back
317 keys = _dict_method_all(dict.keys)
318 values = _dict_method_all(dict.values)319 items = _dict_method_all(dict.items)

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 320why, one step back
320

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 322–323why, one step back
322 return name in self.vars or name in self.parent
323

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

line 329why, one step back
329

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

line 332why, one step back
332

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 333–334why, one step back
333 return item
334

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 337–338why, one step back
337
338

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 339why, one step back
339class BlockReference:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 340–341why, one step back
340 """One block on a template reference."""
341

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 342–348why, one step back
342 def __init__(
343 self,344 name: str,345 context: "Context",346 stack: t.List[t.Callable[["Context"], t.Iterator[str]]],347 depth: int,348 ) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 349–354why, one step back
349 self.name = name
350 self._context = context351 self._stack = stack352 self._depth = depth353354 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 356–358why, one step back
356 """Super the block."""
357 if self._depth + 1 >= len(self._stack):358 return self._context.environment.undefined(

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 359why, one step back
359 f"there is no parent block called {self.name!r}.", name="super"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 360–363why, one step back
360 )
361 return BlockReference(self.name, self._context, self._stack, self._depth + 1)362363 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 364–367why, one step back
364 async def _async_call(self) -> str:
365 rv = concat(366 [x async for x in self._stack[self._depth](self._context)] # type: ignore367 )

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

lines 368–374why, one step back
368
369 if self._context.eval_ctx.autoescape:370 return Markup(rv)371372 return rv373374 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 378why, one step back
378

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 379why, one step back
379 rv = concat(self._stack[self._depth](self._context))

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

line 380why, one step back
380

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

lines 382–383why, one step back
382 return Markup(rv)
383

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 384–394why, one step back
384 return rv
385386387class LoopContext:388 """A wrapper iterable for dynamic ``for`` loops, with information389 about the loop and iteration.390 """391392 #: Current iteration of the loop, starting at 0.393 index0 = -1394

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

line 395why, one step back
395 _length: t.Optional[int] = None

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 396–399why, one step back
396 _after: t.Any = missing
397 _current: t.Any = missing398 _before: t.Any = missing399 _last_changed_value: t.Any = missing

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 400why, one step back
400

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 401–407why, one step back
401 def __init__(
402 self,403 iterable: t.Iterable[V],404 undefined: t.Type["Undefined"],405 recurse: t.Optional["LoopRenderFunc"] = None,406 depth0: int = 0,407 ) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 408–423why, one step back
408 """
409 :param iterable: Iterable to wrap.410 :param undefined: :class:`Undefined` class to use for next and411 previous items.412 :param recurse: The function to render the loop body when the413 loop is marked recursive.414 :param depth0: Incremented when looping recursively.415 """416 self._iterable = iterable417 self._iterator = self._to_iterator(iterable)418 self._undefined = undefined419 self._recurse = recurse420 #: How many levels deep a recursive loop currently is, starting at 0.421 self.depth0 = depth0422423 @staticmethod

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 425–427why, one step back
425 return iter(iterable)
426427 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 429–437why, one step back
429 """Length of the iterable.
430431 If the iterable is a generator or otherwise does not have a432 size, it is eagerly evaluated to get a size.433 """434 if self._length is not None:435 return self._length436437 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 439–445why, one step back
439 except TypeError:
440 iterable = list(self._iterator)441 self._iterator = self._to_iterator(iterable)442 self._length = len(iterable) + self.index + (self._after is not missing)443444 return self._length445

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 447–449why, one step back
447 return self.length
448449 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 451–454why, one step back
451 """How many levels deep a recursive loop currently is, starting at 1."""
452 return self.depth0 + 1453454 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 456–459why, one step back
456 """Current iteration of the loop, starting at 1."""
457 return self.index0 + 1458459 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 461–467why, one step back
461 """Number of iterations from the end of the loop, ending at 0.
462463 Requires calculating :attr:`length`.464 """465 return self.length - self.index466467 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 469–475why, one step back
469 """Number of iterations from the end of the loop, ending at 1.
470471 Requires calculating :attr:`length`.472 """473 return self.length - self.index0474475 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 477–479why, one step back
477 """Whether this is the first iteration of the loop."""
478 return self.index0 == 0479

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 481–492why, one step back
481 """Return the next element in the iterable, or :data:`missing`
482 if the iterable is exhausted. Only peeks one item ahead, caching483 the result in :attr:`_last` for use in subsequent checks. The484 cache is reset when :meth:`__next__` is called.485 """486 if self._after is not missing:487 return self._after488489 self._after = next(self._iterator, missing)490 return self._after491492 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 494–502why, one step back
494 """Whether this is the last iteration of the loop.
495496 Causes the iterable to advance early. See497 :func:`itertools.groupby` for issues this can cause.498 The :func:`groupby` filter avoids that issue.499 """500 return self._peek_next() is missing501502 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 504–512why, one step back
504 """The item in the previous iteration. Undefined during the
505 first iteration.506 """507 if self.first:508 return self._undefined("there is no previous item")509510 return self._before511512 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 514–518why, one step back
514 """The item in the next iteration. Undefined during the last
515 iteration.516517 Causes the iterable to advance early. See518 :func:`itertools.groupby` for issues this can cause.

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 520–527why, one step back
520 """
521 rv = self._peek_next()522523 if rv is missing:524 return self._undefined("there is no next item")525526 return rv527

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 529–538why, one step back
529 """Return a value from the given args, cycling through based on
530 the current :attr:`index0`.531532 :param args: One or more values to cycle through.533 """534 if not args:535 raise TypeError("no items for cycling given")536537 return args[self.index0 % len(args)]538

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 540–550why, one step back
540 """Return ``True`` if previously called with a different value
541 (including when called for the first time).542543 :param value: One or more values to compare to the last call.544 """545 if self._last_changed_value != value:546 self._last_changed_value = value547 return True548549 return False550

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 552–553why, one step back
552 return self
553

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 555–566why, one step back
555 if self._after is not missing:
556 rv = self._after557 self._after = missing558 else:559 rv = next(self._iterator)560561 self.index0 += 1562 self._before = self._current563 self._current = rv564 return rv, self565566 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 582–583why, one step back
582
583

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

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 587why, one step back
587 @staticmethod

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 588–590why, one step back
588 def _to_iterator( # type: ignore
589 iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]]590 ) -> t.AsyncIterator[V]:

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

lines 591–593why, one step back
591 return auto_aiter(iterable)
592593 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 595–598why, one step back
595 if self._length is not None:
596 return self._length597598 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 600–607why, one step back
600 except TypeError:
601 iterable = [x async for x in self._iterator]602 self._iterator = self._to_iterator(iterable)603 self._length = len(iterable) + self.index + (self._after is not missing)604605 return self._length606607 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 609–611why, one step back
609 return await self.length - self.index
610611 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 613–614why, one step back
613 return await self.length - self.index0
614

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 616–626why, one step back
616 if self._after is not missing:
617 return self._after618619 try:620 self._after = await self._iterator.__anext__()621 except StopAsyncIteration:622 self._after = missing623624 return self._after625626 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 628–630why, one step back
628 return await self._peek_next() is missing
629630 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 632–638why, one step back
632 rv = await self._peek_next()
633634 if rv is missing:635 return self._undefined("there is no next item")636637 return rv638

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 640–641why, one step back
640 return self
641

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 643–654why, one step back
643 if self._after is not missing:
644 rv = self._after645 self._after = missing646 else:647 rv = await self._iterator.__anext__()648649 self.index0 += 1650 self._before = self._current651 self._current = rv652 return rv, self653654

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 655why, one step back
655class Macro:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 656–659why, one step back
656 """Wraps a macro function."""
657658 def __init__(659 self,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 660–667why, one step back
660 environment: "Environment",
661 func: t.Callable[..., str],662 name: str,663 arguments: t.List[str],664 catch_kwargs: bool,665 catch_varargs: bool,666 caller: bool,667 default_autoescape: t.Optional[bool] = None,

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 668–677why, one step back
668 ):
669 self._environment = environment670 self._func = func671 self._argument_count = len(arguments)672 self.name = name673 self.arguments = arguments674 self.catch_kwargs = catch_kwargs675 self.catch_varargs = catch_varargs676 self.caller = caller677 self.explicit_caller = "caller" in arguments

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 678why, one step back
678

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 680–684why, one step back
680 if callable(environment.autoescape):
681 default_autoescape = environment.autoescape(None)682 else:683 default_autoescape = environment.autoescape684

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 685–687why, one step back
685 self._default_autoescape = default_autoescape
686687 @internalcode

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

line 688why, one step back
688 @pass_eval_context

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 690–748why, one step back
690 # This requires a bit of explanation, In the past we used to
691 # decide largely based on compile-time information if a macro is692 # safe or unsafe. While there was a volatile mode it was largely693 # unused for deciding on escaping. This turns out to be694 # problematic for macros because whether a macro is safe depends not695 # on the escape mode when it was defined, but rather when it was used.696 #697 # Because however we export macros from the module system and698 # there are historic callers that do not pass an eval context (and699 # will continue to not pass one), we need to perform an instance700 # check here.701 #702 # This is considered safe because an eval context is not a valid703 # argument to callables otherwise anyway. Worst case here is704 # that if no eval context is passed we fall back to the compile705 # time autoescape flag.706 if args and isinstance(args[0], EvalContext):707 autoescape = args[0].autoescape708 args = args[1:]709 else:710 autoescape = self._default_autoescape711712 # try to consume the positional arguments713 arguments = list(args[: self._argument_count])714 off = len(arguments)715716 # For information why this is necessary refer to the handling717 # of caller in the `macro_body` handler in the compiler.718 found_caller = False719720 # if the number of arguments consumed is not the number of721 # arguments expected we start filling in keyword arguments722 # and defaults.723 if off != self._argument_count:724 for name in self.arguments[len(arguments) :]:725 try:726 value = kwargs.pop(name)727 except KeyError:728 value = missing729 if name == "caller":730 found_caller = True731 arguments.append(value)732 else:733 found_caller = self.explicit_caller734735 # it's important that the order of these arguments does not change736 # if not also changed in the compiler's `function_scoping` method.737 # the order is caller, keyword arguments, positional arguments!738 if self.caller and not found_caller:739 caller = kwargs.pop("caller", None)740 if caller is None:741 caller = self._environment.undefined("No caller defined", name="caller")742 arguments.append(caller)743744 if self.catch_kwargs:745 arguments.append(kwargs)746 elif kwargs:747 if "caller" in kwargs:748 raise TypeError(

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 749–750why, one step back
749 f"macro {self.name!r} was invoked with two values for the special"
750 " caller argument. This is most likely a bug."

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 751–752why, one step back
751 )
752 raise TypeError(

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 753why, one step back
753 f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 754–758why, one step back
754 )
755 if self.catch_varargs:756 arguments.append(args[self._argument_count :])757 elif len(args) > self._argument_count:758 raise TypeError(

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 759–760why, one step back
759 f"macro {self.name!r} takes not more than"
760 f" {len(self.arguments)} argument(s)"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 761–764why, one step back
761 )
762763 return self._invoke(arguments, autoescape)764

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 765–766why, one step back
765 async def _async_invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:
766 rv = await self._func(*arguments) # type: ignore

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

lines 767–770why, one step back
767
768 if autoescape:769 return Markup(rv)770

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 772why, one step back
772

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

line 776why, one step back
776

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

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

line 778why, one step back
778

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 779–780why, one step back
779 if autoescape:
780 rv = Markup(rv)

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

line 781why, one step back
781

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 782–783why, one step back
782 return rv
783

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 787–788why, one step back
787
788

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 789why, one step back
789class Undefined:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 790–810why, one step back
790 """The default undefined type. This undefined type can be printed and
791 iterated over, but every other access will raise an :exc:`UndefinedError`:792793 >>> foo = Undefined(name='foo')794 >>> str(foo)795 ''796 >>> not foo797 True798 >>> foo + 42799 Traceback (most recent call last):800 ...801 jinja2.exceptions.UndefinedError: 'foo' is undefined802 """803804 __slots__ = (805 "_undefined_hint",806 "_undefined_obj",807 "_undefined_name",808 "_undefined_exception",809 )810

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 811–817why, one step back
811 def __init__(
812 self,813 hint: t.Optional[str] = None,814 obj: t.Any = missing,815 name: t.Optional[str] = None,816 exc: t.Type[TemplateRuntimeError] = UndefinedError,817 ) -> None:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 818–823why, one step back
818 self._undefined_hint = hint
819 self._undefined_obj = obj820 self._undefined_name = name821 self._undefined_exception = exc822823 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 825–831why, one step back
825 """Build a message about the undefined value based on how it was
826 accessed.827 """828 if self._undefined_hint:829 return self._undefined_hint830831 if self._undefined_obj is missing:

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 832why, one step back
832 return f"{self._undefined_name!r} is undefined"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 833why, one step back
833

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 834–837why, one step back
834 if not isinstance(self._undefined_name, str):
835 return (836 f"{object_type_repr(self._undefined_obj)} has no"837 f" element {self._undefined_name!r}"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 838–839why, one step back
838 )
839

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 840–842why, one step back
840 return (
841 f"{object_type_repr(self._undefined_obj)!r} has no"842 f" attribute {self._undefined_name!r}"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 843–845why, one step back
843 )
844845 @internalcode

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

lines 846–848why, one step back
846 def _fail_with_undefined_error(
847 self, *args: t.Any, **kwargs: t.Any848 ) -> "te.NoReturn":

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 849–854why, one step back
849 """Raise an :exc:`UndefinedError` when operations are performed
850 on the undefined value.851 """852 raise self._undefined_exception(self._undefined_message)853854 @internalcode

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 856–857why, one step back
856 if name[:2] == "__":
857 raise AttributeError(name)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 858why, one step back
858

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 859–860why, one step back
859 return self._fail_with_undefined_error()
860

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 861–866why, one step back
861 __add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error
862 __mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error863 __truediv__ = __rtruediv__ = _fail_with_undefined_error864 __floordiv__ = __rfloordiv__ = _fail_with_undefined_error865 __mod__ = __rmod__ = _fail_with_undefined_error866 __pos__ = __neg__ = _fail_with_undefined_error

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

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 868–870why, one step back
868 __lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
869 __int__ = __float__ = __complex__ = _fail_with_undefined_error870 __pow__ = __rpow__ = _fail_with_undefined_error

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 871why, one step back
871

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 873–874why, one step back
873 return type(self) is type(other)
874

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 876–877why, one step back
876 return not self.__eq__(other)
877

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 879–880why, one step back
879 return id(type(self))
880

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 882why, one step back
882 return ""

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 883why, one step back
883

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 885–886why, one step back
885 return 0
886

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 889why, one step back
889

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

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

lines 891–893why, one step back
891 for _ in ():
892 yield893

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 895–896why, one step back
895 return False
896

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 898–900why, one step back
898 return "Undefined"
899900

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 901–903why, one step back
901def make_logging_undefined(
902 logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined903) -> t.Type[Undefined]:

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 904–928why, one step back
904 """Given a logger object this returns a new undefined class that will
905 log certain failures. It will log iterations and printing. If no906 logger is given a default logger is created.907908 Example::909910 logger = logging.getLogger(__name__)911 LoggingUndefined = make_logging_undefined(912 logger=logger,913 base=Undefined914 )915916 .. versionadded:: 2.8917918 :param logger: the logger to use. If not provided, a default logger919 is created.920 :param base: the base class to add logging functionality to. This921 defaults to :class:`Undefined`.922 """923 if logger is None:924 import logging925926 logger = logging.getLogger(__name__)927 logger.addHandler(logging.StreamHandler(sys.stderr))928

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 929–932why, one step back
929 def _log_message(undef: Undefined) -> None:
930 logger.warning( # type: ignore931 "Template variable warning: %s", undef._undefined_message932 )

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 933why, one step back
933

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 934–938why, one step back
934 class LoggingUndefined(base): # type: ignore
935 __slots__ = ()936937 def _fail_with_undefined_error( # type: ignore938 self, *args: t.Any, **kwargs: t.Any

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 940why, one step back
940 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 944–945why, one step back
944 raise e
945

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 949why, one step back
949

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 953why, one step back
953

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

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

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 957–978why, one step back
957
958 return LoggingUndefined959960961class ChainableUndefined(Undefined):962 """An undefined that is chainable, where both ``__getattr__`` and963 ``__getitem__`` return itself rather than raising an964 :exc:`UndefinedError`.965966 >>> foo = ChainableUndefined(name='foo')967 >>> str(foo.bar['baz'])968 ''969 >>> foo.bar['baz'] + 42970 Traceback (most recent call last):971 ...972 jinja2.exceptions.UndefinedError: 'foo' is undefined973974 .. versionadded:: 2.11.0975 """976977 __slots__ = ()978

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 981why, one step back
981

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 982why, one step back
982 def __getattr__(self, _: str) -> "ChainableUndefined":

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 983–984why, one step back
983 return self
984

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 985why, one step back
985 __getitem__ = __getattr__ # type: ignore

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 986–1003why, one step back
986
987988class DebugUndefined(Undefined):989 """An undefined that returns the debug info when printed.990991 >>> foo = DebugUndefined(name='foo')992 >>> str(foo)993 '{{ foo }}'994 >>> not foo995 True996 >>> foo + 42997 Traceback (most recent call last):998 ...999 jinja2.exceptions.UndefinedError: 'foo' is undefined1000 """10011002 __slots__ = ()1003

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 1005–1008why, one step back
1005 if self._undefined_hint:
1006 message = f"undefined value printed: {self._undefined_hint}"10071008 elif self._undefined_obj is missing:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

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

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 1010–1014why, one step back
1010
1011 else:1012 message = (1013 f"no such element: {object_type_repr(self._undefined_obj)}"1014 f"[{self._undefined_name!r}]"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 1015–1016why, one step back
1015 )
1016

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 1017why, one step back
1017 return f"{{{{ {message} }}}}"

isolate bytecode cache testsDavid Lordbefore adoptiond312609

line 1018why, one step back
1018

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

line 1019why, one step back
1019

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 1020–1040why, one step back
1020class StrictUndefined(Undefined):
1021 """An undefined that barks on print and iteration as well as boolean1022 tests and all kinds of comparisons. In other words: you can do nothing1023 with it except checking if it's defined using the `defined` test.10241025 >>> foo = StrictUndefined(name='foo')1026 >>> str(foo)1027 Traceback (most recent call last):1028 ...1029 jinja2.exceptions.UndefinedError: 'foo' is undefined1030 >>> not foo1031 Traceback (most recent call last):1032 ...1033 jinja2.exceptions.UndefinedError: 'foo' is undefined1034 >>> foo + 421035 Traceback (most recent call last):1036 ...1037 jinja2.exceptions.UndefinedError: 'foo' is undefined1038 """10391040 __slots__ = ()

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 1041–1042why, one step back
1041 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error
1042 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error

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

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

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 1044–1045why, one step back
1044
1045

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 1046–1047why, one step back
1046# Remove slots attributes, after the metaclass is applied they are
1047# unneeded and contain wrong data for subclasses.

isolate bytecode cache testsDavid Lordbefore adoptiond312609

lines 1048–1053why, one step back
1048del (
1049 Undefined.__slots__,1050 ChainableUndefined.__slots__,1051 DebugUndefined.__slots__,1052 StrictUndefined.__slots__,1053)