Skip to content
Myr

satisfy formatter, linter, and strict mypy

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

authored by David Lord · committed by David Lord · parent 20477c6 · Browse files · 21 files+151 added−113 removed
This commit

State

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

Diff stats

21 files+151 added−113 removed

  • tests:+12 added−16 removed
  • other:+139 added−97 removed

21 files+151 added−113 removed

modified:src/jinja2/__init__.py+1 added
1"""Jinja is a template engine written in pure Python. It provides a2non-XML syntax that supports inline expressions and an optional3sandboxed environment.4"""56from .bccache import BytecodeCache as BytecodeCache7from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache8from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache9from .environment import Environment as Environment
29 unmodified lines
modified:src/jinja2/async_utils.py+1 added-1 removed
45 unmodified lines
4647 if need_eval_context:48 wrapper = pass_eval_context(wrapper)4950 wrapper.jinja_async_variant = True50 wrapper.jinja_async_variant = True # type: ignore[attr-defined]51 return wrapper5253 return decorator54
30 unmodified lines
modified:src/jinja2/bccache.py+6 added-4 removed
3 unmodified lines
45Situations where this is useful are often forking web applications that6are initialized on the first request.7"""89import errno10import fnmatch11import marshal12import os
7 unmodified lines
20from types import CodeType2122if t.TYPE_CHECKING:23 import typing_extensions as te2425 from .environment import Environment2627 class _MemcachedClient(te.Protocol):26 def get(self, key: str) -> bytes:27 ...28 def get(self, key: str) -> bytes: ...2929 def set(self, key: str, value: bytes, timeout: t.Optional[int] = None) -> None:30 ...30 def set(31 self, key: str, value: bytes, timeout: t.Optional[int] = None32 ) -> None: ...333435bc_version = 536# Magic bytes to identify Jinja bytecode cache files. Contains the
372 unmodified lines
modified:src/jinja2/compiler.py+14 added-10 removed
1"""Compiles nodes from the parser into Python code."""23import typing as t4from contextlib import contextmanager5from functools import update_wrapper6from io import StringIO
17 unmodified lines
24from .visitor import NodeVisitor2526if t.TYPE_CHECKING:27 import typing_extensions as te2829 from .environment import Environment3031F = t.TypeVar("F", bound=t.Callable[..., t.Any])32
28 unmodified lines
61def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:62 @optimizeconst63 def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:64 if (63 self.environment.sandboxed64 and op in self.environment.intercepted_binops # type: ignore65 self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore66 ):67 self.write(f"environment.call_binop(context, {op!r}, ")68 self.visit(node.left, frame)69 self.write(", ")
14 unmodified lines
84) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:85 @optimizeconst86 def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:87 if (87 self.environment.sandboxed88 and op in self.environment.intercepted_unops # type: ignore88 self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore89 ):90 self.write(f"environment.call_unop(context, {op!r}, ")91 self.visit(node.node, frame)92 else:
39 unmodified lines
132133 if type(value) in {tuple, list, set, frozenset}:134 return all(has_safe_repr(v) for v in value)135136 if type(value) is dict:136 if type(value) is dict: # noqa E721137 return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())138139 return False140
409 unmodified lines
550551 for node in nodes:552 visitor.visit(node)553554 for id_map, names, dependency in (555 (self.filters, visitor.filters, "filters"),554 for id_map, names, dependency in (self.filters, visitor.filters, "filters"), (555 self.tests,556 visitor.tests,557 "tests",556 (557 self.tests,558 visitor.tests,559 "tests",560 ),561 ):562 for name in sorted(names):563 if name not in id_map:564 id_map[name] = self.temporary_identifier()
266 unmodified lines
831 ) -> None:832 assert frame is None, "no root frame allowed"833 eval_ctx = EvalContext(self.environment, self.name)834832 from .runtime import exported, async_exported835 from .runtime import async_exported836 from .runtime import exported837838 if self.environment.is_async:839 exported_names = sorted(exported + async_exported)840 else:
1120 unmodified lines
modified:src/jinja2/environment.py+28 added-20 removed
1"""Classes for managing templates and their runtime and compile time2options.3"""45import os6import typing7import typing as t8import weakref
11 unmodified lines
20from .defaults import BLOCK_END_STRING21from .defaults import BLOCK_START_STRING22from .defaults import COMMENT_END_STRING23from .defaults import COMMENT_START_STRING23from .defaults import DEFAULT_FILTERS24from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]25from .defaults import DEFAULT_NAMESPACE26from .defaults import DEFAULT_POLICIES26from .defaults import DEFAULT_TESTS27from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]28from .defaults import KEEP_TRAILING_NEWLINE29from .defaults import LINE_COMMENT_PREFIX30from .defaults import LINE_STATEMENT_PREFIX31from .defaults import LSTRIP_BLOCKS
23 unmodified lines
55from .utils import missing5657if t.TYPE_CHECKING:58 import typing_extensions as te5960 from .bccache import BytecodeCache61 from .ext import Extension62 from .loaders import BaseLoader63
16 unmodified lines
808182def create_cache(83 size: int,82) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:84) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:85 """Return the cache class for the given size."""86 if size == 0:87 return None88
3 unmodified lines
92 return LRUCache(size) # type: ignore939495def copy_cache(94 cache: t.Optional[t.MutableMapping],95) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:96 cache: t.Optional[t.MutableMapping[t.Any, t.Any]],97) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:98 """Create an empty copy of the given cache."""99 if cache is None:100 return None101100 if type(cache) is dict:102 if type(cache) is dict: # noqa E721103 return {}104105 return LRUCache(cache.capacity) # type: ignore106
564 unmodified lines
671 for ext in self.iter_extensions():672 stream = ext.filter_stream(stream) # type: ignore673674 if not isinstance(stream, TokenStream):673 stream = TokenStream(stream, name, filename) # type: ignore675 stream = TokenStream(stream, name, filename)676677 return stream678679 def _generate(
32 unmodified lines
712 name: t.Optional[str] = None,713 filename: t.Optional[str] = None,714 raw: "te.Literal[False]" = False,715 defer_init: bool = False,714 ) -> CodeType:715 ...716 ) -> CodeType: ...717718 @typing.overload719 def compile(720 self,
1 unmodified line
722 name: t.Optional[str] = None,723 filename: t.Optional[str] = None,724 raw: "te.Literal[True]" = ...,725 defer_init: bool = False,725 ) -> str:726 ...726 ) -> str: ...727728 @internalcode729 def compile(730 self,
82 unmodified lines
813 return TemplateExpression(template, undefined_to_none)814815 def compile_templates(816 self,817 target: t.Union[str, os.PathLike],817 target: t.Union[str, "os.PathLike[str]"],818 extensions: t.Optional[t.Collection[str]] = None,819 filter_func: t.Optional[t.Callable[[str], bool]] = None,820 zip: t.Optional[str] = "deflated",821 log_function: t.Optional[t.Callable[[str], None]] = None,
35 unmodified lines
857 with open(os.path.join(target, filename), "wb") as f:858 f.write(data.encode("utf8"))859860 if zip is not None:861 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED861 from zipfile import ZIP_DEFLATED862 from zipfile import ZIP_STORED863 from zipfile import ZipFile864 from zipfile import ZipInfo865866 zip_file = ZipFile(867 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]868 )
550 unmodified lines
1419 becomes unavailable in async mode.1420 """1421 ctx = self.new_context(vars, shared, locals)1422 return TemplateModule(1420 self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore1423 self,1424 ctx,1425 [x async for x in self.root_render_func(ctx)], # type: ignore1426 )14271428 @internalcode1429 def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":
162 unmodified lines
1592 self.disable_buffering()15931594 def dump(1595 self,1591 fp: t.Union[str, t.IO],1596 fp: t.Union[str, t.IO[bytes]],1597 encoding: t.Optional[str] = None,1598 errors: t.Optional[str] = "strict",1599 ) -> None:1600 """Dump the complete stream into a file or file-like object.
9 unmodified lines
1610 if isinstance(fp, str):1611 if encoding is None:1612 encoding = "utf-8"16131609 fp = open(fp, "wb")1614 real_fp: t.IO[bytes] = open(fp, "wb")1615 close = True1616 else:1617 real_fp = fp16181619 try:1620 if encoding is not None:1621 iterable = (x.encode(encoding, errors) for x in self) # type: ignore1622 else:1623 iterable = self # type: ignore16241617 if hasattr(fp, "writelines"):1618 fp.writelines(iterable)1625 if hasattr(real_fp, "writelines"):1626 real_fp.writelines(iterable)1627 else:1628 for item in iterable:1621 fp.write(item)1629 real_fp.write(item)1630 finally:1631 if close:1624 fp.close()1632 real_fp.close()16331634 def disable_buffering(self) -> None:1635 """Disable the output buffering."""1636 self._next = partial(next, self._gen)
39 unmodified lines
modified:src/jinja2/ext.py+10 added-9 removed
1"""Extension API for adding custom tags and behavior."""23import pprint4import re5import typing as t6
11 unmodified lines
18from .utils import pass_context1920if t.TYPE_CHECKING:21 import typing_extensions as te2223 from .lexer import Token24 from .lexer import TokenStream25 from .parser import Parser2627 class _TranslationsBasic(te.Protocol):26 def gettext(self, message: str) -> str:27 ...28 def gettext(self, message: str) -> str: ...2930 def ngettext(self, singular: str, plural: str, n: int) -> str:31 pass3233 class _TranslationsContext(_TranslationsBasic):33 def pgettext(self, context: str, message: str) -> str:34 ...34 def pgettext(self, context: str, message: str) -> str: ...3536 def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:37 ...36 def npgettext(37 self, context: str, singular: str, plural: str, n: int38 ) -> str: ...3940 _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]4142
175 unmodified lines
218 return pgettext219220221def _make_new_npgettext(221 func: t.Callable[[str, str, str, int], str]222 func: t.Callable[[str, str, str, int], str],223) -> t.Callable[..., str]:224 @pass_context225 def npgettext(226 __context: Context,
67 unmodified lines
294 # Python < 3.8295 pgettext = translations.pgettext296 else:297297 def pgettext(c: str, s: str) -> str:298 def pgettext(c: str, s: str) -> str: # type: ignore[misc]299 return s300301 if hasattr(translations, "npgettext"):302 npgettext = translations.npgettext303 else:304304 def npgettext(c: str, s: str, p: str, n: int) -> str:305 def npgettext(c: str, s: str, p: str, n: int) -> str: # type: ignore[misc]306 return s if n == 1 else p307308 self._install_callables(309 gettext=translations.gettext,
561 unmodified lines
modified:src/jinja2/filters.py+29 added-29 removed
1"""Built-in template filters used with the ``|`` operator."""23import math4import random5import re6import typing
21 unmodified lines
28from .utils import urlize2930if t.TYPE_CHECKING:31 import typing_extensions as te3233 from .environment import Environment34 from .nodes import EvalContext35 from .runtime import Context36 from .sandbox import SandboxedEnvironment # noqa: F401
86 unmodified lines
123 return attrgetter124125126def _prepare_attribute_parts(125 attr: t.Optional[t.Union[str, int]]127 attr: t.Optional[t.Union[str, int]],128) -> t.List[t.Union[str, int]]:129 if attr is None:130 return []131
11 unmodified lines
143 return escape(str(value))144145146def do_urlencode(145 value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]147 value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],148) -> str:149 """Quote data for use in a URL path or query using UTF-8.150151 Basic wrapper around :func:`urllib.parse.quote` when given a
401 unmodified lines
553554@pass_eval_context555def sync_do_join(556 eval_ctx: "EvalContext",555 value: t.Iterable,557 value: t.Iterable[t.Any],558 d: str = "",559 attribute: t.Optional[t.Union[str, int]] = None,560) -> str:561 """Return a string which is the concatenation of the strings in the
49 unmodified lines
611612@async_variant(sync_do_join) # type: ignore613async def do_join(614 eval_ctx: "EvalContext",613 value: t.Union[t.AsyncIterable, t.Iterable],615 value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],616 d: str = "",617 attribute: t.Optional[t.Union[str, int]] = None,618) -> str:619 return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
541 unmodified lines
116111621163class _GroupTuple(t.NamedTuple):1164 grouper: t.Any1163 list: t.List1165 list: t.List[t.Any]11661167 # Use the regular tuple repr to hide this subclass if users print1168 # out the value during debugging.1169 def __repr__(self) -> str:
187 unmodified lines
1357 return str(value)135813591360@typing.overload1359def do_reverse(value: str) -> str:1360 ...1361def do_reverse(value: str) -> str: ...136213631364@typing.overload1364def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1365 ...1365def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...136613671368def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:1369 """Reverse the object or return an iterator that iterates over it the other
45 unmodified lines
141514161417@typing.overload1418def sync_do_map(1419 context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any1420) -> t.Iterable:1421 ...1419 context: "Context",1420 value: t.Iterable[t.Any],1421 name: str,1422 *args: t.Any,1423 **kwargs: t.Any,1424) -> t.Iterable[t.Any]: ...142514261427@typing.overload1428def sync_do_map(1429 context: "Context",1427 value: t.Iterable,1430 value: t.Iterable[t.Any],1431 *,1432 attribute: str = ...,1433 default: t.Optional[t.Any] = None,1431) -> t.Iterable:1432 ...1434) -> t.Iterable[t.Any]: ...143514361437@pass_context1438def sync_do_map(1437 context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any1438) -> t.Iterable:1439 context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any1440) -> t.Iterable[t.Any]:1441 """Applies a filter on a sequence of objects or looks up an attribute.1442 This is useful when dealing with lists of objects but you are really1443 only interested in a certain value of it.1444
41 unmodified lines
14861487@typing.overload1488def do_map(1489 context: "Context",1488 value: t.Union[t.AsyncIterable, t.Iterable],1490 value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1491 name: str,1492 *args: t.Any,1493 **kwargs: t.Any,1492) -> t.Iterable:1493 ...1494) -> t.Iterable[t.Any]: ...149514961497@typing.overload1498def do_map(1499 context: "Context",1499 value: t.Union[t.AsyncIterable, t.Iterable],1500 value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1501 *,1502 attribute: str = ...,1503 default: t.Optional[t.Any] = None,1503) -> t.Iterable:1504 ...1504) -> t.Iterable[t.Any]: ...150515061507@async_variant(sync_do_map) # type: ignore1508async def do_map(1509 context: "Context",1510 value: t.Union[t.AsyncIterable, t.Iterable],1510 value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1511 *args: t.Any,1512 **kwargs: t.Any,1513) -> t.AsyncIterable:1513) -> t.AsyncIterable[t.Any]:1514 if value:1515 func = prepare_map(context, args, kwargs)15161517 async for item in auto_aiter(value):
184 unmodified lines
1702 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)170317041705def prepare_map(1706 context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]1706 context: "Context", args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]1707) -> t.Callable[[t.Any], t.Any]:1708 if not args and "attribute" in kwargs:1709 attribute = kwargs.pop("attribute")1710 default = kwargs.pop("default", None)
20 unmodified lines
173117321733def prepare_select_or_reject(1734 context: "Context",1735 args: t.Tuple,1735 args: t.Tuple[t.Any, ...],1736 kwargs: t.Dict[str, t.Any],1737 modfunc: t.Callable[[t.Any], t.Any],1738 lookup_attr: bool,1739) -> t.Callable[[t.Any], t.Any]:
26 unmodified lines
17661767def select_or_reject(1768 context: "Context",1769 value: "t.Iterable[V]",1770 args: t.Tuple,1770 args: t.Tuple[t.Any, ...],1771 kwargs: t.Dict[str, t.Any],1772 modfunc: t.Callable[[t.Any], t.Any],1773 lookup_attr: bool,1774) -> "t.Iterator[V]":
7 unmodified lines
17821783async def async_select_or_reject(1784 context: "Context",1785 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1786 args: t.Tuple,1786 args: t.Tuple[t.Any, ...],1787 kwargs: t.Dict[str, t.Any],1788 modfunc: t.Callable[[t.Any], t.Any],1789 lookup_attr: bool,1790) -> "t.AsyncIterator[V]":
64 unmodified lines
modified:src/jinja2/lexer.py+3 added-1 removed
1 unmodified line
2is used to do some preprocessing. It filters out invalid operators like3the bitshift operators we don't allow in templates. It separates4template code and python code in expressions.5"""67import re8import typing as t9from ast import literal_eval10from collections import deque
4 unmodified lines
15from .utils import LRUCache1617if t.TYPE_CHECKING:18 import typing_extensions as te1920 from .environment import Environment2122# cache for the lexers. Exists in order to be able to have multiple23# environments with the same lexer
424 unmodified lines
448449 return lexer450451450class OptionalLStrip(tuple):452class OptionalLStrip(tuple): # type: ignore[type-arg]453 """A special tuple for marking a point in the state that can have454 lstrip applied.455 """456
412 unmodified lines
modified:src/jinja2/loaders.py+8 added-2 removed
1"""API and implementations for loading templates from different data2sources.3"""45import importlib.util6import os7import posixpath8import sys
168 unmodified lines
177 """178179 def __init__(180 self,180 searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],181 searchpath: t.Union[182 str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]183 ],184 encoding: str = "utf-8",185 followlinks: bool = False,186 ) -> None:187 if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
415 unmodified lines
603604 has_source_access = False605606 def __init__(604 self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]607 self,608 path: t.Union[609 str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]610 ],611 ) -> None:612 package_name = f"_jinja2_module_templates_{id(self):x}"613614 # create a fake module that looks for the templates in the
53 unmodified lines
modified:src/jinja2/meta.py+1 added
1"""Functions that expose information about templates that might be2interesting for introspection.3"""45import typing as t67from . import nodes8from .compiler import CodeGenerator
104 unmodified lines
modified:src/jinja2/nodes.py+3 added-1 removed
1"""AST nodes generated by the parser for the compiler. Also provides2some node tree helper functions used by the parser and compiler in order3to normalize nodes.4"""56import inspect7import operator8import typing as t9from collections import deque
3 unmodified lines
13from .utils import _PassArg1415if t.TYPE_CHECKING:16 import typing_extensions as te1718 from .environment import Environment1920_NodeBound = t.TypeVar("_NodeBound", bound="Node")21
35 unmodified lines
57 automatically forwarded to the child."""5859 def __new__(mcs, name, bases, d): # type: ignore60 for attr in "fields", "attributes":59 storage = []61 storage: t.List[t.Tuple[str, ...]] = []62 storage.extend(getattr(bases[0] if bases else object, attr, ()))63 storage.extend(d.get(attr, ()))64 assert len(bases) <= 1, "multiple inheritance not allowed"65 assert len(storage) == len(set(storage)), "layout conflict"
1141 unmodified lines
modified:src/jinja2/optimizer.py+1 added
5 unmodified lines
6want. For example, loop unrolling doesn't work because unrolled loops7would have a different scope. The solution would be a second syntax tree8that stored the scoping rules.9"""1011import typing as t1213from . import nodes14from .visitor import NodeTransformer
34 unmodified lines
modified:src/jinja2/parser.py+13 added-6 removed
1"""Parse tokens from the lexer into nodes for the compiler."""23import typing4import typing as t56from . import nodes
3 unmodified lines
10from .lexer import describe_token_expr1112if t.TYPE_CHECKING:13 import typing_extensions as te1415 from .environment import Environment1617_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)18_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)
439 unmodified lines
458459 @typing.overload460 def parse_assign_target(461 self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...460 ) -> nodes.Name:461 ...462 ) -> nodes.Name: ...463464 @typing.overload465 def parse_assign_target(466 self,467 with_tuple: bool = True,468 name_only: bool = False,469 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,470 with_namespace: bool = False,470 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:471 ...471 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...472473 def parse_assign_target(474 self,475 with_tuple: bool = True,
384 unmodified lines
860 args.append(None)861862 return nodes.Slice(lineno=lineno, *args) # noqa: B026863864 def parse_call_args(self) -> t.Tuple:864 def parse_call_args(865 self,866 ) -> t.Tuple[867 t.List[nodes.Expr],868 t.List[nodes.Keyword],869 t.Optional[nodes.Expr],870 t.Optional[nodes.Expr],871 ]:872 token = self.stream.expect("lparen")873 args = []874 kwargs = []875 dyn_args = None
82 unmodified lines
958 while self.stream.current.type == "dot":959 next(self.stream)960 name += "." + self.stream.expect("name").value961 dyn_args = dyn_kwargs = None955 kwargs = []962 kwargs: t.List[nodes.Keyword] = []963 if self.stream.current.type == "lparen":964 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()965 elif self.stream.current.type in {966 "name",
75 unmodified lines
modified:src/jinja2/runtime.py+9 added-4 removed
1"""The runtime functions and state used by compiled templates."""23import functools4import sys5import typing as t6from collections import abc
21 unmodified lines
28F = t.TypeVar("F", bound=t.Callable[..., t.Any])2930if t.TYPE_CHECKING:31 import logging3233 import typing_extensions as te3435 from .environment import Environment3637 class LoopRenderFunc(te.Protocol):38 def __call__(39 self,40 reciter: t.Iterable[V],41 loop_render_func: "LoopRenderFunc",42 depth: int = 0,40 ) -> str:41 ...43 ) -> str: ...444546# these variables are exported to the template runtime47exported = [
212 unmodified lines
260 return dict(self.parent, **self.vars)261262 @internalcode263 def call(262 __self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902264 __self,265 __obj: t.Callable[..., t.Any],266 *args: t.Any,267 **kwargs: t.Any, # noqa: B902268 ) -> t.Union[t.Any, "Undefined"]:269 """Call the callable with the arguments and keyword arguments270 provided but inject the active context or environment as first271 argument if the callable has :func:`pass_context` or
318 unmodified lines
590 _iterator: t.AsyncIterator[t.Any] # type: ignore591592 @staticmethod593 def _to_iterator( # type: ignore589 iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]]594 iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]],595 ) -> t.AsyncIterator[V]:596 return auto_aiter(iterable)597598 @property
458 unmodified lines
modified:src/jinja2/sandbox.py+5 added-4 removed
1"""A sandbox layer that ensures unsafe operations cannot be performed.2Useful when the template itself comes from an untrusted source.3"""45import operator6import types7import typing as t7from _string import formatter_field_name_split # type: ignore8from collections import abc9from collections import deque10from string import Formatter1112from _string import formatter_field_name_split # type: ignore13from markupsafe import EscapeFormatter14from markupsafe import Markup1516from .environment import Environment
20 unmodified lines
3738#: unsafe attributes on async generators39UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}4040_mutable_spec: t.Tuple[t.Tuple[t.Type, t.FrozenSet[str]], ...] = (41_mutable_spec: t.Tuple[t.Tuple[t.Type[t.Any], t.FrozenSet[str]], ...] = (42 (43 abc.MutableSet,44 frozenset(45 [
34 unmodified lines
80 ),81)828383def inspect_format_method(callable: t.Callable) -> t.Optional[str]:84def inspect_format_method(callable: t.Callable[..., t.Any]) -> t.Optional[str]:85 if not isinstance(86 callable, (types.MethodType, types.BuiltinMethodType)87 ) or callable.__name__ not in ("format", "format_map"):88 return None
261 unmodified lines
350 self,351 s: str,352 args: t.Tuple[t.Any, ...],353 kwargs: t.Dict[str, t.Any],353 format_func: t.Optional[t.Callable] = None,354 format_func: t.Optional[t.Callable[..., t.Any]] = None,355 ) -> str:356 """If a format call is detected, then this is routed through this357 method so that our safety sandbox can be used for it.358 """
71 unmodified lines
modified:src/jinja2/tests.py+3 added-2 removed
1"""Built-in template tests used with the ``is`` operator."""23import operator4import typing as t5from collections import abc6from numbers import Number
162 unmodified lines
169 that are iterable.170 """171 try:172 len(value)172 value.__getitem__173 value.__getitem__ # noqa B018174 except Exception:175 return False176177 return True
26 unmodified lines
204 """Check if the value is escaped."""205 return hasattr(value, "__html__")206207207def test_in(value: t.Any, seq: t.Container) -> bool:208def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:209 """Check if value is in seq.210211 .. versionadded:: 2.10212 """
44 unmodified lines
modified:src/jinja2/utils.py+2 added-2 removed
150 unmodified lines
151 if not silent:152 raise153154155def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:155def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO[t.Any]]:156 """Returns a file descriptor for the filename if that file exists,157 otherwise ``None``.158 """159 if not os.path.isfile(filename):
289 unmodified lines
449 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:450 self.__dict__.update(d)451 self._postinit()452453 def __getnewargs__(self) -> t.Tuple:453 def __getnewargs__(self) -> t.Tuple[t.Any, ...]:454 return (self.capacity,)455456 def copy(self) -> "LRUCache":457 """Return a shallow copy of the instance."""
298 unmodified lines
modified:src/jinja2/visitor.py+2 added-2 removed
1"""API for traversing the AST nodes. Implemented by the compiler and2meta introspection.3"""45import typing as t67from .nodes import Node89if t.TYPE_CHECKING:10 import typing_extensions as te1112 class VisitCallable(te.Protocol):12 def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:13 ...13 def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any: ...141516class NodeVisitor:17 """Walks the abstract syntax tree and call visitor functions for every
75 unmodified lines
modified:tests/test_api.py+3 added-2 removed
148 unmodified lines
149 t = env.from_string("{{ foo }}")150 assert t.render(foo="<foo>") == "<foo>"151152 def test_sandbox_max_range(self, env):153 from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE153 from jinja2.sandbox import MAX_RANGE154 from jinja2.sandbox import SandboxedEnvironment155156 env = SandboxedEnvironment()157 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")158
105 unmodified lines
264 pytest.raises(UndefinedError, t.render, test=test)265266 def test_undefined_and_special_attributes(self):267 with pytest.raises(AttributeError):267 Undefined("Foo").__dict__268 Undefined("Foo").__dict__ # noqa B018269270 def test_undefined_attribute_error(self):271 # Django's LazyObject turns the __class__ attribute into a272 # property that resolves the wrapped function. If that wrapped
163 unmodified lines
modified:tests/test_inheritance.py+8 added-14 removed
363 unmodified lines
364365366class TestBugFix:367 def test_fixed_macro_scoping_bug(self, env):368 assert (369 Environment(370 loader=DictLoader(371 {372 "test.html": """\368 assert Environment(369 loader=DictLoader(370 {371 "test.html": """\372 {% extends 'details.html' %}373374 {% macro my_macro() %}375 my_macro
2 unmodified lines
378 {% block inner_box %}379 {{ my_macro() }}380 {% endblock %}381 """,383 "details.html": """\382 "details.html": """\383 {% extends 'standard.html' %}384385 {% macro my_macro() %}386 my_macro
7 unmodified lines
394 {% endblock %}395 {% endblock %}396 {% endblock %}397 """,399 "standard.html": """398 "standard.html": """399 {% block content %}&nbsp;{% endblock %}400 """,402 }403 )401 }402 )405 .get_template("test.html")406 .render()407 .split()408 == ["outer_box", "my_macro"]409 )403 ).get_template("test.html").render().split() == ["outer_box", "my_macro"]404405 def test_double_extends(self, env):406 """Ensures that a template with more than 1 {% extends ... %} usage407 raises a ``TemplateError``.
3 unmodified lines
modified:tests/test_regression.py+1 added
597 unmodified lines
598 assert tmpl.render(values=[]) == "0"599600 def test_markup_and_chainable_undefined(self):601 from markupsafe import Markup602603 from jinja2.runtime import ChainableUndefined604605 assert str(Markup(ChainableUndefined())) == ""606
139 unmodified lines