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
Provenance
- Commit
0ee5eb4- Tree
3277a64- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
20477c6
21 files changed+151 added−113 removed
modified:src/jinja2/__init__.py+1 added
1 """Jinja is a template engine written in pure Python. It provides a2 non-XML syntax that supports inline expressions and an optional3 sandboxed environment.4 """5+6 from .bccache import BytecodeCache as BytecodeCache7 from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache8 from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache9 from .environment import Environment as Environment29 unmodified linesmodified:src/jinja2/async_utils.py+1 added-1 removed
45 unmodified lines46 47 if need_eval_context:48 wrapper = pass_eval_context(wrapper)49 50- wrapper.jinja_async_variant = True50+ wrapper.jinja_async_variant = True # type: ignore[attr-defined]51 return wrapper52 53 return decorator54 30 unmodified linesmodified:src/jinja2/bccache.py+6 added-4 removed
3 unmodified lines4 5 Situations where this is useful are often forking web applications that6 are initialized on the first request.7 """8+9 import errno10 import fnmatch11 import marshal12 import os7 unmodified lines20 from types import CodeType21 22 if t.TYPE_CHECKING:23 import typing_extensions as te24+25 from .environment import Environment26 27 class _MemcachedClient(te.Protocol):26- def get(self, key: str) -> bytes:27- ...28+ def get(self, key: str) -> bytes: ...29 29- 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: ...33 34 35 bc_version = 536 # Magic bytes to identify Jinja bytecode cache files. Contains the372 unmodified linesmodified:src/jinja2/compiler.py+14 added-10 removed
1 """Compiles nodes from the parser into Python code."""2+3 import typing as t4 from contextlib import contextmanager5 from functools import update_wrapper6 from io import StringIO17 unmodified lines24 from .visitor import NodeVisitor25 26 if t.TYPE_CHECKING:27 import typing_extensions as te28+29 from .environment import Environment30 31 F = t.TypeVar("F", bound=t.Callable[..., t.Any])32 28 unmodified lines61 def _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 lines84 ) -> 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 lines132 133 if type(value) in {tuple, list, set, frozenset}:134 return all(has_safe_repr(v) for v in value)135 136- 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())138 139 return False140 409 unmodified lines550 551 for node in nodes:552 visitor.visit(node)553 554+ 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 lines831 ) -> None:832 assert frame is None, "no root frame allowed"833 eval_ctx = EvalContext(self.environment, self.name)834 832- from .runtime import exported, async_exported835+ from .runtime import async_exported836+ from .runtime import exported837 838 if self.environment.is_async:839 exported_names = sorted(exported + async_exported)840 else:1120 unmodified linesmodified:src/jinja2/environment.py+28 added-20 removed
1 """Classes for managing templates and their runtime and compile time2 options.3 """4+5 import os6 import typing7 import typing as t8 import weakref11 unmodified lines20 from .defaults import BLOCK_END_STRING21 from .defaults import BLOCK_START_STRING22 from .defaults import COMMENT_END_STRING23 from .defaults import COMMENT_START_STRING23-from .defaults import DEFAULT_FILTERS24+from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]25 from .defaults import DEFAULT_NAMESPACE26 from .defaults import DEFAULT_POLICIES26-from .defaults import DEFAULT_TESTS27+from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]28 from .defaults import KEEP_TRAILING_NEWLINE29 from .defaults import LINE_COMMENT_PREFIX30 from .defaults import LINE_STATEMENT_PREFIX31 from .defaults import LSTRIP_BLOCKS23 unmodified lines55 from .utils import missing56 57 if t.TYPE_CHECKING:58 import typing_extensions as te59+60 from .bccache import BytecodeCache61 from .ext import Extension62 from .loaders import BaseLoader63 16 unmodified lines80 81 82 def 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 lines92 return LRUCache(size) # type: ignore93 94 95 def 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 None101 100- if type(cache) is dict:102+ if type(cache) is dict: # noqa E721103 return {}104 105 return LRUCache(cache.capacity) # type: ignore106 564 unmodified lines671 for ext in self.iter_extensions():672 stream = ext.filter_stream(stream) # type: ignore673 674 if not isinstance(stream, TokenStream):673- stream = TokenStream(stream, name, filename) # type: ignore675+ stream = TokenStream(stream, name, filename)676 677 return stream678 679 def _generate(32 unmodified lines712 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: ...717 718 @typing.overload719 def compile(720 self,1 unmodified line722 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: ...727 728 @internalcode729 def compile(730 self,82 unmodified lines813 return TemplateExpression(template, undefined_to_none)814 815 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 lines857 with open(os.path.join(target, filename), "wb") as f:858 f.write(data.encode("utf8"))859 860 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 ZipInfo865 866 zip_file = ZipFile(867 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]868 )550 unmodified lines1419 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 )1427 1428 @internalcode1429 def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":162 unmodified lines1592 self.disable_buffering()1593 1594 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 lines1610 if isinstance(fp, str):1611 if encoding is None:1612 encoding = "utf-8"1613 1609- fp = open(fp, "wb")1614+ real_fp: t.IO[bytes] = open(fp, "wb")1615 close = True1616+ else:1617+ real_fp = fp1618+1619 try:1620 if encoding is not None:1621 iterable = (x.encode(encoding, errors) for x in self) # type: ignore1622 else:1623 iterable = self # type: ignore1624 1617- 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()1633 1634 def disable_buffering(self) -> None:1635 """Disable the output buffering."""1636 self._next = partial(next, self._gen)39 unmodified linesmodified:src/jinja2/ext.py+10 added-9 removed
1 """Extension API for adding custom tags and behavior."""2+3 import pprint4 import re5 import typing as t6 11 unmodified lines18 from .utils import pass_context19 20 if t.TYPE_CHECKING:21 import typing_extensions as te22+23 from .lexer import Token24 from .lexer import TokenStream25 from .parser import Parser26 27 class _TranslationsBasic(te.Protocol):26- def gettext(self, message: str) -> str:27- ...28+ def gettext(self, message: str) -> str: ...29 30 def ngettext(self, singular: str, plural: str, n: int) -> str:31 pass32 33 class _TranslationsContext(_TranslationsBasic):33- def pgettext(self, context: str, message: str) -> str:34- ...34+ def pgettext(self, context: str, message: str) -> str: ...35 36- 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: ...39 40 _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]41 42 175 unmodified lines218 return pgettext219 220 221 def _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 lines294 # Python < 3.8295 pgettext = translations.pgettext296 else:297 297- def pgettext(c: str, s: str) -> str:298+ def pgettext(c: str, s: str) -> str: # type: ignore[misc]299 return s300 301 if hasattr(translations, "npgettext"):302 npgettext = translations.npgettext303 else:304 304- 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 p307 308 self._install_callables(309 gettext=translations.gettext,561 unmodified linesmodified:src/jinja2/filters.py+29 added-29 removed
1 """Built-in template filters used with the ``|`` operator."""2+3 import math4 import random5 import re6 import typing21 unmodified lines28 from .utils import urlize29 30 if t.TYPE_CHECKING:31 import typing_extensions as te32+33 from .environment import Environment34 from .nodes import EvalContext35 from .runtime import Context36 from .sandbox import SandboxedEnvironment # noqa: F40186 unmodified lines123 return attrgetter124 125 126 def _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 lines143 return escape(str(value))144 145 146 def 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.150 151 Basic wrapper around :func:`urllib.parse.quote` when given a401 unmodified lines553 554 @pass_eval_context555 def 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 the49 unmodified lines611 612 @async_variant(sync_do_join) # type: ignore613 async 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 lines1161 1162 1163 class _GroupTuple(t.NamedTuple):1164 grouper: t.Any1163- list: t.List1165+ list: t.List[t.Any]1166 1167 # Use the regular tuple repr to hide this subclass if users print1168 # out the value during debugging.1169 def __repr__(self) -> str:187 unmodified lines1357 return str(value)1358 1359 1360 @typing.overload1359-def do_reverse(value: str) -> str:1360- ...1361+def do_reverse(value: str) -> str: ...1362 1363 1364 @typing.overload1364-def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1365- ...1365+def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...1366 1367 1368 def 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 other45 unmodified lines1415 1416 1417 @typing.overload1418 def 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]: ...1425 1426 1427 @typing.overload1428 def 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]: ...1435 1436 1437 @pass_context1438 def 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 lines1486 1487 @typing.overload1488 def 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]: ...1495 1496 1497 @typing.overload1498 def 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]: ...1505 1506 1507 @async_variant(sync_do_map) # type: ignore1508 async 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)1516 1517 async for item in auto_aiter(value):184 unmodified lines1702 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)1703 1704 1705 def 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 lines1731 1732 1733 def 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 lines1766 1767 def 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 lines1782 1783 async 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 linesmodified:src/jinja2/lexer.py+3 added-1 removed
1 unmodified line2 is used to do some preprocessing. It filters out invalid operators like3 the bitshift operators we don't allow in templates. It separates4 template code and python code in expressions.5 """6+7 import re8 import typing as t9 from ast import literal_eval10 from collections import deque4 unmodified lines15 from .utils import LRUCache16 17 if t.TYPE_CHECKING:18 import typing_extensions as te19+20 from .environment import Environment21 22 # cache for the lexers. Exists in order to be able to have multiple23 # environments with the same lexer424 unmodified lines448 449 return lexer450 451 450-class OptionalLStrip(tuple):452+class 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 linesmodified:src/jinja2/loaders.py+8 added-2 removed
1 """API and implementations for loading templates from different data2 sources.3 """4+5 import importlib.util6 import os7 import posixpath8 import sys168 unmodified lines177 """178 179 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 lines603 604 has_source_access = False605 606 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}"613 614 # create a fake module that looks for the templates in the53 unmodified linesmodified:src/jinja2/meta.py+1 added
1 """Functions that expose information about templates that might be2 interesting for introspection.3 """4+5 import typing as t6 7 from . import nodes8 from .compiler import CodeGenerator104 unmodified linesmodified:src/jinja2/nodes.py+3 added-1 removed
1 """AST nodes generated by the parser for the compiler. Also provides2 some node tree helper functions used by the parser and compiler in order3 to normalize nodes.4 """5+6 import inspect7 import operator8 import typing as t9 from collections import deque3 unmodified lines13 from .utils import _PassArg14 15 if t.TYPE_CHECKING:16 import typing_extensions as te17+18 from .environment import Environment19 20 _NodeBound = t.TypeVar("_NodeBound", bound="Node")21 35 unmodified lines57 automatically forwarded to the child."""58 59 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 linesmodified:src/jinja2/optimizer.py+1 added
5 unmodified lines6 want. For example, loop unrolling doesn't work because unrolled loops7 would have a different scope. The solution would be a second syntax tree8 that stored the scoping rules.9 """10+11 import typing as t12 13 from . import nodes14 from .visitor import NodeTransformer34 unmodified linesmodified:src/jinja2/parser.py+13 added-6 removed
1 """Parse tokens from the lexer into nodes for the compiler."""2+3 import typing4 import typing as t5 6 from . import nodes3 unmodified lines10 from .lexer import describe_token_expr11 12 if t.TYPE_CHECKING:13 import typing_extensions as te14+15 from .environment import Environment16 17 _ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)18 _MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)439 unmodified lines458 459 @typing.overload460 def parse_assign_target(461 self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...460- ) -> nodes.Name:461- ...462+ ) -> nodes.Name: ...463 464 @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]: ...472 473 def parse_assign_target(474 self,475 with_tuple: bool = True,384 unmodified lines860 args.append(None)861 862 return nodes.Slice(lineno=lineno, *args) # noqa: B026863 864- 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 = None82 unmodified lines958 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 linesmodified:src/jinja2/runtime.py+9 added-4 removed
1 """The runtime functions and state used by compiled templates."""2+3 import functools4 import sys5 import typing as t6 from collections import abc21 unmodified lines28 F = t.TypeVar("F", bound=t.Callable[..., t.Any])29 30 if t.TYPE_CHECKING:31 import logging32+33 import typing_extensions as te34+35 from .environment import Environment36 37 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: ...44 45 46 # these variables are exported to the template runtime47 exported = [212 unmodified lines260 return dict(self.parent, **self.vars)261 262 @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` or318 unmodified lines590 _iterator: t.AsyncIterator[t.Any] # type: ignore591 592 @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)597 598 @property458 unmodified linesmodified:src/jinja2/sandbox.py+5 added-4 removed
1 """A sandbox layer that ensures unsafe operations cannot be performed.2 Useful when the template itself comes from an untrusted source.3 """4+5 import operator6 import types7 import typing as t7-from _string import formatter_field_name_split # type: ignore8 from collections import abc9 from collections import deque10 from string import Formatter11 12+from _string import formatter_field_name_split # type: ignore13 from markupsafe import EscapeFormatter14 from markupsafe import Markup15 16 from .environment import Environment20 unmodified lines37 38 #: unsafe attributes on async generators39 UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}40 40-_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 lines80 ),81 )82 83 83-def inspect_format_method(callable: t.Callable) -> t.Optional[str]:84+def 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 None261 unmodified lines350 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 linesmodified:src/jinja2/tests.py+3 added-2 removed
1 """Built-in template tests used with the ``is`` operator."""2+3 import operator4 import typing as t5 from collections import abc6 from numbers import Number162 unmodified lines169 that are iterable.170 """171 try:172 len(value)172- value.__getitem__173+ value.__getitem__ # noqa B018174 except Exception:175 return False176 177 return True26 unmodified lines204 """Check if the value is escaped."""205 return hasattr(value, "__html__")206 207 207-def test_in(value: t.Any, seq: t.Container) -> bool:208+def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:209 """Check if value is in seq.210 211 .. versionadded:: 2.10212 """44 unmodified linesmodified:src/jinja2/utils.py+2 added-2 removed
150 unmodified lines151 if not silent:152 raise153 154 155-def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:155+def 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 lines449 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:450 self.__dict__.update(d)451 self._postinit()452 453- def __getnewargs__(self) -> t.Tuple:453+ def __getnewargs__(self) -> t.Tuple[t.Any, ...]:454 return (self.capacity,)455 456 def copy(self) -> "LRUCache":457 """Return a shallow copy of the instance."""298 unmodified linesmodified:src/jinja2/visitor.py+2 added-2 removed
1 """API for traversing the AST nodes. Implemented by the compiler and2 meta introspection.3 """4+5 import typing as t6 7 from .nodes import Node8 9 if t.TYPE_CHECKING:10 import typing_extensions as te11 12 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: ...14 15 16 class NodeVisitor:17 """Walks the abstract syntax tree and call visitor functions for every75 unmodified linesmodified:tests/test_api.py+3 added-2 removed
148 unmodified lines149 t = env.from_string("{{ foo }}")150 assert t.render(foo="<foo>") == "<foo>"151 152 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 SandboxedEnvironment155 156 env = SandboxedEnvironment()157 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")158 105 unmodified lines264 pytest.raises(UndefinedError, t.render, test=test)265 266 def test_undefined_and_special_attributes(self):267 with pytest.raises(AttributeError):267- Undefined("Foo").__dict__268+ Undefined("Foo").__dict__ # noqa B018269 270 def test_undefined_attribute_error(self):271 # Django's LazyObject turns the __class__ attribute into a272 # property that resolves the wrapped function. If that wrapped163 unmodified linesmodified:tests/test_inheritance.py+8 added-14 removed
363 unmodified lines364 365 366 class 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' %}373 374 {% macro my_macro() %}375 my_macro2 unmodified lines378 {% block inner_box %}379 {{ my_macro() }}380 {% endblock %}381 """,383- "details.html": """\382+ "details.html": """\383 {% extends 'standard.html' %}384 385 {% macro my_macro() %}386 my_macro7 unmodified lines394 {% endblock %}395 {% endblock %}396 {% endblock %}397 """,399- "standard.html": """398+ "standard.html": """399 {% block content %} {% 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"]404 405 def test_double_extends(self, env):406 """Ensures that a template with more than 1 {% extends ... %} usage407 raises a ``TemplateError``.3 unmodified linesmodified:tests/test_regression.py+1 added
597 unmodified lines598 assert tmpl.render(values=[]) == "0"599 600 def test_markup_and_chainable_undefined(self):601 from markupsafe import Markup602+603 from jinja2.runtime import ChainableUndefined604 605 assert str(Markup(ChainableUndefined())) == ""606 139 unmodified lines