fix type/lint/format findings
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Adam Englander · committed by David Lord · parent 51dbd89 · Browse files · 23 files·+262 added−283 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
23 files+262 added−283 removed
- tests:+8 added−14 removed
- other:+254 added−269 removed
Provenance
- Commit
a3dce7b- Tree
cca2db8- Author
Adam Englander <adam@voltaire.claims>- Committer
David Lord <davidism@gmail.com>- Parent
51dbd89
23 files changed+262 added−283 removed
modified:src/jinja2/async_utils.py+1 added-1 removed
93 unmodified lines94 95 96 async def auto_to_list(97 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",98-) -> t.List["V"]:98+) -> list["V"]:99 return [x async for x in auto_aiter(value)]modified:src/jinja2/compiler.py+14 added-16 removed
137 unmodified lines138 139 return False140 141 142-def find_undeclared(143- nodes: t.Iterable[nodes.Node], names: t.Iterable[str]144-) -> t.Set[str]:142+def find_undeclared(nodes: t.Iterable[nodes.Node], names: t.Iterable[str]) -> set[str]:143 """Check if the names passed are accessed undeclared. The return value144 is a set of all the undeclared names from the sequence of names found.145 """146 visitor = UndeclaredNameVisitor(names)103 unmodified lines250 class DependencyFinderVisitor(NodeVisitor):251 """A visitor that collects filter and test calls."""252 253 def __init__(self) -> None:256- self.filters: t.Set[str] = set()257- self.tests: t.Set[str] = set()254+ self.filters: set[str] = set()255+ self.tests: set[str] = set()256 257 def visit_Filter(self, node: nodes.Filter) -> None:258 self.generic_visit(node)259 self.filters.add(node.name)13 unmodified lines273 """274 275 def __init__(self, names: t.Iterable[str]) -> None:276 self.names = set(names)279- self.undeclared: t.Set[str] = set()277+ self.undeclared: set[str] = set()278 279 def visit_Name(self, node: nodes.Name) -> None:280 if node.ctx == "load" and node.name in self.names:281 self.undeclared.add(node.name)36 unmodified lines318 if optimized:319 self.optimizer = Optimizer(environment)320 321 # aliases for imports324- self.import_aliases: t.Dict[str, str] = {}322+ self.import_aliases: dict[str, str] = {}323 324 # a registry for all blocks. Because blocks are moved out325 # into the global python scope they are registered here328- self.blocks: t.Dict[str, nodes.Block] = {}326+ self.blocks: dict[str, nodes.Block] = {}327 328 # the number of extends statements so far329 self.extends_so_far = 0330 5 unmodified lines336 # the current line number337 self.code_lineno = 1338 339 # registry of all filters and tests (global, not block local)342- self.tests: t.Dict[str, str] = {}343- self.filters: t.Dict[str, str] = {}340+ self.tests: dict[str, str] = {}341+ self.filters: dict[str, str] = {}342 343 # the debug information346- self.debug_info: t.List[t.Tuple[int, int]] = []344+ self.debug_info: list[tuple[int, int]] = []345 self._write_debug_info: t.Optional[int] = None346 347 # the number of new lines before the next write()348 self._new_lines = 011 unmodified lines360 # the current indentation361 self._indentation = 0362 363 # Tracks toplevel assignments366- self._assign_stack: t.List[t.Set[str]] = []364+ self._assign_stack: list[set[str]] = []365 366 # Tracks parameter definition blocks369- self._param_def_block: t.List[t.Set[str]] = []367+ self._param_def_block: list[set[str]] = []368 369 # Tracks the current context.370 self._context_reference_stack = ["context"]371 238 unmodified lines610 return f"{self.choose_async()}def {name}"611 612 def macro_body(613 self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame616- ) -> t.Tuple[Frame, MacroRef]:614+ ) -> tuple[Frame, MacroRef]:615 """Dump the function def of a macro or call block."""616 frame = frame.inner()617 frame.symbols.analyze_node(node)618 macro_ref = MacroRef(node)889 unmodified lines1508 self.writeline("if parent_template is None:")1509 self.indent()1510 1511 finalize = self._make_finalize()1514- body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = []1512+ body: list[t.Union[list[t.Any], nodes.Expr]] = []1513 1514 # Evaluate constants at compile time if possible. Each item in1515 # body will be either a list of static data or a node to be1516 # evaluated at runtime.66 unmodified lines1583 # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However,1584 # it is only valid if it references a Namespace object. Emit a check for1585 # that for each ref here, before assignment code is emitted. This can't1586 # be done in visit_NSRef as the ref could be in the middle of a tuple.1589- seen_refs: t.Set[str] = set()1587+ seen_refs: set[str] = set()1588 1589 for nsref in node.find_all(nodes.NSRef):1590 if nsref.name in seen_refs:1591 # Only emit the check for each reference once, in case the same405 unmodified linesmodified:src/jinja2/debug.py+3 added-3 removed
126 unmodified lines127 except BaseException:128 return sys.exc_info()[2].tb_next # type: ignore129 130 131-def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:131+def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> dict[str, t.Any]:132 """Based on the runtime locals, get the context that would be133 available at that point in the template.134 """135 # Start with the current template context.136 ctx: t.Optional[Context] = real_locals.get("context")137 138 if ctx is not None:139- data: t.Dict[str, t.Any] = ctx.get_all().copy()139+ data: dict[str, t.Any] = ctx.get_all().copy()140 else:141 data = {}142 143 # Might be in a derived context that only sets local variables144 # rather than pushing a context. Local variables follow the scheme145 # l_depth_name. Find the highest-depth local that has a value for146 # each name.147- local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}147+ local_overrides: dict[str, tuple[int, t.Any]] = {}148 149 for name, value in real_locals.items():150 if not name.startswith("l_") or value is missing:151 # Not a template variable, or no longer relevant.21 unmodified linesmodified:src/jinja2/defaults.py+1 added-1 removed
34 unmodified lines35 "namespace": Namespace,36 }37 38 # default policies39-DEFAULT_POLICIES: t.Dict[str, t.Any] = {39+DEFAULT_POLICIES: dict[str, t.Any] = {40 "compiler.ascii_str": True,41 "urlize.rel": "noopener",42 "urlize.target": None,43 "urlize.extra_schemes": None,5 unmodified linesmodified:src/jinja2/environment.py+34 added-36 removed
64 unmodified lines65 66 67 # for direct template usage we have up to ten living environments68 @lru_cache(maxsize=10)69-def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound:69+def get_spontaneous_environment(cls: type[_env_bound], *args: t.Any) -> _env_bound:70 """Return a new spontaneous environment. A spontaneous environment71 is used for templates created directly rather than through an72 existing environment.73 6 unmodified lines80 81 82 def create_cache(83 size: int,84-) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[BaseLoader]", str], "Template"]]:84+) -> t.Optional[t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"]]:85 """Return the cache class for the given size."""86 if size == 0:87 return None88 4 unmodified lines93 94 95 def copy_cache(96 cache: t.Optional[97- t.MutableMapping[t.Tuple["weakref.ref[BaseLoader]", str], "Template"]97+ t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"]98 ],99-) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[BaseLoader]", str], "Template"]]:99+) -> t.Optional[t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"]]:100 """Create an empty copy of the given cache."""101 if cache is None:102 return None103 4 unmodified lines108 109 110 def load_extensions(111 environment: "Environment",112- extensions: t.Sequence[t.Union[str, t.Type["Extension"]]],113-) -> t.Dict[str, "Extension"]:112+ extensions: t.Sequence[t.Union[str, type["Extension"]]],113+) -> dict[str, "Extension"]:114 """Load the extensions from the list and bind it to the environment.115 Returns a dict of instantiated extensions.116 """117 result = {}118 119 for extension in extensions:120 if isinstance(extension, str):121- extension = t.cast(t.Type["Extension"], import_string(extension))121+ extension = t.cast(type["Extension"], import_string(extension))122 123 result[extension.identifier] = extension(environment)124 125 return result126 127 128 def _environment_config_check(environment: _env_bound) -> _env_bound:129 """Perform a sanity check on the environment."""130- assert issubclass(131- environment.undefined, Undefined132- ), "'undefined' must be a subclass of 'jinja2.Undefined'."130+ assert issubclass(environment.undefined, Undefined), (131+ "'undefined' must be a subclass of 'jinja2.Undefined'."132+ )133 assert (134 environment.block_start_string135 != environment.variable_start_string136 != environment.comment_start_string145 unmodified lines282 shared = False283 284 #: the class that is used for code generation. See285 #: :class:`~jinja2.compiler.CodeGenerator` for more information.286- code_generator_class: t.Type["CodeGenerator"] = CodeGenerator286+ code_generator_class: type["CodeGenerator"] = CodeGenerator287 288 concat = "".join289 290 #: the context class that is used for templates. See291 #: :class:`~jinja2.runtime.Context` for more information.292- context_class: t.Type[Context] = Context292+ context_class: type[Context] = Context293 294- template_class: t.Type["Template"]294+ template_class: type["Template"]295 296 def __init__(297 self,298 block_start_string: str = BLOCK_START_STRING,7 unmodified lines306 trim_blocks: bool = TRIM_BLOCKS,307 lstrip_blocks: bool = LSTRIP_BLOCKS,308 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,309 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,310- extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),310+ extensions: t.Sequence[t.Union[str, type["Extension"]]] = (),311 optimized: bool = True,312- undefined: t.Type[Undefined] = Undefined,312+ undefined: type[Undefined] = Undefined,313 finalize: t.Optional[t.Callable[..., t.Any]] = None,314 autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,315 loader: t.Optional["BaseLoader"] = None,316 cache_size: int = 400,26 unmodified lines343 self.newline_sequence = newline_sequence344 self.keep_trailing_newline = keep_trailing_newline345 346 # runtime information347- self.undefined: t.Type[Undefined] = undefined347+ self.undefined: type[Undefined] = undefined348 self.optimized = optimized349 self.finalize = finalize350 self.autoescape = autoescape351 16 unmodified lines368 369 self.is_async = enable_async370 _environment_config_check(self)371 372- def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:372+ def add_extension(self, extension: t.Union[str, type["Extension"]]) -> None:373 """Adds an extension after the environment was created.374 375 .. versionadded:: 2.5376 """21 unmodified lines398 trim_blocks: bool = missing,399 lstrip_blocks: bool = missing,400 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,401 keep_trailing_newline: bool = missing,402- extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,402+ extensions: t.Sequence[t.Union[str, type["Extension"]]] = missing,403 optimized: bool = missing,404- undefined: t.Type[Undefined] = missing,404+ undefined: type[Undefined] = missing,405 finalize: t.Optional[t.Callable[..., t.Any]] = missing,406 autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,407 loader: t.Optional["BaseLoader"] = missing,408 cache_size: int = missing,218 unmodified lines627 self,628 source: str,629 name: t.Optional[str] = None,630 filename: t.Optional[str] = None,631- ) -> t.Iterator[t.Tuple[int, str, str]]:631+ ) -> t.Iterator[tuple[int, str, str]]:632 """Lex the given sourcecode and return a generator that yields633 tokens as tuples in the form ``(lineno, token_type, value)``.634 This can be useful for :ref:`extension development <writing-extensions>`635 and debugging templates.40 unmodified lines676 for ext in self.iter_extensions():677 stream = ext.filter_stream(stream) # type: ignore678 679 if not isinstance(stream, TokenStream):680- stream = TokenStream(stream, name, filename) # type: ignore[unreachable]680+ stream = TokenStream(stream, name, filename)681 682 return stream683 684 def _generate(216 unmodified lines901 def list_templates(902 self,903 extensions: t.Optional[t.Collection[str]] = None,904 filter_func: t.Optional[t.Callable[[str], bool]] = None,905- ) -> t.List[str]:905+ ) -> list[str]:906 """Returns a list of templates for this environment. This requires907 that the loader supports the loader's908 :meth:`~BaseLoader.list_templates` method.909 163 unmodified lines1073 1074 @internalcode1075 def get_or_select_template(1076 self,1077- template_name_or_list: t.Union[1078- str, "Template", t.List[t.Union[str, "Template"]]1079- ],1077+ template_name_or_list: t.Union[str, "Template", list[t.Union[str, "Template"]]],1078 parent: t.Optional[str] = None,1079 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,1080 ) -> "Template":1081 """Use :meth:`select_template` if an iterable of template names10 unmodified lines1092 def from_string(1093 self,1094 source: t.Union[str, nodes.Template],1095 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,1098- template_class: t.Optional[t.Type["Template"]] = None,1096+ template_class: t.Optional[type["Template"]] = None,1097 ) -> "Template":1098 """Load a template from a source string without using1099 :attr:`loader`.1100 50 unmodified lines1151 """1152 1153 #: Type of environment to create when creating a template directly1154 #: rather than through an existing environment.1157- environment_class: t.Type[Environment] = Environment1155+ environment_class: type[Environment] = Environment1156 1157 environment: Environment1158 globals: t.MutableMapping[str, t.Any]1159 name: t.Optional[str]1160 filename: t.Optional[str]1163- blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]]1161+ blocks: dict[str, t.Callable[[Context], t.Iterator[str]]]1162 root_render_func: t.Callable[[Context], t.Iterator[str]]1163 _module: t.Optional["TemplateModule"]1164 _debug_info: str1165 _uptodate: t.Optional[t.Callable[[], bool]]12 unmodified lines1178 trim_blocks: bool = TRIM_BLOCKS,1179 lstrip_blocks: bool = LSTRIP_BLOCKS,1180 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,1181 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,1184- extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),1182+ extensions: t.Sequence[t.Union[str, type["Extension"]]] = (),1183 optimized: bool = True,1186- undefined: t.Type[Undefined] = Undefined,1184+ undefined: type[Undefined] = Undefined,1185 finalize: t.Optional[t.Callable[..., t.Any]] = None,1186 autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,1187 enable_async: bool = False,1188 ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...144 unmodified lines1333 """1334 if self.environment.is_async:1335 import asyncio1336 1339- async def to_list() -> t.List[str]:1337+ async def to_list() -> list[str]:1338 return [x async for x in self.generate_async(*args, **kwargs)]1339 1340 yield from asyncio.run(to_list())1341 return31 unmodified lines1373 yield self.environment.handle_exception()1374 1375 def new_context(1376 self,1379- vars: t.Optional[t.Dict[str, t.Any]] = None,1377+ vars: t.Optional[dict[str, t.Any]] = None,1378 shared: bool = False,1379 locals: t.Optional[t.Mapping[str, t.Any]] = None,1380 ) -> Context:1381 """Create a new :class:`Context` for this template. The vars8 unmodified lines1390 )1391 1392 def make_module(1393 self,1396- vars: t.Optional[t.Dict[str, t.Any]] = None,1394+ vars: t.Optional[dict[str, t.Any]] = None,1395 shared: bool = False,1396 locals: t.Optional[t.Mapping[str, t.Any]] = None,1397 ) -> "TemplateModule":1398 """This method works like the :attr:`module` attribute when called6 unmodified lines1405 return TemplateModule(self, ctx)1406 1407 async def make_module_async(1408 self,1411- vars: t.Optional[t.Dict[str, t.Any]] = None,1409+ vars: t.Optional[dict[str, t.Any]] = None,1410 shared: bool = False,1411 locals: t.Optional[t.Mapping[str, t.Any]] = None,1412 ) -> "TemplateModule":1413 """As template module creation can invoke template code for81 unmodified lines1495 return True1496 return self._uptodate()1497 1498 @property1501- def debug_info(self) -> t.List[t.Tuple[int, int]]:1499+ def debug_info(self) -> list[tuple[int, int]]:1500 """The debug info mapping."""1501 if self._debug_info:1502 return [1503 tuple(map(int, x.split("="))) # type: ignore129 unmodified lines1633 self._next = partial(next, self._gen)1634 self.buffered = False1635 1636 def _buffered_generator(self, size: int) -> t.Iterator[str]:1639- buf: t.List[str] = []1637+ buf: list[str] = []1638 c_size = 01639 push = buf.append1640 1641 while True:31 unmodified linesmodified:src/jinja2/ext.py+20 added-24 removed
40 unmodified lines41 42 43 # I18N functions available in Jinja templates. If the I18N library44 # provides ugettext, it will be assigned to gettext.45-GETTEXT_FUNCTIONS: t.Tuple[str, ...] = (45+GETTEXT_FUNCTIONS: tuple[str, ...] = (46 "_",47 "gettext",48 "ngettext",49 "pgettext",26 unmodified lines76 def __init_subclass__(cls) -> None:77 cls.identifier = f"{cls.__module__}.{cls.__name__}"78 79 #: if this extension parses this is the list of tags it's listening to.80- tags: t.Set[str] = set()80+ tags: set[str] = set()81 82 #: the priority of that extension. This is especially useful for83 #: extensions that preprocess values. A lower value means higher84 #: priority.29 unmodified lines114 :class:`~jinja2.lexer.TokenStream`.115 """116 return stream117 118- def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:118+ def parse(self, parser: "Parser") -> t.Union[nodes.Node, list[nodes.Node]]:119 """If any of the :attr:`tags` matched this method is called with the120 parser as first argument. The token the parser stream is pointing at121 is the name token that matched. This method has to return one or a122 list of multiple nodes.14 unmodified lines137 138 def call_method(139 self,140 name: str,141- args: t.Optional[t.List[nodes.Expr]] = None,142- kwargs: t.Optional[t.List[nodes.Keyword]] = None,141+ args: t.Optional[list[nodes.Expr]] = None,142+ kwargs: t.Optional[list[nodes.Keyword]] = None,143 dyn_args: t.Optional[nodes.Expr] = None,144 dyn_kwargs: t.Optional[nodes.Expr] = None,145 lineno: t.Optional[int] = None,146 ) -> nodes.Call:182 unmodified lines329 self,330 source: t.Union[str, nodes.Template],331 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,332 ) -> t.Iterator[333- t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]333+ tuple[int, str, t.Union[t.Optional[str], tuple[t.Optional[str], ...]]]334 ]:335 if isinstance(source, str):336 source = self.environment.parse(source)337 return extract_from_ast(source, gettext_functions)338 339- def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:339+ def parse(self, parser: "Parser") -> t.Union[nodes.Node, list[nodes.Node]]:340 """Parse a translatable tag."""341 lineno = next(parser.stream).lineno342 343 context = None7 unmodified lines351 # a later state.352 plural_expr: t.Optional[nodes.Expr] = None353 plural_expr_assignment: t.Optional[nodes.Assign] = None354 num_called_num = False355- variables: t.Dict[str, nodes.Expr] = {}355+ variables: dict[str, nodes.Expr] = {}356 trimmed = None357 while parser.stream.current.type != "block_end":358 if variables:359 parser.stream.expect("comma")102 unmodified lines462 return _ws_re.sub(" ", string.strip())463 464 def _parse_block(465 self, parser: "Parser", allow_pluralize: bool466- ) -> t.Tuple[t.List[str], str]:466+ ) -> tuple[list[str], str]:467 """Parse until the next block tag with a given name."""468 referenced = []469 buf = []470 41 unmodified lines512 self,513 singular: str,514 plural: t.Optional[str],515 context: t.Optional[str],516- variables: t.Dict[str, nodes.Expr],516+ variables: dict[str, nodes.Expr],517 plural_expr: t.Optional[nodes.Expr],518 vars_referenced: bool,519 num_called_num: bool,520 ) -> nodes.Output:8 unmodified lines529 if plural:530 plural = plural.replace("%%", "%")531 532 func_name = "gettext"533- func_args: t.List[nodes.Expr] = [nodes.Const(singular)]533+ func_args: list[nodes.Expr] = [nodes.Const(singular)]534 535 if context is not None:536 func_args.insert(0, nodes.Const(context))537 func_name = f"p{func_name}"101 unmodified lines639 def extract_from_ast(640 ast: nodes.Template,641 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,642 babel_style: bool = True,643-) -> t.Iterator[644- t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]645-]:643+) -> t.Iterator[tuple[int, str, t.Union[t.Optional[str], tuple[t.Optional[str], ...]]]]:644 """Extract localizable strings from the given template node. Per645 default this function returns matches in babel style that means non string646 parameters as well as keyword arguments are returned as `None`. This647 allows Babel to figure out what you really meant if you are using26 unmodified lines674 This extraction function operates on the AST and is because of that unable675 to extract any comments. For comment support you have to use the babel676 extraction interface or extract comments yourself.677 """680- out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]678+ out: t.Union[t.Optional[str], tuple[t.Optional[str], ...]]679 680 for node in ast.find_all(nodes.Call):681 if (682 not isinstance(node.node, nodes.Name)683 or node.node.name not in gettext_functions684 ):685 continue686 689- strings: t.List[t.Optional[str]] = []687+ strings: list[t.Optional[str]] = []688 689 for arg in node.args:690 if isinstance(arg, nodes.Const) and isinstance(arg.value, str):691 strings.append(arg.value)28 unmodified lines720 usable value.721 """722 723 def __init__(726- self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]724+ self, tokens: t.Sequence[tuple[int, str, str]], comment_tags: t.Sequence[str]725 ) -> None:726 self.tokens = tokens727 self.comment_tags = comment_tags728 self.offset = 0729 self.last_lineno = 0730 733- def find_backwards(self, offset: int) -> t.List[str]:731+ def find_backwards(self, offset: int) -> list[str]:732 try:733 for _, token_type, token_value in reversed(734 self.tokens[self.offset : offset]735 ):7 unmodified lines743 return []744 finally:745 self.offset = offset746 749- def find_comments(self, lineno: int) -> t.List[str]:747+ def find_comments(self, lineno: int) -> list[str]:748 if not self.comment_tags or self.last_lineno > lineno:749 return []750 for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):751 if token_lineno > lineno:4 unmodified lines756 def babel_extract(757 fileobj: t.BinaryIO,758 keywords: t.Sequence[str],759 comment_tags: t.Sequence[str],762- options: t.Dict[str, t.Any],760+ options: dict[str, t.Any],761 ) -> t.Iterator[764- t.Tuple[765- int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]766- ]762+ tuple[int, str, t.Union[t.Optional[str], tuple[t.Optional[str], ...]], list[str]]763 ]:764 """Babel extraction method for Jinja templates.765 766 .. versionchanged:: 2.320 unmodified lines787 :param options: a dictionary of additional options (optional)788 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.789 (comments will be empty currently)790 """795- extensions: t.Dict[t.Type[Extension], None] = {}791+ extensions: dict[type[Extension], None] = {}792 793 for extension_name in options.get("extensions", "").split(","):794 extension_name = extension_name.strip()795 55 unmodified linesmodified:src/jinja2/filters.py+25 added-25 removed
85 unmodified lines86 def make_multi_attrgetter(87 environment: "Environment",88 attribute: t.Optional[t.Union[str, int]],89 postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,90-) -> t.Callable[[t.Any], t.List[t.Any]]:90+) -> t.Callable[[t.Any], list[t.Any]]:91 """Returns a callable that looks up the given comma separated92 attributes from a passed object with the rules of the environment.93 Dots are allowed to access attributes of each attribute. Integer94 parts in paths are looked up as integers.9 unmodified lines104 split = [attribute]105 106 parts = [_prepare_attribute_parts(item) for item in split]107 108- def attrgetter(item: t.Any) -> t.List[t.Any]:108+ def attrgetter(item: t.Any) -> list[t.Any]:109 items = [None] * len(parts)110 111 for i, attribute_part in enumerate(parts):112 item_i = item12 unmodified lines125 126 127 def _prepare_attribute_parts(128 attr: t.Optional[t.Union[str, int]],129-) -> t.List[t.Union[str, int]]:129+) -> list[t.Union[str, int]]:130 if attr is None:131 return []132 133 if isinstance(attr, str):10 unmodified lines144 return escape(str(value))145 146 147 def do_urlencode(148- value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],148+ value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[tuple[str, t.Any]]],149 ) -> str:150 """Quote data for use in a URL path or query using UTF-8.151 152 Basic wrapper around :func:`urllib.parse.quote` when given a12 unmodified lines165 if isinstance(value, str) or not isinstance(value, abc.Iterable):166 return url_quote(value)167 168 if isinstance(value, dict):169- items: t.Iterable[t.Tuple[str, t.Any]] = value.items()169+ items: t.Iterable[tuple[str, t.Any]] = value.items()170 else:171 items = value # type: ignore172 173 return "&".join(46 unmodified lines220 """Convert a value to lowercase."""221 return soft_str(s).lower()222 223 224-def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]:224+def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[tuple[K, V]]:225 """Return an iterator over the ``(key, value)`` items of a mapping.226 227 ``x|items`` is the same as ``x.items()``, except if ``x`` is228 undefined an empty iterator is returned.116 unmodified lines345 value: t.Mapping[K, V],346 case_sensitive: bool = False,347 by: 'te.Literal["key", "value"]' = "key",348 reverse: bool = False,349-) -> t.List[t.Tuple[K, V]]:349+) -> list[tuple[K, V]]:350 """Sort a dict and yield (key, value) pairs. Python dicts may not351 be in the order you want to display them in, so sort them first.352 353 .. sourcecode:: jinja16 unmodified lines370 pos = 1371 else:372 raise FilterArgumentError('You can only sort by either "key" or "value"')373 374- def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:374+ def sort_func(item: tuple[t.Any, t.Any]) -> t.Any:375 value = item[pos]376 377 if not case_sensitive:378 value = ignore_case(value)9 unmodified lines388 value: "t.Iterable[V]",389 reverse: bool = False,390 case_sensitive: bool = False,391 attribute: t.Optional[t.Union[str, int]] = None,392-) -> "t.List[V]":392+) -> "list[V]":393 """Sort an iterable using Python's :func:`sorted`.394 395 .. sourcecode:: jinja396 660 unmodified lines1057 1058 1059 def sync_do_slice(1060 value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None1061-) -> "t.Iterator[t.List[V]]":1061+) -> "t.Iterator[list[V]]":1062 """Slice an iterator and return a list of lists containing1063 those items. Useful if you want to create a div containing1064 three ul tags that represent columns:1065 37 unmodified lines1103 async def do_slice(1104 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1105 slices: int,1106 fill_with: t.Optional[t.Any] = None,1107-) -> "t.Iterator[t.List[V]]":1107+) -> "t.Iterator[list[V]]":1108 return sync_do_slice(await auto_to_list(value), slices, fill_with)1109 1110 1111 def do_batch(1112 value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None1113-) -> "t.Iterator[t.List[V]]":1113+) -> "t.Iterator[list[V]]":1114 """1115 A filter that batches items. It works pretty much like `slice`1116 just the other way round. It returns a list of lists with the1117 given number of items. If you provide a second parameter this10 unmodified lines1128 </tr>1129 {%- endfor %}1130 </table>1131 """1132- tmp: t.List[V] = []1132+ tmp: list[V] = []1133 1134 for item in value:1135 if len(tmp) == linecount:1136 yield tmp49 unmodified lines1186 1187 1188 class _GroupTuple(t.NamedTuple):1189 grouper: t.Any1190- list: t.List[t.Any]1190+ list: list[t.Any]1191 1192 # Use the regular tuple repr to hide this subclass if users print1193 # out the value during debugging.1194 def __repr__(self) -> str:9 unmodified lines1204 value: "t.Iterable[V]",1205 attribute: t.Union[str, int],1206 default: t.Optional[t.Any] = None,1207 case_sensitive: bool = False,1208-) -> "t.List[_GroupTuple]":1208+) -> "list[_GroupTuple]":1209 """Group a sequence of objects by an attribute using Python's1210 :func:`itertools.groupby`. The attribute can use dot notation for1211 nested access, like ``"address.city"``. Unlike Python's ``groupby``,1212 the values are sorted first so only one group is returned for each75 unmodified lines1288 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1289 attribute: t.Union[str, int],1290 default: t.Optional[t.Any] = None,1291 case_sensitive: bool = False,1292-) -> "t.List[_GroupTuple]":1292+) -> "list[_GroupTuple]":1293 expr = make_attrgetter(1294 environment,1295 attribute,1296 postprocess=ignore_case if not case_sensitive else None,60 unmodified lines1357 1358 return rv1359 1360 1361-def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":1361+def sync_do_list(value: "t.Iterable[V]") -> "list[V]":1362 """Convert the value into a list. If it was a string the returned list1363 will be a list of characters.1364 """1365 return list(value)1366 1367 1368 @async_variant(sync_do_list) # type: ignore1369-async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":1369+async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "list[V]":1370 return await auto_to_list(value)1371 1372 1373 def do_mark_safe(value: str) -> Markup:347 unmodified lines1721 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)1722 1723 1724 def prepare_map(1725- context: "Context", args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]1725+ context: "Context", args: tuple[t.Any, ...], kwargs: dict[str, t.Any]1726 ) -> t.Callable[[t.Any], t.Any]:1727 if not args and "attribute" in kwargs:1728 attribute = kwargs.pop("attribute")1729 default = kwargs.pop("default", None)20 unmodified lines1750 1751 1752 def prepare_select_or_reject(1753 context: "Context",1754- args: t.Tuple[t.Any, ...],1755- kwargs: t.Dict[str, t.Any],1754+ args: tuple[t.Any, ...],1755+ kwargs: dict[str, t.Any],1756 modfunc: t.Callable[[t.Any], t.Any],1757 lookup_attr: bool,1758 ) -> t.Callable[[t.Any], t.Any]:1759 if lookup_attr:25 unmodified lines1785 1786 def select_or_reject(1787 context: "Context",1788 value: "t.Iterable[V]",1789- args: t.Tuple[t.Any, ...],1790- kwargs: t.Dict[str, t.Any],1789+ args: tuple[t.Any, ...],1790+ kwargs: dict[str, t.Any],1791 modfunc: t.Callable[[t.Any], t.Any],1792 lookup_attr: bool,1793 ) -> "t.Iterator[V]":1794 if value:6 unmodified lines1801 1802 async def async_select_or_reject(1803 context: "Context",1804 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1805- args: t.Tuple[t.Any, ...],1806- kwargs: t.Dict[str, t.Any],1805+ args: tuple[t.Any, ...],1806+ kwargs: dict[str, t.Any],1807 modfunc: t.Callable[[t.Any], t.Any],1808 lookup_attr: bool,1809 ) -> "t.AsyncIterator[V]":1810 if value:63 unmodified linesmodified:src/jinja2/idtracking.py+8 added-8 removed
40 unmodified lines41 level = parent.level + 142 43 self.level: int = level44 self.parent = parent45- self.refs: t.Dict[str, str] = {}46- self.loads: t.Dict[str, t.Any] = {}47- self.stores: t.Set[str] = set()45+ self.refs: dict[str, str] = {}46+ self.loads: dict[str, t.Any] = {}47+ self.stores: set[str] = set()48 49 def analyze_node(self, node: nodes.Node, **kwargs: t.Any) -> None:50 visitor = RootVisitor(self)51 visitor.visit(node, **kwargs)52 53 def _define_ref(54- self, name: str, load: t.Optional[t.Tuple[str, t.Optional[str]]] = None54+ self, name: str, load: t.Optional[tuple[str, t.Optional[str]]] = None55 ) -> str:56 ident = f"l_{self.level}_{name}"57 self.refs[name] = ident58 if load is not None:61 unmodified lines120 if self.find_ref(name) is None:121 self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))122 123 def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:124- stores: t.Set[str] = set()124+ stores: set[str] = set()125 126 for branch in branch_symbols:127 stores.update(branch.stores)128 14 unmodified lines143 self.loads[target] = (VAR_LOAD_ALIAS, outer_target)144 continue145 self.loads[target] = (VAR_LOAD_RESOLVE, name)146 147- def dump_stores(self) -> t.Dict[str, str]:148- rv: t.Dict[str, str] = {}147+ def dump_stores(self) -> dict[str, str]:148+ rv: dict[str, str] = {}149 node: t.Optional[Symbols] = self150 151 while node is not None:152 for name in sorted(node.stores):3 unmodified lines156 node = node.parent157 158 return rv159 160- def dump_param_targets(self) -> t.Set[str]:160+ def dump_param_targets(self) -> set[str]:161 rv = set()162 node: t.Optional[Symbols] = self163 164 while node is not None:154 unmodified linesmodified:src/jinja2/lexer.py+10 added-10 removed
19 unmodified lines20 from .environment import Environment21 22 # cache for the lexers. Exists in order to be able to have multiple23 # environments with the same lexer24-_lexer_cache: t.MutableMapping[t.Tuple, "Lexer"] = LRUCache(50) # type: ignore24+_lexer_cache: t.MutableMapping[tuple, "Lexer"] = LRUCache(50) # type: ignore25 26 # static regular expressions27 whitespace_re = re.compile(r"\s+")28 newline_re = re.compile(r"(\r\n|\r|\n)")180 unmodified lines209 """210 return len(newline_re.findall(value))211 212 213-def compile_rules(environment: "Environment") -> t.List[t.Tuple[str, str]]:213+def compile_rules(environment: "Environment") -> list[tuple[str, str]]:214 """Compiles all the rules from the environment into a list of rules."""215 e = re.escape216 rules = [217 (38 unmodified lines256 Used by the `Lexer` to specify known errors.257 """258 259 def __init__(260- self, message: str, cls: t.Type[TemplateSyntaxError] = TemplateSyntaxError260+ self, message: str, cls: type[TemplateSyntaxError] = TemplateSyntaxError261 ) -> None:262 self.message = message263 self.error_class = cls264 63 unmodified lines328 name: t.Optional[str],329 filename: t.Optional[str],330 ):331 self._iter = iter(generator)332- self._pushed: te.Deque[Token] = deque()332+ self._pushed: deque[Token] = deque()333 self.name = name334 self.filename = filename335 self.closed = False336 self.current = Token(1, TOKEN_INITIAL, "")126 unmodified lines463 464 465 class _Rule(t.NamedTuple):466 pattern: t.Pattern[str]467- tokens: t.Union[str, t.Tuple[str, ...], t.Tuple[Failure]]467+ tokens: t.Union[str, tuple[str, ...], tuple[Failure]]468 command: t.Optional[str]469 470 471 class Lexer:11 unmodified lines483 def c(x: str) -> t.Pattern[str]:484 return re.compile(x, re.M | re.S)485 486 # lexing rules for tags487- tag_rules: t.List[_Rule] = [487+ tag_rules: list[_Rule] = [488 _Rule(whitespace_re, TOKEN_WHITESPACE, None),489 _Rule(float_re, TOKEN_FLOAT, None),490 _Rule(integer_re, TOKEN_INTEGER, None),491 _Rule(name_re, TOKEN_NAME, None),30 unmodified lines522 [root_raw_re] + [rf"(?P<{n}>{r}(\-|\+|))" for n, r in root_tag_rules]523 )524 525 # global lexing rules526- self.rules: t.Dict[str, t.List[_Rule]] = {526+ self.rules: dict[str, list[_Rule]] = {527 "root": [528 # directives529 _Rule(530 c(rf"(.*?)(?:{root_parts_re})"),82 unmodified lines613 return TokenStream(self.wrap(stream, name, filename), name, filename)614 615 def wrap(616 self,617- stream: t.Iterable[t.Tuple[int, str, str]],617+ stream: t.Iterable[tuple[int, str, str]],618 name: t.Optional[str] = None,619 filename: t.Optional[str] = None,620 ) -> t.Iterator[Token]:621 """This is called with the stream as returned by `tokenize` and wraps49 unmodified lines671 source: str,672 name: t.Optional[str],673 filename: t.Optional[str] = None,674 state: t.Optional[str] = None,675- ) -> t.Iterator[t.Tuple[int, str, str]]:675+ ) -> t.Iterator[tuple[int, str, str]]:676 """This method tokenizes the text and returns the tokens in a677 generator. Use this method if you just want to tokenize a template.678 679 .. versionchanged:: 3.015 unmodified lines695 stack.append(state + "_begin")696 697 statetokens = self.rules[stack[-1]]698 source_length = len(source)699- balancing_stack: t.List[str] = []699+ balancing_stack: list[str] = []700 newlines_stripped = 0701 line_starting = True702 703 while True:165 unmodified linesmodified:src/jinja2/loaders.py+23 added-24 removed
20 unmodified lines21 from .environment import Environment22 from .environment import Template23 24 25-def split_template_path(template: str) -> t.List[str]:25+def split_template_path(template: str) -> list[str]:26 """Split a path into segments and perform a sanity check. If it detects27 '..' in the path it will raise a `TemplateNotFound` error.28 """29 pieces = []43 unmodified lines73 has_source_access = True74 75 def get_source(76 self, environment: "Environment", template: str77- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:77+ ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:78 """Get the template source, filename and reload helper for a template.79 It's passed the environment and template name and has to return a80 tuple in the form ``(source, filename, uptodate)`` or raise a81 `TemplateNotFound` error if it can't locate the template.15 unmodified lines97 f"{type(self).__name__} cannot provide access to the source"98 )99 raise TemplateNotFound(template)100 101- def list_templates(self) -> t.List[str]:101+ def list_templates(self) -> list[str]:102 """Iterates over all templates. If the loader does not support that103 it should raise a :exc:`TypeError` which is the default behavior.104 """105 raise TypeError("this loader cannot iterate over all templates")86 unmodified lines192 self.followlinks = followlinks193 194 def get_source(195 self, environment: "Environment", template: str196- ) -> t.Tuple[str, str, t.Callable[[], bool]]:196+ ) -> tuple[str, str, t.Callable[[], bool]]:197 pieces = split_template_path(template)198 199 for searchpath in self.searchpath:200 # Use posixpath even on Windows to avoid "drive:" or UNC23 unmodified lines224 225 # Use normpath to convert Windows altsep to sep.226 return contents, os.path.normpath(filename), uptodate227 228- def list_templates(self) -> t.List[str]:228+ def list_templates(self) -> list[str]:229 found = set()230 for searchpath in self.searchpath:231 walk_dir = os.walk(searchpath, followlinks=self.followlinks)232 for dirpath, _, filenames in walk_dir:11 unmodified lines244 245 246 if sys.version_info >= (3, 13):247 248- def _get_zipimporter_files(z: t.Any) -> t.Dict[str, object]:248+ def _get_zipimporter_files(z: t.Any) -> dict[str, object]:249 try:250 get_files = z._get_files251 except AttributeError as e:252 raise TypeError(253- "This zip import does not have the required"254- " metadata to list templates."253+ "This zip import does not have the required metadata to list templates."254 ) from e255 return get_files()256+257 else:258 259- def _get_zipimporter_files(z: t.Any) -> t.Dict[str, object]:259+ def _get_zipimporter_files(z: t.Any) -> dict[str, object]:260 try:261 files = z._files262 except AttributeError as e:263 raise TypeError(264- "This zip import does not have the required"265- " metadata to list templates."264+ "This zip import does not have the required metadata to list templates."265 ) from e266 return files # type: ignore[no-any-return]267 268 62 unmodified lines331 self._archive = loader.archive332 pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore333 template_root = os.path.join(pkgdir, package_path).rstrip(os.sep)334 else:336- roots: t.List[str] = []335+ roots: list[str] = []336 337 # One element for regular packages, multiple for namespace338 # packages, or None for single module file.339 if spec.submodule_search_locations:23 unmodified lines363 self._template_root = template_root364 365 def get_source(366 self, environment: "Environment", template: str368- ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:367+ ) -> tuple[str, str, t.Optional[t.Callable[[], bool]]]:368 # Use posixpath even on Windows to avoid "drive:" or UNC369 # segments breaking out of the search directory. Use normpath to370 # convert Windows altsep to sep.371 p = os.path.normpath(27 unmodified lines399 up_to_date = None400 401 return source.decode(self.encoding), p, up_to_date402 404- def list_templates(self) -> t.List[str]:405- results: t.List[str] = []403+ def list_templates(self) -> list[str]:404+ results: list[str] = []405 406 if self._archive is None:407 # Package is a directory.408 offset = len(self._template_root)33 unmodified lines442 self.mapping = mapping443 444 def get_source(445 self, environment: "Environment", template: str447- ) -> t.Tuple[str, None, t.Callable[[], bool]]:446+ ) -> tuple[str, None, t.Callable[[], bool]]:447 if template in self.mapping:448 source = self.mapping[template]449 return source, None, lambda: source == self.mapping.get(template)450 raise TemplateNotFound(template)451 453- def list_templates(self) -> t.List[str]:452+ def list_templates(self) -> list[str]:453 return sorted(self.mapping)454 455 456 class FunctionLoader(BaseLoader):19 unmodified lines476 load_func: t.Callable[477 [str],478 t.Optional[479 t.Union[481- str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]480+ str, tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]481 ]482 ],483 ],484 ) -> None:485 self.load_func = load_func486 487 def get_source(488 self, environment: "Environment", template: str490- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:489+ ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:490 rv = self.load_func(template)491 492 if rv is None:493 raise TemplateNotFound(template)24 unmodified lines518 ) -> None:519 self.mapping = mapping520 self.delimiter = delimiter521 523- def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:522+ def get_loader(self, template: str) -> tuple[BaseLoader, str]:523 try:524 prefix, name = template.split(self.delimiter, 1)525 loader = self.mapping[prefix]526 except (ValueError, KeyError) as e:1 unmodified line528 return loader, name529 530 def get_source(531 self, environment: "Environment", template: str533- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:532+ ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:533 loader, name = self.get_loader(template)534 try:535 return loader.get_source(environment, name)536 except TemplateNotFound as e:15 unmodified lines552 # re-raise the exception with the correct filename here.553 # (the one that includes the prefix)554 raise TemplateNotFound(name) from e555 557- def list_templates(self) -> t.List[str]:556+ def list_templates(self) -> list[str]:557 result = []558 for prefix, loader in self.mapping.items():559 for template in loader.list_templates():560 result.append(prefix + self.delimiter + template)18 unmodified lines579 self.loaders = loaders580 581 def get_source(582 self, environment: "Environment", template: str584- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:583+ ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:584 for loader in self.loaders:585 try:586 return loader.get_source(environment, template)587 except TemplateNotFound:13 unmodified lines601 except TemplateNotFound:602 pass603 raise TemplateNotFound(name)604 606- def list_templates(self) -> t.List[str]:605+ def list_templates(self) -> list[str]:606 found = set()607 for loader in self.loaders:608 found.update(loader.list_templates())609 return sorted(found)80 unmodified linesmodified:src/jinja2/meta.py+2 added-2 removed
15 unmodified lines16 """We abuse the code generator for introspection."""17 18 def __init__(self, environment: "Environment") -> None:19 super().__init__(environment, "<introspection>", "<introspection>")20- self.undeclared_identifiers: t.Set[str] = set()20+ self.undeclared_identifiers: set[str] = set()21 22 def write(self, x: str) -> None:23 """Don't write."""24 5 unmodified lines30 if action == "resolve" and param not in self.environment.globals:31 self.undeclared_identifiers.add(param)32 33 34-def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]:34+def find_undeclared_variables(ast: nodes.Template) -> set[str]:35 """Returns a set of all variables in the AST that will be looked up from36 the context at runtime. Because at compile time it's not known which37 variables will be used depending on the path the execution takes at38 runtime, all variables are returned.74 unmodified linesmodified:src/jinja2/nodes.py+49 added-53 removed
17 unmodified lines18 from .environment import Environment19 20 _NodeBound = t.TypeVar("_NodeBound", bound="Node")21 22-_binop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {22+_binop_to_func: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {23 "*": operator.mul,24 "/": operator.truediv,25 "//": operator.floordiv,26 "**": operator.pow,1 unmodified line28 "+": operator.add,29 "-": operator.sub,30 }31 32-_uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] = {32+_uaop_to_func: dict[str, t.Callable[[t.Any], t.Any]] = {33 "not": operator.not_,34 "+": operator.pos,35 "-": operator.neg,36 }37 38-_cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {38+_cmpop_to_func: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {39 "eq": operator.eq,40 "ne": operator.ne,41 "gt": operator.gt,42 "gteq": operator.ge,14 unmodified lines57 automatically forwarded to the child."""58 59 def __new__(mcs, name, bases, d): # type: ignore60 for attr in "fields", "attributes":61- storage: t.List[t.Tuple[str, ...]] = []61+ storage: list[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"52 unmodified lines118 The `environment` attribute is set at the end of the parsing process for119 all nodes automatically.120 """121 122- fields: t.Tuple[str, ...] = ()123- attributes: t.Tuple[str, ...] = ("lineno", "environment")122+ fields: tuple[str, ...] = ()123+ attributes: tuple[str, ...] = ("lineno", "environment")124 abstract = True125 126 lineno: int127 environment: t.Optional["Environment"]19 unmodified lines147 def iter_fields(148 self,149 exclude: t.Optional[t.Container[str]] = None,150 only: t.Optional[t.Container[str]] = None,151- ) -> t.Iterator[t.Tuple[str, t.Any]]:151+ ) -> t.Iterator[tuple[str, t.Any]]:152 """This method iterates over all fields that are defined and yields153 ``(key, value)`` tuples. Per default all fields are returned, but154 it's possible to limit that to some fields by providing the `only`155 parameter or to exclude some using the `exclude` parameter. Both26 unmodified lines182 yield n183 elif isinstance(item, Node):184 yield item185 186- def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:186+ def find(self, node_type: type[_NodeBound]) -> t.Optional[_NodeBound]:187 """Find the first node of a given type. If no such node exists the188 return value is `None`.189 """190 for result in self.find_all(node_type):1 unmodified line192 193 return None194 195 def find_all(196- self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]196+ self, node_type: t.Union[type[_NodeBound], tuple[type[_NodeBound], ...]]197 ) -> t.Iterator[_NodeBound]:198 """Find all the nodes of a given type. If the type is a tuple,199 the check is performed for any of the tuple items.200 """72 unmodified lines273 else:274 _dump(value)275 buf.append(")")276 277- buf: t.List[str] = []277+ buf: list[str] = []278 _dump(self)279 return "".join(buf)280 281 14 unmodified lines296 is passed to the compiler.297 """298 299 fields = ("body",)300- body: t.List[Node]300+ body: list[Node]301 302 303 class Output(Stmt):304 """A node that holds multiple expressions which are then printed out.305 This is used both for the `print` statement and the regular template data.306 """307 308 fields = ("nodes",)309- nodes: t.List["Expr"]309+ nodes: list["Expr"]310 311 312 class Extends(Stmt):313 """Represents an extends statement."""13 unmodified lines327 328 fields = ("target", "iter", "body", "else_", "test", "recursive")329 target: Node330 iter: Node331- body: t.List[Node]332- else_: t.List[Node]331+ body: list[Node]332+ else_: list[Node]333 test: t.Optional[Node]334 recursive: bool335 336 1 unmodified line338 """If `test` is true, `body` is rendered, else `else_`."""339 340 fields = ("test", "body", "elif_", "else_")341 test: Node342- body: t.List[Node]343- elif_: t.List["If"]344- else_: t.List[Node]342+ body: list[Node]343+ elif_: list["If"]344+ else_: list[Node]345 346 347 class Macro(Stmt):348 """A macro definition. `name` is the name of the macro, `args` a list of2 unmodified lines351 """352 353 fields = ("name", "args", "defaults", "body")354 name: str355- args: t.List["Name"]356- defaults: t.List["Expr"]357- body: t.List[Node]355+ args: list["Name"]356+ defaults: list["Expr"]357+ body: list[Node]358 359 360 class CallBlock(Stmt):361 """Like a macro without a name but a call instead. `call` is called with1 unmodified line363 """364 365 fields = ("call", "args", "defaults", "body")366 call: "Call"367- args: t.List["Name"]368- defaults: t.List["Expr"]369- body: t.List[Node]367+ args: list["Name"]368+ defaults: list["Expr"]369+ body: list[Node]370 371 372 class FilterBlock(Stmt):373 """Node for filter sections."""374 375 fields = ("body", "filter")376- body: t.List[Node]376+ body: list[Node]377 filter: "Filter"378 379 380 class With(Stmt):3 unmodified lines384 .. versionadded:: 2.9.3385 """386 387 fields = ("targets", "values", "body")388- targets: t.List["Expr"]389- values: t.List["Expr"]390- body: t.List[Node]388+ targets: list["Expr"]389+ values: list["Expr"]390+ body: list[Node]391 392 393 class Block(Stmt):394 """A node that represents a block.3 unmodified lines398 """399 400 fields = ("name", "body", "scoped", "required")401 name: str402- body: t.List[Node]402+ body: list[Node]403 scoped: bool404 required: bool405 406 28 unmodified lines435 """436 437 fields = ("template", "names", "with_context")438 template: "Expr"439- names: t.List[t.Union[str, t.Tuple[str, str]]]439+ names: list[t.Union[str, tuple[str, str]]]440 with_context: bool441 442 443 class ExprStmt(Stmt):16 unmodified lines460 461 fields = ("target", "filter", "body")462 target: "Expr"463 filter: t.Optional["Filter"]464- body: t.List[Node]464+ body: list[Node]465 466 467 class Expr(Node):468 """Baseclass for all expressions."""157 unmodified lines626 is used for loading the names or storing.627 """628 629 fields = ("items", "ctx")630- items: t.List[Expr]630+ items: list[Expr]631 ctx: str632 633- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:633+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> tuple[t.Any, ...]:634 eval_ctx = get_eval_context(self, eval_ctx)635 return tuple(x.as_const(eval_ctx) for x in self.items)636 637 def can_assign(self) -> bool:6 unmodified lines644 class List(Literal):645 """Any list literal such as ``[1, 2, 3]``"""646 647 fields = ("items",)648- items: t.List[Expr]648+ items: list[Expr]649 650- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:650+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> list[t.Any]:651 eval_ctx = get_eval_context(self, eval_ctx)652 return [x.as_const(eval_ctx) for x in self.items]653 654 2 unmodified lines657 :class:`Pair` nodes.658 """659 660 fields = ("items",)661- items: t.List["Pair"]661+ items: list["Pair"]662 663- def as_const(664- self, eval_ctx: t.Optional[EvalContext] = None665- ) -> t.Dict[t.Any, t.Any]:663+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> dict[t.Any, t.Any]:664 eval_ctx = get_eval_context(self, eval_ctx)665 return dict(x.as_const(eval_ctx) for x in self.items)666 667 3 unmodified lines671 fields = ("key", "value")672 key: Expr673 value: Expr674 677- def as_const(678- self, eval_ctx: t.Optional[EvalContext] = None679- ) -> t.Tuple[t.Any, t.Any]:675+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> tuple[t.Any, t.Any]:676 eval_ctx = get_eval_context(self, eval_ctx)677 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)678 679 3 unmodified lines683 fields = ("key", "value")684 key: str685 value: Expr686 691- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:687+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> tuple[str, t.Any]:688 eval_ctx = get_eval_context(self, eval_ctx)689 return self.key, self.value.as_const(eval_ctx)690 691 20 unmodified lines712 713 714 def args_as_const(715 node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]720-) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:716+) -> tuple[list[t.Any], dict[t.Any, t.Any]]:717 args = [x.as_const(eval_ctx) for x in node.args]718 kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)719 720 if node.dyn_args is not None:14 unmodified lines735 class _FilterTestCommon(Expr):736 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")737 node: Expr738 name: str743- args: t.List[Expr]744- kwargs: t.List[Pair]739+ args: list[Expr]740+ kwargs: list[Pair]741 dyn_args: t.Optional[Expr]742 dyn_kwargs: t.Optional[Expr]743 abstract = True744 _is_filter = True74 unmodified lines819 """820 821 fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")822 node: Expr827- args: t.List[Expr]828- kwargs: t.List[Keyword]823+ args: list[Expr]824+ kwargs: list[Keyword]825 dyn_args: t.Optional[Expr]826 dyn_kwargs: t.Optional[Expr]827 828 67 unmodified lines896 them to strings.897 """898 899 fields = ("nodes",)904- nodes: t.List[Expr]900+ nodes: list[Expr]901 902 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:903 eval_ctx = get_eval_context(self, eval_ctx)904 return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)5 unmodified lines910 """911 912 fields = ("expr", "ops")913 expr: Expr918- ops: t.List["Operand"]914+ ops: list["Operand"]915 916 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:917 eval_ctx = get_eval_context(self, eval_ctx)918 result = value = self.expr.as_const(eval_ctx)228 unmodified lines1147 class Scope(Stmt):1148 """An artificial scope."""1149 1150 fields = ("body",)1155- body: t.List[Node]1151+ body: list[Node]1152 1153 1154 class OverlayScope(Stmt):1155 """An overlay scope for extensions. This is a largely unoptimized scope10 unmodified lines1166 """1167 1168 fields = ("context", "body")1169 context: Expr1174- body: t.List[Node]1170+ body: list[Node]1171 1172 1173 class EvalContextModifier(Stmt):1174 """Modifies the eval context. For each option that should be modified,4 unmodified lines1179 EvalContextModifier(options=[Keyword('autoescape', Const(True))])1180 """1181 1182 fields = ("options",)1187- options: t.List[Keyword]1183+ options: list[Keyword]1184 1185 1186 class ScopedEvalContextModifier(EvalContextModifier):1187 """Modifies the eval context and reverts it later. Works exactly like1 unmodified line1189 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1190 """1191 1192 fields = ("body",)1197- body: t.List[Node]1193+ body: list[Node]1194 1195 1196 # make sure nobody creates custom nodes1197 def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":5 unmodified linesmodified:src/jinja2/parser.py+31 added-33 removed
33 unmodified lines34 ]35 )36 _compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])37 38-_math_nodes: t.Dict[str, t.Type[nodes.Expr]] = {38+_math_nodes: dict[str, type[nodes.Expr]] = {39 "add": nodes.Add,40 "sub": nodes.Sub,41 "mul": nodes.Mul,42 "div": nodes.Div,19 unmodified lines62 self.stream = environment._tokenize(source, name, filename, state)63 self.name = name64 self.filename = filename65 self.closed = False66- self.extensions: t.Dict[67- str, t.Callable[[Parser], t.Union[nodes.Node, t.List[nodes.Node]]]66+ self.extensions: dict[67+ str, t.Callable[[Parser], t.Union[nodes.Node, list[nodes.Node]]]68 ] = {}69 for extension in environment.iter_extensions():70 for tag in extension.tags:71 self.extensions[tag] = extension.parse72 self._last_identifier = 073- self._tag_stack: t.List[str] = []74- self._end_token_stack: t.List[t.Tuple[str, ...]] = []73+ self._tag_stack: list[str] = []74+ self._end_token_stack: list[tuple[str, ...]] = []75 76 def fail(77 self,78 msg: str,79 lineno: t.Optional[int] = None,80- exc: t.Type[TemplateSyntaxError] = TemplateSyntaxError,80+ exc: type[TemplateSyntaxError] = TemplateSyntaxError,81 ) -> "te.NoReturn":82 """Convenience method that raises `exc` with the message, passed83 line number or last line number as well as the current name and84 filename.4 unmodified lines89 90 def _fail_ut_eof(91 self,92 name: t.Optional[str],93- end_token_stack: t.List[t.Tuple[str, ...]],93+ end_token_stack: list[tuple[str, ...]],94 lineno: t.Optional[int],95 ) -> "te.NoReturn":96- expected: t.Set[str] = set()96+ expected: set[str] = set()97 for exprs in end_token_stack:98 expected.update(map(describe_token_expr, exprs))99 if end_token_stack:100 currently_looking: t.Optional[str] = " or ".join(36 unmodified lines137 self._fail_ut_eof(name, self._end_token_stack, lineno)138 139 def fail_eof(140 self,141- end_tokens: t.Optional[t.Tuple[str, ...]] = None,141+ end_tokens: t.Optional[tuple[str, ...]] = None,142 lineno: t.Optional[int] = None,143 ) -> "te.NoReturn":144 """Like fail_unknown_tag but for end of template situations."""145 stack = list(self._end_token_stack)146 if end_tokens is not None:147 stack.append(end_tokens)148 self._fail_ut_eof(None, stack, lineno)149 150- def is_tuple_end(151- self, extra_end_rules: t.Optional[t.Tuple[str, ...]] = None152- ) -> bool:150+ def is_tuple_end(self, extra_end_rules: t.Optional[tuple[str, ...]] = None) -> bool:151 """Are we at the end of a tuple?"""152 if self.stream.current.type in ("variable_end", "block_end", "rparen"):153 return True154 elif extra_end_rules is not None:6 unmodified lines161 rv = object.__new__(nodes.InternalName)162 nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)163 return rv164 167- def parse_statement(self) -> t.Union[nodes.Node, t.List[nodes.Node]]:165+ def parse_statement(self) -> t.Union[nodes.Node, list[nodes.Node]]:166 """Parse a single statement."""167 token = self.stream.current168 if token.type != "name":169 self.fail("tag name expected", token.lineno)21 unmodified lines191 if pop_tag:192 self._tag_stack.pop()193 194 def parse_statements(197- self, end_tokens: t.Tuple[str, ...], drop_needle: bool = False198- ) -> t.List[nodes.Node]:195+ self, end_tokens: tuple[str, ...], drop_needle: bool = False196+ ) -> list[nodes.Node]:197 """Parse multiple statements into a list until one of the end tokens198 is reached. This is used to parse the body of statements as it also199 parses template data if appropriate. The parser checks first if the200 current token is a colon and skips it if there is one. Then it checks68 unmodified lines269 return result270 271 def parse_with(self) -> nodes.With:272 node = nodes.With(lineno=next(self.stream).lineno)275- targets: t.List[nodes.Expr] = []276- values: t.List[nodes.Expr] = []273+ targets: list[nodes.Expr] = []274+ values: list[nodes.Expr] = []275 while self.stream.current.type != "block_end":276 if targets:277 self.stream.expect("comma")278 target = self.parse_assign_target()184 unmodified lines463 def parse_assign_target(464 self,465 with_tuple: bool = True,466 name_only: bool = False,469- extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,467+ extra_end_rules: t.Optional[tuple[str, ...]] = None,468 with_namespace: bool = False,469 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...470 471 def parse_assign_target(472 self,473 with_tuple: bool = True,474 name_only: bool = False,477- extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,475+ extra_end_rules: t.Optional[tuple[str, ...]] = None,476 with_namespace: bool = False,477 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:478 """Parse an assignment target. As Jinja allows assignments to479 tuples, this function can parse all allowed assignment targets. Per203 unmodified lines683 def parse_tuple(684 self,685 simplified: bool = False,686 with_condexpr: bool = True,689- extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,687+ extra_end_rules: t.Optional[tuple[str, ...]] = None,688 explicit_parentheses: bool = False,689 with_namespace: bool = False,690 ) -> t.Union[nodes.Tuple, nodes.Expr]:691 """Works like `parse_expression` but if multiple expressions are25 unmodified lines717 718 def parse() -> nodes.Expr:719 return self.parse_expression(with_condexpr=with_condexpr)720 723- args: t.List[nodes.Expr] = []721+ args: list[nodes.Expr] = []722 is_tuple = False723 724 while True:725 if args:24 unmodified lines750 return nodes.Tuple(args, "load", lineno=lineno)751 752 def parse_list(self) -> nodes.List:753 token = self.stream.expect("lbracket")756- items: t.List[nodes.Expr] = []754+ items: list[nodes.Expr] = []755 while self.stream.current.type != "rbracket":756 if items:757 self.stream.expect("comma")758 if self.stream.current.type == "rbracket":3 unmodified lines762 return nodes.List(items, lineno=token.lineno)763 764 def parse_dict(self) -> nodes.Dict:765 token = self.stream.expect("lbrace")768- items: t.List[nodes.Pair] = []766+ items: list[nodes.Pair] = []767 while self.stream.current.type != "rbrace":768 if items:769 self.stream.expect("comma")770 if self.stream.current.type == "rbrace":50 unmodified lines821 self.fail("expected name or number", attr_token.lineno)822 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)823 return nodes.Getitem(node, arg, "load", lineno=token.lineno)824 if token.type == "lbracket":827- args: t.List[nodes.Expr] = []825+ args: list[nodes.Expr] = []826 while self.stream.current.type != "rbracket":827 if args:828 self.stream.expect("comma")829 args.append(self.parse_subscribed())6 unmodified lines836 self.fail("expected subscript expression", token.lineno)837 838 def parse_subscribed(self) -> nodes.Expr:839 lineno = self.stream.current.lineno842- args: t.List[t.Optional[nodes.Expr]]840+ args: list[t.Optional[nodes.Expr]]841 842 if self.stream.current.type == "colon":843 next(self.stream)844 args = [None]23 unmodified lines868 return nodes.Slice(lineno=lineno, *args) # noqa: B026869 870 def parse_call_args(871 self,874- ) -> t.Tuple[875- t.List[nodes.Expr],876- t.List[nodes.Keyword],872+ ) -> tuple[873+ list[nodes.Expr],874+ list[nodes.Keyword],875 t.Union[nodes.Expr, None],876 t.Union[nodes.Expr, None],877 ]:878 token = self.stream.expect("lparen")85 unmodified lines964 while self.stream.current.type == "dot":965 next(self.stream)966 name += "." + self.stream.expect("name").value967 dyn_args = dyn_kwargs = None970- kwargs: t.List[nodes.Keyword] = []968+ kwargs: list[nodes.Keyword] = []969 if self.stream.current.type == "lparen":970 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()971 elif self.stream.current.type in {972 "name",18 unmodified lines991 node = nodes.Not(node, lineno=token.lineno)992 return node993 994 def subparse(997- self, end_tokens: t.Optional[t.Tuple[str, ...]] = None998- ) -> t.List[nodes.Node]:999- body: t.List[nodes.Node] = []1000- data_buffer: t.List[nodes.Node] = []995+ self, end_tokens: t.Optional[tuple[str, ...]] = None996+ ) -> list[nodes.Node]:997+ body: list[nodes.Node] = []998+ data_buffer: list[nodes.Node] = []999 add_data = data_buffer.append1000 1001 if end_tokens is not None:1002 self._end_token_stack.append(end_tokens)45 unmodified linesmodified:src/jinja2/runtime.py+19 added-19 removed
91 unmodified lines92 93 def new_context(94 environment: "Environment",95 template_name: t.Optional[str],96- blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],97- vars: t.Optional[t.Dict[str, t.Any]] = None,96+ blocks: dict[str, t.Callable[["Context"], t.Iterator[str]]],97+ vars: t.Optional[dict[str, t.Any]] = None,98 shared: bool = False,99 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,100 locals: t.Optional[t.Mapping[str, t.Any]] = None,101 ) -> "Context":62 unmodified lines164 165 def __init__(166 self,167 environment: "Environment",168- parent: t.Dict[str, t.Any],168+ parent: dict[str, t.Any],169 name: t.Optional[str],170- blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],170+ blocks: dict[str, t.Callable[["Context"], t.Iterator[str]]],171 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,172 ):173 self.parent = parent174- self.vars: t.Dict[str, t.Any] = {}174+ self.vars: dict[str, t.Any] = {}175 self.environment: Environment = environment176 self.eval_ctx = EvalContext(self.environment, name)177- self.exported_vars: t.Set[str] = set()177+ self.exported_vars: set[str] = set()178 self.name = name179 self.globals_keys = set() if globals is None else set(globals)180 181 # create the initial mapping of blocks. Whenever template inheritance61 unmodified lines243 return self.parent[key]244 245 return missing246 247- def get_exported(self) -> t.Dict[str, t.Any]:247+ def get_exported(self) -> dict[str, t.Any]:248 """Get a new dict with the exported variables."""249 return {k: self.vars[k] for k in self.exported_vars}250 251- def get_all(self) -> t.Dict[str, t.Any]:251+ def get_all(self) -> dict[str, t.Any]:252 """Return the complete context as dict including the exported253 variables. For optimizations reasons this might not return an254 actual copy so be careful with using it.255 """50 unmodified lines306 "value was undefined because a callable raised a"307 " StopIteration exception"308 )309 310- def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":310+ def derived(self, locals: t.Optional[dict[str, t.Any]] = None) -> "Context":311 """Internal helper function to create a derived context. This is312 used in situations where the system needs a new context in the same313 template that is independent.314 """32 unmodified lines347 def __init__(348 self,349 name: str,350 context: "Context",351- stack: t.List[t.Callable[["Context"], t.Iterator[str]]],351+ stack: list[t.Callable[["Context"], t.Iterator[str]]],352 depth: int,353 ) -> None:354 self.name = name355 self._context = context51 unmodified lines407 408 def __init__(409 self,410 iterable: t.Iterable[V],411- undefined: t.Type["Undefined"],411+ undefined: type["Undefined"],412 recurse: t.Optional["LoopRenderFunc"] = None,413 depth0: int = 0,414 ) -> None:415 """141 unmodified lines557 558 def __iter__(self) -> "LoopContext":559 return self560 561- def __next__(self) -> t.Tuple[t.Any, "LoopContext"]:561+ def __next__(self) -> tuple[t.Any, "LoopContext"]:562 if self._after is not missing:563 rv = self._after564 self._after = missing565 else:79 unmodified lines645 646 def __aiter__(self) -> "AsyncLoopContext":647 return self648 649- async def __anext__(self) -> t.Tuple[t.Any, "AsyncLoopContext"]:649+ async def __anext__(self) -> tuple[t.Any, "AsyncLoopContext"]:650 if self._after is not missing:651 rv = self._after652 self._after = missing653 else:12 unmodified lines666 self,667 environment: "Environment",668 func: t.Callable[..., str],669 name: str,670- arguments: t.List[str],670+ arguments: list[str],671 catch_kwargs: bool,672 catch_varargs: bool,673 caller: bool,674 default_autoescape: t.Optional[bool] = None,93 unmodified lines768 )769 770 return self._invoke(arguments, autoescape)771 772- async def _async_invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:772+ async def _async_invoke(self, arguments: list[t.Any], autoescape: bool) -> str:773 rv = await self._func(*arguments) # type: ignore774 775 if autoescape:776 return Markup(rv)777 778 return rv # type: ignore779 780- def _invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:780+ def _invoke(self, arguments: list[t.Any], autoescape: bool) -> str:781 if self._environment.is_async:782 return self._async_invoke(arguments, autoescape) # type: ignore783 784 rv = self._func(*arguments)34 unmodified lines819 self,820 hint: t.Optional[str] = None,821 obj: t.Any = missing,822 name: t.Optional[str] = None,823- exc: t.Type[TemplateRuntimeError] = UndefinedError,823+ exc: type[TemplateRuntimeError] = UndefinedError,824 ) -> None:825 self._undefined_hint = hint826 self._undefined_obj = obj827 self._undefined_name = name81 unmodified lines909 return "Undefined"910 911 912 def make_logging_undefined(913- logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined914-) -> t.Type[Undefined]:913+ logger: t.Optional["logging.Logger"] = None, base: type[Undefined] = Undefined914+) -> type[Undefined]:915 """Given a logger object this returns a new undefined class that will916 log certain failures. It will log iterations and printing. If no917 logger is given a default logger is created.918 144 unmodified linesmodified:src/jinja2/sandbox.py+9 added-9 removed
23 unmodified lines24 #: maximum number of items a range may produce25 MAX_RANGE = 10000026 27 #: Unsafe function attributes.28-UNSAFE_FUNCTION_ATTRIBUTES: t.Set[str] = set()28+UNSAFE_FUNCTION_ATTRIBUTES: set[str] = set()29 30 #: Unsafe method attributes. Function attributes are unsafe for methods too.31-UNSAFE_METHOD_ATTRIBUTES: t.Set[str] = set()31+UNSAFE_METHOD_ATTRIBUTES: set[str] = set()32 33 #: unsafe generator attributes.34 UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}35 2 unmodified lines38 39 #: unsafe attributes on async generators40 UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}41 42-_mutable_spec: t.Tuple[t.Tuple[t.Type[t.Any], t.FrozenSet[str]], ...] = (42+_mutable_spec: tuple[tuple[type[t.Any], frozenset[str]], ...] = (43 (44 abc.MutableSet,45 frozenset(46 [142 unmodified lines189 190 #: default callback table for the binary operators. A copy of this is191 #: available on each instance of a sandboxed environment as192 #: :attr:`binop_table`193- default_binop_table: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {193+ default_binop_table: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {194 "+": operator.add,195 "-": operator.sub,196 "*": operator.mul,197 "/": operator.truediv,4 unmodified lines202 203 #: default callback table for the unary operators. A copy of this is204 #: available on each instance of a sandboxed environment as205 #: :attr:`unop_table`206- default_unop_table: t.Dict[str, t.Callable[[t.Any], t.Any]] = {206+ default_unop_table: dict[str, t.Callable[[t.Any], t.Any]] = {207 "+": operator.pos,208 "-": operator.neg,209 }210 10 unmodified lines221 #: operator call, so make sure only to intercept the ones you are222 #: interested in.223 #:224 #: .. versionadded:: 2.6225- intercepted_binops: t.FrozenSet[str] = frozenset()225+ intercepted_binops: frozenset[str] = frozenset()226 227 #: a set of unary operators that should be intercepted. Each operator228 #: that is added to this set (empty by default) is delegated to the229 #: :meth:`call_unop` method that will perform the operator. The default6 unmodified lines236 #: operator call, so make sure only to intercept the ones you are237 #: interested in.238 #:239 #: .. versionadded:: 2.6240- intercepted_unops: t.FrozenSet[str] = frozenset()240+ intercepted_unops: frozenset[str] = frozenset()241 242 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:243 super().__init__(*args, **kwargs)244 self.globals["range"] = safe_range111 unmodified lines356 357 if not isinstance(f_self, str):358 return None359 360- str_type: t.Type[str] = type(f_self)360+ str_type: type[str] = type(f_self)361 is_format_map = value.__name__ == "format_map"362 formatter: SandboxedFormatter363 364 if isinstance(f_self, Markup):55 unmodified lines420 super().__init__(**kwargs)421 422 def get_field(423 self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]424- ) -> t.Tuple[t.Any, str]:424+ ) -> tuple[t.Any, str]:425 first, rest = formatter_field_name_split(field_name)426 obj = self.get_value(first, args, kwargs)427 for is_attr, i in rest:428 if is_attr:8 unmodified linesmodified:src/jinja2/utils.py+4 added-4 removed
436 unmodified lines437 # won't do any harm.438 439 def __init__(self, capacity: int) -> None:440 self.capacity = capacity441- self._mapping: t.Dict[t.Any, t.Any] = {}442- self._queue: te.Deque[t.Any] = deque()441+ self._mapping: dict[t.Any, t.Any] = {}442+ self._queue: deque[t.Any] = deque()443 self._postinit()444 445 def _postinit(self) -> None:446 # alias all queue methods for faster lookup13 unmodified lines460 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:461 self.__dict__.update(d)462 self._postinit()463 464- def __getnewargs__(self) -> t.Tuple[t.Any, ...]:464+ def __getnewargs__(self) -> tuple[t.Any, ...]:465 return (self.capacity,)466 467 def copy(self) -> "te.Self":468 """Return a shallow copy of the instance."""82 unmodified lines551 self._remove(key)552 except ValueError:553 pass554 555- def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:555+ def items(self) -> t.Iterable[tuple[t.Any, t.Any]]:556 """Return a list of items."""557 result = [(key, self._mapping[key]) for key in list(self._queue)]558 result.reverse()559 return result207 unmodified linesmodified:src/jinja2/visitor.py+1 added-1 removed
78 unmodified lines79 else:80 setattr(node, field, new_node)81 return node82 83- def visit_list(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.List[Node]:83+ def visit_list(self, node: Node, *args: t.Any, **kwargs: t.Any) -> list[Node]:84 """As transformers may return lists in some places this method85 can be used to enforce a list as return value.86 """87 rv = self.visit(node, *args, **kwargs)5 unmodified linesmodified:tests/test_async.py+1 added-3 removed
447 unmodified lines448 assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"449 450 def test_reversed_bug(self, test_env_async):451 tmpl = test_env_async.from_string(452- "{% for i in items %}{{ i }}"453- "{% if not loop.last %}"454- ",{% endif %}{% endfor %}"452+ "{% for i in items %}{{ i }}{% if not loop.last %},{% endif %}{% endfor %}"453 )454 assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"455 456 def test_loop_errors(self, test_env_async, run_async_fn):264 unmodified linesmodified:tests/test_core_tags.py+1 added-3 removed
189 unmodified lines190 assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"191 192 def test_reversed_bug(self, env):193 tmpl = env.from_string(194- "{% for i in items %}{{ i }}"195- "{% if not loop.last %}"196- ",{% endif %}{% endfor %}"194+ "{% for i in items %}{{ i }}{% if not loop.last %},{% endif %}{% endfor %}"195 )196 assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"197 198 def test_loop_errors(self, env):403 unmodified linesmodified:tests/test_debug.py+3 added-3 removed
21 unmodified lines22 callback()23 24 tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)25 m = re.search(expected_tb.strip(), "".join(tb))26- assert (27- m is not None28- ), f"Traceback did not match:\n\n{''.join(tb)}\nexpected:\n{expected_tb}"26+ assert m is not None, (27+ f"Traceback did not match:\n\n{''.join(tb)}\nexpected:\n{expected_tb}"28+ )29 30 def test_runtime_error(self, fs_env):31 def test():32 tmpl.render(fail=lambda: 1 / 0)85 unmodified linesmodified:tests/test_ext.py+1 added-2 removed
552 unmodified lines553 lambda s, p, n: s,554 newstyle=True,555 )556 t = env.from_string(557- '{% autoescape ae %}{{ gettext("foo", name='558- '"<test>") }}{% endautoescape %}'557+ '{% autoescape ae %}{{ gettext("foo", name="<test>") }}{% endautoescape %}'558 )559 assert t.render(ae=True) == "<strong>Wert: <test></strong>"560 assert t.render(ae=False) == "<strong>Wert: <test></strong>"561 177 unmodified linesmodified:tests/test_filters.py+1 added-1 removed
355 unmodified lines356 357 def test_urlize(self, env):358 tmpl = env.from_string('{{ "foo example.org bar"|urlize }}')359 assert tmpl.render() == (360- 'foo <a href="https://example.org" rel="noopener">' "example.org</a> bar"360+ 'foo <a href="https://example.org" rel="noopener">example.org</a> bar'361 )362 tmpl = env.from_string('{{ "foo http://www.example.com/ bar"|urlize }}')363 assert tmpl.render() == (364 'foo <a href="http://www.example.com/" rel="noopener">'519 unmodified linesmodified:tests/test_lexnparse.py+1 added-2 removed
41 unmodified lines42 43 class TestLexer:44 def test_raw1(self, env):45 tmpl = env.from_string(46- "{% raw %}foo{% endraw %}|"47- "{%raw%}{{ bar }}|{% baz %}{% endraw %}"46+ "{% raw %}foo{% endraw %}|{%raw%}{{ bar }}|{% baz %}{% endraw %}"47 )48 assert tmpl.render() == "foo|{{ bar }}|{% baz %}"49 50 def test_raw2(self, env):979 unmodified lines