fix ruff pyupgrade findings
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 0cc6ff9 · Browse files · 21 files·+372 added−412 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+372 added−412 removed
- other:+372 added−412 removed
Provenance
- Commit
ece7c27- Tree
58f8a8c- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
0cc6ff9
21 files changed+372 added−412 removed
modified:src/jinja2/async_utils.py+2 added-2 removed
83 unmodified lines84 raise StopAsyncIteration(e.value) from e85 86 87 def auto_aiter(88- iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",88+ iterable: "t.AsyncIterable[V] | t.Iterable[V]",89 ) -> "t.AsyncIterator[V]":90 if hasattr(iterable, "__aiter__"):91 return iterable.__aiter__()92 else:93 return _IteratorToAsyncIterator(iter(iterable))94 95 96 async def auto_to_list(97- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",97+ value: "t.AsyncIterable[V] | t.Iterable[V]",98 ) -> list["V"]:99 return [x async for x in auto_aiter(value)]modified:src/jinja2/bccache.py+6 added-10 removed
25 unmodified lines26 27 class _MemcachedClient(te.Protocol):28 def get(self, key: str) -> bytes: ...29 30- def set(31- self, key: str, value: bytes, timeout: t.Optional[int] = None32- ) -> None: ...30+ def set(self, key: str, value: bytes, timeout: int | None = None) -> None: ...31 32 33 bc_version = 534 # Magic bytes to identify Jinja bytecode cache files. Contains the22 unmodified lines57 self.reset()58 59 def reset(self) -> None:60 """Resets the bucket (unloads the bytecode)."""63- self.code: t.Optional[CodeType] = None61+ self.code: CodeType | None = None62 63 def load_bytecode(self, f: t.BinaryIO) -> None:64 """Loads bytecode from a file or file like object."""65 # make sure the magic header is correct80 unmodified lines146 implemented to allow applications to clear the bytecode cache used147 by a particular environment.148 """149 152- def get_cache_key(153- self, name: str, filename: t.Optional[t.Union[str]] = None154- ) -> str:150+ def get_cache_key(self, name: str, filename: str | None = None) -> str:151 """Returns the unique hash key for this template name."""152 hash = sha1(name.encode("utf-8"))153 154 if filename is not None:8 unmodified lines163 def get_bucket(164 self,165 environment: "Environment",166 name: str,171- filename: t.Optional[str],167+ filename: str | None,168 source: str,169 ) -> Bucket:170 """Return a cache bucket for the given template. All arguments are171 mandatory but filename may be `None`.27 unmodified lines199 This bytecode cache supports clearing of the cache using the clear method.200 """201 202 def __init__(207- self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache"203+ self, directory: str | None = None, pattern: str = "__jinja2_%s.cache"204 ) -> None:205 if directory is None:206 directory = self._get_default_cache_dir()207 self.directory = directory164 unmodified lines372 def __init__(373 self,374 client: "_MemcachedClient",375 prefix: str = "jinja2/bytecode/",380- timeout: t.Optional[int] = None,376+ timeout: int | None = None,377 ignore_memcache_errors: bool = True,378 ):379 self.client = client380 self.prefix = prefix24 unmodified linesmodified:src/jinja2/compiler.py+29 added-33 removed
99 unmodified lines100 101 def generate(102 node: nodes.Template,103 environment: "Environment",104- name: t.Optional[str],105- filename: t.Optional[str],106- stream: t.Optional[t.TextIO] = None,104+ name: str | None,105+ filename: str | None,106+ stream: t.TextIO | None = None,107 defer_init: bool = False,108 optimized: bool = True,109-) -> t.Optional[str]:109+) -> str | None:110 """Generate the python source for a node tree."""111 if not isinstance(node, nodes.Template):112 raise TypeError("Can't compile non template nodes")113 38 unmodified lines152 return visitor.undeclared153 154 155 class MacroRef:156- def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None:156+ def __init__(self, node: nodes.Macro | nodes.CallBlock) -> None:157 self.node = node158 self.accesses_caller = False159 self.accesses_kwargs = False160 self.accesses_varargs = False5 unmodified lines166 def __init__(167 self,168 eval_ctx: EvalContext,169 parent: t.Optional["Frame"] = None,170- level: t.Optional[int] = None,170+ level: int | None = None,171 ) -> None:172 self.eval_ctx = eval_ctx173 174 # the parent of this frame9 unmodified lines184 # inside some tags we are using a buffer rather than yield statements.185 # this for example affects {% filter %} or {% macro %}. If a frame186 # is buffered this variable points to the name of the list used as187 # buffer.188- self.buffer: t.Optional[str] = None188+ self.buffer: str | None = None189 190 # the name of the block we're in, otherwise None.191- self.block: t.Optional[str] = None191+ self.block: str | None = None192 193 else:194 self.symbols = Symbols(parent.symbols, level=level)195 self.require_output_check = parent.require_output_check102 unmodified lines298 class CodeGenerator(NodeVisitor):299 def __init__(300 self,301 environment: "Environment",302- name: t.Optional[str],303- filename: t.Optional[str],304- stream: t.Optional[t.TextIO] = None,302+ name: str | None,303+ filename: str | None,304+ stream: t.TextIO | None = None,305 defer_init: bool = False,306 optimized: bool = True,307 ) -> None:308 if stream is None:3 unmodified lines312 self.filename = filename313 self.stream = stream314 self.created_block_context = False315 self.defer_init = defer_init316- self.optimizer: t.Optional[Optimizer] = None316+ self.optimizer: Optimizer | None = None317 318 if optimized:319 self.optimizer = Optimizer(environment)320 20 unmodified lines341 self.filters: dict[str, str] = {}342 343 # the debug information344 self.debug_info: list[tuple[int, int]] = []345- self._write_debug_info: t.Optional[int] = None345+ self._write_debug_info: int | None = None346 347 # the number of new lines before the next write()348 self._new_lines = 0349 66 unmodified lines416 def outdent(self, step: int = 1) -> None:417 """Outdent by step."""418 self._indentation -= step419 420- def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None:420+ def start_write(self, frame: Frame, node: nodes.Node | None = None) -> None:421 """Yield or write into the frame buffer."""422 if frame.buffer is None:423 self.writeline("yield ", node)424 else:4 unmodified lines429 if frame.buffer is not None:430 self.write(")")431 432 def simple_write(433- self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None433+ self, s: str, frame: Frame, node: nodes.Node | None = None434 ) -> None:435 """Simple shortcut for start_write + write + end_write."""436 self.start_write(frame, node)437 self.write(s)23 unmodified lines461 self.stream.write(" " * self._indentation)462 self._new_lines = 0463 self.stream.write(x)464 465- def writeline(466- self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0467- ) -> None:465+ def writeline(self, x: str, node: nodes.Node | None = None, extra: int = 0) -> None:466 """Combination of newline and write."""467 self.newline(node, extra)468 self.write(x)469 472- def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None:470+ def newline(self, node: nodes.Node | None = None, extra: int = 0) -> None:471 """Add one or more newlines before the next write."""472 self._new_lines = max(self._new_lines, 1 + extra)473 if node is not None and node.lineno != self._last_line:474 self._write_debug_info = node.lineno475 self._last_line = node.lineno476 477 def signature(478 self,481- node: t.Union[nodes.Call, nodes.Filter, nodes.Test],479+ node: nodes.Call | nodes.Filter | nodes.Test,480 frame: Frame,483- extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None,481+ extra_kwargs: t.Mapping[str, t.Any] | None = None,482 ) -> None:483 """Writes a function call to the stream for the current node.484 A leading comma is added automatically. The extra keyword485 arguments may not include python keywords otherwise a syntax121 unmodified lines607 def func(self, name: str) -> str:608 return f"{self.choose_async()}def {name}"609 610 def macro_body(613- self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame611+ self, node: nodes.Macro | nodes.CallBlock, frame: Frame612 ) -> tuple[Frame, MacroRef]:613 """Dump the function def of a macro or call block."""614 frame = frame.inner()615 frame.symbols.analyze_node(node)205 unmodified lines821 self.writeline(f"context.exported_vars.update(({names_str}))")822 823 # -- Statement Visitors824 827- def visit_Template(828- self, node: nodes.Template, frame: t.Optional[Frame] = None829- ) -> None:825+ def visit_Template(self, node: nodes.Template, frame: Frame | None = None) -> None:826 assert frame is None, "no root frame allowed"827 eval_ctx = EvalContext(self.environment, self.name)828 829 from .runtime import async_exported261 unmodified lines1091 if node.ignore_missing:1092 self.outdent()1093 1094 def _import_common(1099- self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame1095+ self, node: nodes.Import | nodes.FromImport, frame: Frame1096 ) -> None:1097 self.write(f"{self.choose_async('await ')}environment.get_template(")1098 self.visit(node.template, frame)1099 self.write(f", {self.name!r}).")264 unmodified lines1364 def visit_With(self, node: nodes.With, frame: Frame) -> None:1365 with_frame = frame.inner()1366 with_frame.symbols.analyze_node(node)1367 self.enter_frame(with_frame)1372- for target, expr in zip(node.targets, node.values):1368+ for target, expr in zip(node.targets, node.values, strict=False):1369 self.newline()1370 self.visit(target, with_frame)1371 self.write(" = ")1372 self.visit(expr, frame)4 unmodified lines1377 self.newline(node)1378 self.visit(node.node, frame)1379 1380 class _FinalizeInfo(t.NamedTuple):1385- const: t.Optional[t.Callable[..., str]]1386- src: t.Optional[str]1381+ const: t.Callable[..., str] | None1382+ src: str | None1383 1384 @staticmethod1385 def _default_finalize(value: t.Any) -> t.Any:1386 """The default finalize function if the environment isn't1 unmodified line1388 called on that function's output for constants.1389 """1390 return str(value)1391 1396- _finalize: t.Optional[_FinalizeInfo] = None1392+ _finalize: _FinalizeInfo | None = None1393 1394 def _make_finalize(self) -> _FinalizeInfo:1395 """Build the finalize function to be used on constants and at1396 runtime. Cached so it's only created once for all output nodes.9 unmodified lines1406 """1407 if self._finalize is not None:1408 return self._finalize1409 1414- finalize: t.Optional[t.Callable[..., t.Any]]1410+ finalize: t.Callable[..., t.Any] | None1411 finalize = default = self._default_finalize1412 src = None1413 1414 if self.environment.finalize:89 unmodified lines1504 self.writeline("if parent_template is None:")1505 self.indent()1506 1507 finalize = self._make_finalize()1512- body: list[t.Union[list[t.Any], nodes.Expr]] = []1508+ body: list[list[t.Any] | nodes.Expr] = []1509 1510 # Evaluate constants at compile time if possible. Each item in1511 # body will be either a list of static data or a node to be1512 # evaluated at runtime.273 unmodified lines1786 self.visit(node.step, frame)1787 1788 @contextmanager1789 def _filter_test_common(1794- self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool1790+ self, node: nodes.Filter | nodes.Test, frame: Frame, is_filter: bool1791 ) -> t.Iterator[None]:1792 if self.environment.is_async:1793 self.write("(await auto_await(")1794 198 unmodified linesmodified:src/jinja2/debug.py+3 added-3 removed
9 unmodified lines10 if t.TYPE_CHECKING:11 from .runtime import Context12 13 14-def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:14+def rewrite_traceback_stack(source: str | None = None) -> BaseException:15 """Rewrite the current exception to replace any tracebacks from16 within compiled template code with tracebacks that look like they17 came from the template source.18 54 unmodified lines73 return exc_value.with_traceback(tb_next)74 75 76 def fake_traceback( # type: ignore77- exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int77+ exc_value: BaseException, tb: TracebackType | None, filename: str, lineno: int78 ) -> TracebackType:79 """Produce a new traceback object that looks like it came from the80 template source instead of the compiled code. The filename, line81 number, and location name will point to the template, and the local50 unmodified lines132 """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")136+ ctx: Context | None = real_locals.get("context")137 138 if ctx is not None:139 data: dict[str, t.Any] = ctx.get_all().copy()140 else:32 unmodified linesmodified:src/jinja2/defaults.py+2 added-2 removed
15 unmodified lines16 VARIABLE_START_STRING = "{{"17 VARIABLE_END_STRING = "}}"18 COMMENT_START_STRING = "{#"19 COMMENT_END_STRING = "#}"20-LINE_STATEMENT_PREFIX: t.Optional[str] = None21-LINE_COMMENT_PREFIX: t.Optional[str] = None20+LINE_STATEMENT_PREFIX: str | None = None21+LINE_COMMENT_PREFIX: str | None = None22 TRIM_BLOCKS = False23 LSTRIP_BLOCKS = False24 NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n"25 KEEP_TRAILING_NEWLINE = False23 unmodified linesmodified:src/jinja2/environment.py+92 added-96 removed
80 unmodified lines81 82 83 def create_cache(84 size: int,85-) -> t.Optional[t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"]]:85+) -> t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None:86 """Return the cache class for the given size."""87 if size == 0:88 return None89 3 unmodified lines93 return LRUCache(size) # type: ignore94 95 96 def copy_cache(97- cache: t.Optional[98- t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"]99- ],100-) -> t.Optional[t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"]]:97+ cache: t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None,98+) -> t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None:99 """Create an empty copy of the given cache."""100 if cache is None:101 return None102 4 unmodified lines107 108 109 def load_extensions(110 environment: "Environment",113- extensions: t.Sequence[t.Union[str, type["Extension"]]],111+ extensions: t.Sequence[str | type["Extension"]],112 ) -> dict[str, "Extension"]:113 """Load the extensions from the list and bind it to the environment.114 Returns a dict of instantiated extensions.115 """183 unmodified lines299 variable_start_string: str = VARIABLE_START_STRING,300 variable_end_string: str = VARIABLE_END_STRING,301 comment_start_string: str = COMMENT_START_STRING,302 comment_end_string: str = COMMENT_END_STRING,305- line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,306- line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,303+ line_statement_prefix: str | None = LINE_STATEMENT_PREFIX,304+ line_comment_prefix: str | None = LINE_COMMENT_PREFIX,305 trim_blocks: bool = TRIM_BLOCKS,306 lstrip_blocks: bool = LSTRIP_BLOCKS,307 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,308 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,311- extensions: t.Sequence[t.Union[str, type["Extension"]]] = (),309+ extensions: t.Sequence[str | type["Extension"]] = (),310 optimized: bool = True,311 undefined: type[Undefined] = Undefined,314- finalize: t.Optional[t.Callable[..., t.Any]] = None,315- autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,312+ finalize: t.Callable[..., t.Any] | None = None,313+ autoescape: bool | t.Callable[[str | None], bool] = False,314 loader: t.Optional["BaseLoader"] = None,315 cache_size: int = 400,316 auto_reload: bool = True,317 bytecode_cache: t.Optional["BytecodeCache"] = None,49 unmodified lines367 368 self.is_async = enable_async369 _environment_config_check(self)370 373- def add_extension(self, extension: t.Union[str, type["Extension"]]) -> None:371+ def add_extension(self, extension: str | type["Extension"]) -> None:372 """Adds an extension after the environment was created.373 374 .. versionadded:: 2.5375 """15 unmodified lines391 variable_start_string: str = missing,392 variable_end_string: str = missing,393 comment_start_string: str = missing,394 comment_end_string: str = missing,397- line_statement_prefix: t.Optional[str] = missing,398- line_comment_prefix: t.Optional[str] = missing,395+ line_statement_prefix: str | None = missing,396+ line_comment_prefix: str | None = missing,397 trim_blocks: bool = missing,398 lstrip_blocks: bool = missing,399 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,400 keep_trailing_newline: bool = missing,403- extensions: t.Sequence[t.Union[str, type["Extension"]]] = missing,401+ extensions: t.Sequence[str | type["Extension"]] = missing,402 optimized: bool = missing,403 undefined: type[Undefined] = missing,406- finalize: t.Optional[t.Callable[..., t.Any]] = missing,407- autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,404+ finalize: t.Callable[..., t.Any] | None = missing,405+ autoescape: bool | t.Callable[[str | None], bool] = missing,406 loader: t.Optional["BaseLoader"] = missing,407 cache_size: int = missing,408 auto_reload: bool = missing,409 bytecode_cache: t.Optional["BytecodeCache"] = missing,53 unmodified lines463 def iter_extensions(self) -> t.Iterator["Extension"]:464 """Iterates over the extensions by priority."""465 return iter(sorted(self.extensions.values(), key=lambda x: x.priority))466 469- def getitem(470- self, obj: t.Any, argument: t.Union[str, t.Any]471- ) -> t.Union[t.Any, Undefined]:467+ def getitem(self, obj: t.Any, argument: str | t.Any) -> t.Any | Undefined:468 """Get an item or attribute of an object but prefer the item."""469 try:470 return obj[argument]471 except (AttributeError, TypeError, LookupError):23 unmodified lines495 return self.undefined(obj=obj, name=attribute)496 497 def _filter_test_common(498 self,503- name: t.Union[str, Undefined],499+ name: str | Undefined,500 value: t.Any,505- args: t.Optional[t.Sequence[t.Any]],506- kwargs: t.Optional[t.Mapping[str, t.Any]],507- context: t.Optional[Context],508- eval_ctx: t.Optional[EvalContext],501+ args: t.Sequence[t.Any] | None,502+ kwargs: t.Mapping[str, t.Any] | None,503+ context: Context | None,504+ eval_ctx: EvalContext | None,505 is_filter: bool,506 ) -> t.Any:507 if is_filter:508 env_map = self.filters42 unmodified lines551 def call_filter(552 self,553 name: str,554 value: t.Any,559- args: t.Optional[t.Sequence[t.Any]] = None,560- kwargs: t.Optional[t.Mapping[str, t.Any]] = None,561- context: t.Optional[Context] = None,562- eval_ctx: t.Optional[EvalContext] = None,555+ args: t.Sequence[t.Any] | None = None,556+ kwargs: t.Mapping[str, t.Any] | None = None,557+ context: Context | None = None,558+ eval_ctx: EvalContext | None = None,559 ) -> t.Any:560 """Invoke a filter on a value the same way the compiler does.561 562 This might return a coroutine if the filter is running from an9 unmodified lines572 def call_test(573 self,574 name: str,575 value: t.Any,580- args: t.Optional[t.Sequence[t.Any]] = None,581- kwargs: t.Optional[t.Mapping[str, t.Any]] = None,582- context: t.Optional[Context] = None,583- eval_ctx: t.Optional[EvalContext] = None,576+ args: t.Sequence[t.Any] | None = None,577+ kwargs: t.Mapping[str, t.Any] | None = None,578+ context: Context | None = None,579+ eval_ctx: EvalContext | None = None,580 ) -> t.Any:581 """Invoke a test on a value the same way the compiler does.582 583 This might return a coroutine if the test is running from an13 unmodified lines597 @internalcode598 def parse(599 self,600 source: str,605- name: t.Optional[str] = None,606- filename: t.Optional[str] = None,601+ name: str | None = None,602+ filename: str | None = None,603 ) -> nodes.Template:604 """Parse the sourcecode and return the abstract syntax tree. This605 tree of nodes is used by the compiler to convert the template into606 executable source- or bytecode. This is useful for debugging or to7 unmodified lines614 except TemplateSyntaxError:615 self.handle_exception(source=source)616 617 def _parse(622- self, source: str, name: t.Optional[str], filename: t.Optional[str]618+ self, source: str, name: str | None, filename: str | None619 ) -> nodes.Template:620 """Internal parsing function used by `parse` and `compile`."""621 return Parser(self, source, name, filename).parse()622 623 def lex(624 self,625 source: str,630- name: t.Optional[str] = None,631- filename: t.Optional[str] = None,626+ name: str | None = None,627+ filename: str | None = None,628 ) -> t.Iterator[tuple[int, str, str]]:629 """Lex the given sourcecode and return a generator that yields630 tokens as tuples in the form ``(lineno, token_type, value)``.631 This can be useful for :ref:`extension development <writing-extensions>`11 unmodified lines643 644 def preprocess(645 self,646 source: str,651- name: t.Optional[str] = None,652- filename: t.Optional[str] = None,647+ name: str | None = None,648+ filename: str | None = None,649 ) -> str:650 """Preprocesses the source with all extensions. This is automatically651 called for all parsing and compiling methods but *not* for :meth:`lex`652 because there you usually only want the actual source tokenized.6 unmodified lines659 660 def _tokenize(661 self,662 source: str,667- name: t.Optional[str],668- filename: t.Optional[str] = None,669- state: t.Optional[str] = None,663+ name: str | None,664+ filename: str | None = None,665+ state: str | None = None,666 ) -> TokenStream:667 """Called by the parser to do the preprocessing and filtering668 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.669 """10 unmodified lines680 681 def _generate(682 self,683 source: nodes.Template,688- name: t.Optional[str],689- filename: t.Optional[str],684+ name: str | None,685+ filename: str | None,686 defer_init: bool = False,687 ) -> str:688 """Internal hook that can be overridden to hook a different generate689 method in.19 unmodified lines709 710 @typing.overload711 def compile(712 self,717- source: t.Union[str, nodes.Template],718- name: t.Optional[str] = None,719- filename: t.Optional[str] = None,713+ source: str | nodes.Template,714+ name: str | None = None,715+ filename: str | None = None,716 raw: "te.Literal[False]" = False,717 defer_init: bool = False,718 ) -> CodeType: ...719 720 @typing.overload721 def compile(722 self,727- source: t.Union[str, nodes.Template],728- name: t.Optional[str] = None,729- filename: t.Optional[str] = None,723+ source: str | nodes.Template,724+ name: str | None = None,725+ filename: str | None = None,726 raw: "te.Literal[True]" = ...,727 defer_init: bool = False,728 ) -> str: ...729 730 @internalcode731 def compile(732 self,737- source: t.Union[str, nodes.Template],738- name: t.Optional[str] = None,739- filename: t.Optional[str] = None,733+ source: str | nodes.Template,734+ name: str | None = None,735+ filename: str | None = None,736 raw: bool = False,737 defer_init: bool = False,742- ) -> t.Union[str, CodeType]:738+ ) -> str | CodeType:739 """Compile a node or template source code. The `name` parameter is740 the load name of the template after it was joined using741 :meth:`join_path` if necessary, not the filename on the file system.742 the `filename` parameter is the estimated filename of the template on73 unmodified lines816 817 def compile_templates(818 self,819 target: t.Union[str, "os.PathLike[str]"],824- extensions: t.Optional[t.Collection[str]] = None,825- filter_func: t.Optional[t.Callable[[str], bool]] = None,826- zip: t.Optional[str] = "deflated",827- log_function: t.Optional[t.Callable[[str], None]] = None,820+ extensions: t.Collection[str] | None = None,821+ filter_func: t.Callable[[str], bool] | None = None,822+ zip: str | None = "deflated",823+ log_function: t.Callable[[str], None] | None = None,824 ignore_errors: bool = True,825 ) -> None:826 """Finds all the templates the loader can find, compiles them827 and stores them in `target`. If `zip` is `None`, instead of in a68 unmodified lines896 log_function("Finished compiling templates")897 898 def list_templates(899 self,904- extensions: t.Optional[t.Collection[str]] = None,905- filter_func: t.Optional[t.Callable[[str], bool]] = None,900+ extensions: t.Collection[str] | None = None,901+ filter_func: t.Callable[[str], bool] | None = None,902 ) -> list[str]:903 """Returns a list of templates for this environment. This requires904 that the loader supports the loader's905 :meth:`~BaseLoader.list_templates` method.25 unmodified lines931 names = [name for name in names if filter_func(name)]932 933 return names934 939- def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":935+ def handle_exception(self, source: str | None = None) -> "te.NoReturn":936 """Exception handling helper. This is used internally to either raise937 rewritten exceptions or return a rendered traceback for the template.938 """939 from .debug import rewrite_traceback_stack13 unmodified lines953 return template954 955 @internalcode956 def _load_template(961- self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]957+ self, name: str, globals: t.MutableMapping[str, t.Any] | None958 ) -> "Template":959 if self.loader is None:960 raise TypeError("no loader for this environment specified")961 cache_key = (weakref.ref(self.loader), name)18 unmodified lines980 @internalcode981 def get_template(982 self,983 name: t.Union[str, "Template"],988- parent: t.Optional[str] = None,989- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,984+ parent: str | None = None,985+ globals: t.MutableMapping[str, t.Any] | None = None,986 ) -> "Template":987 """Load a template by name with :attr:`loader` and return a988 :class:`Template`. If the template does not exist a989 :exc:`TemplateNotFound` exception is raised.27 unmodified lines1017 @internalcode1018 def select_template(1019 self,1020 names: t.Iterable[t.Union[str, "Template"]],1025- parent: t.Optional[str] = None,1026- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,1021+ parent: str | None = None,1022+ globals: t.MutableMapping[str, t.Any] | None = None,1023 ) -> "Template":1024 """Like :meth:`get_template`, but tries loading multiple names.1025 If none of the names can be loaded a :exc:`TemplatesNotFound`1026 exception is raised.44 unmodified lines1071 @internalcode1072 def get_or_select_template(1073 self,1074 template_name_or_list: t.Union[str, "Template", list[t.Union[str, "Template"]]],1079- parent: t.Optional[str] = None,1080- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,1075+ parent: str | None = None,1076+ globals: t.MutableMapping[str, t.Any] | None = None,1077 ) -> "Template":1078 """Use :meth:`select_template` if an iterable of template names1079 is given, or :meth:`get_template` if one name is given.1080 6 unmodified lines1087 return self.select_template(template_name_or_list, parent, globals)1088 1089 def from_string(1090 self,1095- source: t.Union[str, nodes.Template],1096- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,1097- template_class: t.Optional[type["Template"]] = None,1091+ source: str | nodes.Template,1092+ globals: t.MutableMapping[str, t.Any] | None = None,1093+ template_class: type["Template"] | None = None,1094 ) -> "Template":1095 """Load a template from a source string without using1096 :attr:`loader`.1097 9 unmodified lines1107 cls = template_class or self.template_class1108 return cls.from_code(self, self.compile(source), gs, None)1109 1110 def make_globals(1115- self, d: t.Optional[t.MutableMapping[str, t.Any]]1111+ self, d: t.MutableMapping[str, t.Any] | None1112 ) -> t.MutableMapping[str, t.Any]:1113 """Make the globals map for a template. Any given template1114 globals overlay the environment :attr:`globals`.1115 36 unmodified lines1152 environment_class: type[Environment] = Environment1153 1154 environment: Environment1155 globals: t.MutableMapping[str, t.Any]1160- name: t.Optional[str]1161- filename: t.Optional[str]1156+ name: str | None1157+ filename: str | None1158 blocks: dict[str, t.Callable[[Context], t.Iterator[str]]]1159 root_render_func: t.Callable[[Context], t.Iterator[str]]1160 _module: t.Optional["TemplateModule"]1161 _debug_info: str1166- _uptodate: t.Optional[t.Callable[[], bool]]1162+ _uptodate: t.Callable[[], bool] | None1163 1164 def __new__(1165 cls,1170- source: t.Union[str, nodes.Template],1166+ source: str | nodes.Template,1167 block_start_string: str = BLOCK_START_STRING,1168 block_end_string: str = BLOCK_END_STRING,1169 variable_start_string: str = VARIABLE_START_STRING,1170 variable_end_string: str = VARIABLE_END_STRING,1171 comment_start_string: str = COMMENT_START_STRING,1172 comment_end_string: str = COMMENT_END_STRING,1177- line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,1178- line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,1173+ line_statement_prefix: str | None = LINE_STATEMENT_PREFIX,1174+ line_comment_prefix: str | None = LINE_COMMENT_PREFIX,1175 trim_blocks: bool = TRIM_BLOCKS,1176 lstrip_blocks: bool = LSTRIP_BLOCKS,1177 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,1178 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,1183- extensions: t.Sequence[t.Union[str, type["Extension"]]] = (),1179+ extensions: t.Sequence[str | type["Extension"]] = (),1180 optimized: bool = True,1181 undefined: type[Undefined] = Undefined,1186- finalize: t.Optional[t.Callable[..., t.Any]] = None,1187- autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,1182+ finalize: t.Callable[..., t.Any] | None = None,1183+ autoescape: bool | t.Callable[[str | None], bool] = False,1184 enable_async: bool = False,1185 ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...1186 env = get_spontaneous_environment(1187 cls.environment_class, # type: ignore27 unmodified lines1215 cls,1216 environment: Environment,1217 code: CodeType,1218 globals: t.MutableMapping[str, t.Any],1223- uptodate: t.Optional[t.Callable[[], bool]] = None,1219+ uptodate: t.Callable[[], bool] | None = None,1220 ) -> "Template":1221 """Creates a template object from compiled code and the globals. This1222 is used by the loaders and environment to create a template object.1223 """143 unmodified lines1367 yield self.environment.handle_exception()1368 1369 def new_context(1370 self,1375- vars: t.Optional[dict[str, t.Any]] = None,1371+ vars: dict[str, t.Any] | None = None,1372 shared: bool = False,1377- locals: t.Optional[t.Mapping[str, t.Any]] = None,1373+ locals: t.Mapping[str, t.Any] | None = None,1374 ) -> Context:1375 """Create a new :class:`Context` for this template. The vars1376 provided will be passed to the template. Per default the globals1377 are added to the context. If shared is set to `True` the data6 unmodified lines1384 )1385 1386 def make_module(1387 self,1392- vars: t.Optional[dict[str, t.Any]] = None,1388+ vars: dict[str, t.Any] | None = None,1389 shared: bool = False,1394- locals: t.Optional[t.Mapping[str, t.Any]] = None,1390+ locals: t.Mapping[str, t.Any] | None = None,1391 ) -> "TemplateModule":1392 """This method works like the :attr:`module` attribute when called1393 without arguments but it will evaluate the template on every call1394 rather than caching it. It's also possible to provide4 unmodified lines1399 return TemplateModule(self, ctx)1400 1401 async def make_module_async(1402 self,1407- vars: t.Optional[dict[str, t.Any]] = None,1403+ vars: dict[str, t.Any] | None = None,1404 shared: bool = False,1409- locals: t.Optional[t.Mapping[str, t.Any]] = None,1405+ locals: t.Mapping[str, t.Any] | None = None,1406 ) -> "TemplateModule":1407 """As template module creation can invoke template code for1408 asynchronous executions this method must be used instead of the1409 normal :meth:`make_module` one. Likewise the module attribute6 unmodified lines1416 [x async for x in self.root_render_func(ctx)], # type: ignore1417 )1418 1419 @internalcode1424- def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":1420+ def _get_default_module(self, ctx: Context | None = None) -> "TemplateModule":1421 """If a context is passed in, this means that the template was1422 imported. Imported templates have access to the current1423 template's globals by default, but they can only be accessed via1424 the context during runtime.18 unmodified lines1443 1444 return self._module1445 1446 async def _get_default_module_async(1451- self, ctx: t.Optional[Context] = None1447+ self, ctx: Context | None = None1448 ) -> "TemplateModule":1449 if ctx is not None:1450 keys = ctx.globals_keys - self.globals.keys()1451 65 unmodified lines1517 def __init__(1518 self,1519 template: Template,1520 context: Context,1525- body_stream: t.Optional[t.Iterable[str]] = None,1521+ body_stream: t.Iterable[str] | None = None,1522 ) -> None:1523 if body_stream is None:1524 if context.environment.is_async:1525 raise RuntimeError(31 unmodified lines1557 def __init__(self, template: Template, undefined_to_none: bool) -> None:1558 self._template = template1559 self._undefined_to_none = undefined_to_none1560 1565- def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]:1561+ def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any | None:1562 context = self._template.new_context(dict(*args, **kwargs))1563 consume(self._template.root_render_func(context))1564 rv = context.vars["result"]1565 if self._undefined_to_none and isinstance(rv, Undefined):17 unmodified lines1583 self.disable_buffering()1584 1585 def dump(1586 self,1591- fp: t.Union[str, t.IO[bytes]],1592- encoding: t.Optional[str] = None,1593- errors: t.Optional[str] = "strict",1587+ fp: str | t.IO[bytes],1588+ encoding: str | None = None,1589+ errors: str | None = "strict",1590 ) -> None:1591 """Dump the complete stream into a file or file-like object.1592 Per default strings are written, if you want to encode1593 before writing specify an `encoding`.73 unmodified linesmodified:src/jinja2/exceptions.py+9 added-9 removed
5 unmodified lines6 7 class TemplateError(Exception):8 """Baseclass for all template errors."""9 10- def __init__(self, message: t.Optional[str] = None) -> None:10+ def __init__(self, message: str | None = None) -> None:11 super().__init__(message)12 13 @property14- def message(self) -> t.Optional[str]:14+ def message(self) -> str | None:15 return self.args[0] if self.args else None16 17 18 class TemplateNotFound(IOError, LookupError, TemplateError):5 unmodified lines24 """25 26 # Silence the Python warning about message being deprecated since27 # it's not valid here.28- message: t.Optional[str] = None28+ message: str | None = None29 30 def __init__(31 self,32- name: t.Optional[t.Union[str, "Undefined"]],33- message: t.Optional[str] = None,32+ name: t.Union[str, "Undefined"] | None,33+ message: str | None = None,34 ) -> None:35 IOError.__init__(self, name)36 37 if message is None:26 unmodified lines64 65 def __init__(66 self,67 names: t.Sequence[t.Union[str, "Undefined"]] = (),68- message: t.Optional[str] = None,68+ message: str | None = None,69 ) -> None:70 if message is None:71 from .runtime import Undefined72 18 unmodified lines91 def __init__(92 self,93 message: str,94 lineno: int,95- name: t.Optional[str] = None,96- filename: t.Optional[str] = None,95+ name: str | None = None,96+ filename: str | None = None,97 ) -> None:98 super().__init__(message)99 self.lineno = lineno100 self.name = name101 self.filename = filename102- self.source: t.Optional[str] = None102+ self.source: str | None = None103 104 # this is set to True if the debug.translate_syntax_error105 # function translated the syntax error into a new traceback106 self.translated = False60 unmodified linesmodified:src/jinja2/ext.py+28 added-34 removed
35 unmodified lines36 def npgettext(37 self, context: str, singular: str, plural: str, n: int38 ) -> str: ...39 40- _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]40+ _SupportedTranslations = _TranslationsBasic | _TranslationsContext41 42 43 # I18N functions available in Jinja templates. If the I18N library44 # provides ugettext, it will be assigned to gettext.51 unmodified lines96 rv.environment = environment97 return rv98 99 def preprocess(100- self, source: str, name: t.Optional[str], filename: t.Optional[str] = None100+ self, source: str, name: str | None, filename: str | None = None101 ) -> str:102 """This method is called before the actual lexing and can be used to103 preprocess the source. The `filename` is optional. The return value104 must be the preprocessed source.9 unmodified lines114 :class:`~jinja2.lexer.TokenStream`.115 """116 return stream117 118- def parse(self, parser: "Parser") -> t.Union[nodes.Node, list[nodes.Node]]:118+ def parse(self, parser: "Parser") -> 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.123 """124 raise NotImplementedError()125 126- def attr(127- self, name: str, lineno: t.Optional[int] = None128- ) -> nodes.ExtensionAttribute:126+ def attr(self, name: str, lineno: int | None = None) -> nodes.ExtensionAttribute:127 """Return an attribute node for the current extension. This is useful128 to pass constants on extensions to generated template code.129 130 ::4 unmodified lines135 136 def call_method(137 self,138 name: str,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,139+ args: list[nodes.Expr] | None = None,140+ kwargs: list[nodes.Keyword] | None = None,141+ dyn_args: nodes.Expr | None = None,142+ dyn_kwargs: nodes.Expr | None = None,143+ lineno: int | None = None,144 ) -> nodes.Call:145 """Call a method of the extension. This is a shortcut for146 :meth:`attr` + :class:`jinja2.nodes.Call`.147 """13 unmodified lines161 162 @pass_context163 def _gettext_alias(164 __context: Context, *args: t.Any, **kwargs: t.Any167-) -> t.Union[t.Any, Undefined]:165+) -> t.Any | Undefined:166 return __context.call(__context.resolve("gettext"), *args, **kwargs)167 168 169 def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:95 unmodified lines265 newstyle_gettext=False,266 )267 268 def _install(271- self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None269+ self, translations: "_SupportedTranslations", newstyle: bool | None = None270 ) -> None:271 # ugettext and ungettext are preferred in case the I18N library272 # is providing compatibility with older Python versions.273 gettext = getattr(translations, "ugettext", None)8 unmodified lines282 self._install_callables(283 gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext284 )285 288- def _install_null(self, newstyle: t.Optional[bool] = None) -> None:286+ def _install_null(self, newstyle: bool | None = None) -> None:287 import gettext288 289 translations = gettext.NullTranslations()290 self._install_callables(7 unmodified lines298 def _install_callables(299 self,300 gettext: t.Callable[[str], str],301 ngettext: t.Callable[[str, str, int], str],304- newstyle: t.Optional[bool] = None,305- pgettext: t.Optional[t.Callable[[str, str], str]] = None,306- npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,302+ newstyle: bool | None = None,303+ pgettext: t.Callable[[str, str], str] | None = None,304+ npgettext: t.Callable[[str, str, str, int], str] | None = None,305 ) -> None:306 if newstyle is not None:307 self.environment.newstyle_gettext = newstyle # type: ignore308 if self.environment.newstyle_gettext: # type: ignore15 unmodified lines324 self.environment.globals.pop(key, None)325 326 def _extract(327 self,330- source: t.Union[str, nodes.Template],328+ source: str | nodes.Template,329 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,332- ) -> t.Iterator[333- tuple[int, str, t.Union[t.Optional[str], tuple[t.Optional[str], ...]]]334- ]:330+ ) -> t.Iterator[tuple[int, str, str | None | tuple[str | None, ...]]]:331 if isinstance(source, str):332 source = self.environment.parse(source)333 return extract_from_ast(source, gettext_functions)334 339- def parse(self, parser: "Parser") -> t.Union[nodes.Node, list[nodes.Node]]:335+ def parse(self, parser: "Parser") -> nodes.Node | list[nodes.Node]:336 """Parse a translatable tag."""337 lineno = next(parser.stream).lineno338 339 context = None4 unmodified lines344 345 # find all the variables referenced. Additionally a variable can be346 # defined in the body of the trans block too, but this is checked at347 # a later state.352- plural_expr: t.Optional[nodes.Expr] = None353- plural_expr_assignment: t.Optional[nodes.Assign] = None348+ plural_expr: nodes.Expr | None = None349+ plural_expr_assignment: nodes.Assign | None = None350 num_called_num = False351 variables: dict[str, nodes.Expr] = {}352 trimmed = None353 while parser.stream.current.type != "block_end":152 unmodified lines506 507 def _make_node(508 self,509 singular: str,514- plural: t.Optional[str],515- context: t.Optional[str],510+ plural: str | None,511+ context: str | None,512 variables: dict[str, nodes.Expr],517- plural_expr: t.Optional[nodes.Expr],513+ plural_expr: nodes.Expr | None,514 vars_referenced: bool,515 num_called_num: bool,516 ) -> nodes.Output:517 """Generates a useful node from the data provided."""66 unmodified lines584 """Adds break and continue to the template engine."""585 586 tags = {"break", "continue"}587 592- def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:588+ def parse(self, parser: "Parser") -> nodes.Break | nodes.Continue:589 token = next(parser.stream)590 if token.value == "break":591 return nodes.Break(lineno=token.lineno)592 return nodes.Continue(lineno=token.lineno)42 unmodified lines635 def extract_from_ast(636 ast: nodes.Template,637 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,638 babel_style: bool = True,643-) -> t.Iterator[tuple[int, str, t.Union[t.Optional[str], tuple[t.Optional[str], ...]]]]:639+) -> t.Iterator[tuple[int, str, str | None | tuple[str | None, ...]]]:640 """Extract localizable strings from the given template node. Per641 default this function returns matches in babel style that means non string642 parameters as well as keyword arguments are returned as `None`. This643 allows Babel to figure out what you really meant if you are using26 unmodified lines670 This extraction function operates on the AST and is because of that unable671 to extract any comments. For comment support you have to use the babel672 extraction interface or extract comments yourself.673 """678- out: t.Union[t.Optional[str], tuple[t.Optional[str], ...]]674+ out: str | None | tuple[str | None, ...]675 676 for node in ast.find_all(nodes.Call):677 if (678 not isinstance(node.node, nodes.Name)679 or node.node.name not in gettext_functions680 ):681 continue682 687- strings: list[t.Optional[str]] = []683+ strings: list[str | None] = []684 685 for arg in node.args:686 if isinstance(arg, nodes.Const) and isinstance(arg.value, str):687 strings.append(arg.value)65 unmodified lines753 fileobj: t.BinaryIO,754 keywords: t.Sequence[str],755 comment_tags: t.Sequence[str],756 options: dict[str, t.Any],761-) -> t.Iterator[762- tuple[int, str, t.Union[t.Optional[str], tuple[t.Optional[str], ...]], list[str]]763-]:757+) -> t.Iterator[tuple[int, str, str | None | tuple[str | None, ...], list[str]]]:758 """Babel extraction method for Jinja templates.759 760 .. versionchanged:: 2.3761 Basic support for translation comments was added. If `comment_tags`83 unmodified linesmodified:src/jinja2/filters.py+66 added-72 removed
55 unmodified lines56 57 58 def make_attrgetter(59 environment: "Environment",60- attribute: t.Optional[t.Union[str, int]],61- postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,62- default: t.Optional[t.Any] = None,60+ attribute: str | int | None,61+ postprocess: t.Callable[[t.Any], t.Any] | None = None,62+ default: t.Any | None = None,63 ) -> t.Callable[[t.Any], t.Any]:64 """Returns a callable that looks up the given attribute from a65 passed object with the rules of the environment. Dots are allowed66 to access attributes of attributes. Integer parts in paths are17 unmodified lines84 85 86 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,88+ attribute: str | int | None,89+ postprocess: t.Callable[[t.Any], t.Any] | None = None,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. Integer4 unmodified lines98 99 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.100 """101 if isinstance(attribute, str):102- split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")102+ split: t.Sequence[str | int | None] = attribute.split(",")103 else:104 split = [attribute]105 106 parts = [_prepare_attribute_parts(item) for item in split]17 unmodified lines124 return attrgetter125 126 127 def _prepare_attribute_parts(128- attr: t.Optional[t.Union[str, int]],129-) -> list[t.Union[str, int]]:128+ attr: str | int | None,129+) -> list[str | int]:130 if attr is None:131 return []132 133 if isinstance(attr, str):1 unmodified line135 136 return [attr]137 138 139-def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:139+def do_forceescape(value: "str | HasHTML") -> Markup:140 """Enforce HTML escaping. This will probably double escape variables."""141 if hasattr(value, "__html__"):142 value = t.cast("HasHTML", value).__html__()143 144 return escape(str(value))145 146 147 def do_urlencode(148- value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[tuple[str, t.Any]]],148+ value: 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 a23 unmodified lines176 177 178 @pass_eval_context179 def do_replace(180- eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None180+ eval_ctx: "EvalContext", s: str, old: str, new: str, count: int | None = None181 ) -> str:182 """Return a copy of the value with all occurrences of a substring183 replaced with a new one. The first argument is the substring184 that should be replaced, the second is the replacement string.35 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[tuple[K, V]]:224+def do_items(value: 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.158 unmodified lines387 environment: "Environment",388 value: "t.Iterable[V]",389 reverse: bool = False,390 case_sensitive: bool = False,391- attribute: t.Optional[t.Union[str, int]] = None,391+ attribute: str | int | None = None,392 ) -> "list[V]":393 """Sort an iterable using Python's :func:`sorted`.394 395 .. sourcecode:: jinja46 unmodified lines442 def sync_do_unique(443 environment: "Environment",444 value: "t.Iterable[V]",445 case_sensitive: bool = False,446- attribute: t.Optional[t.Union[str, int]] = None,446+ attribute: str | int | None = None,447 ) -> "t.Iterator[V]":448 """Returns a list of unique items from the given iterable.449 450 .. sourcecode:: jinja22 unmodified lines473 474 @async_variant(sync_do_unique) # type: ignore475 async def do_unique(476 environment: "Environment",477- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",477+ value: "t.AsyncIterable[V] | t.Iterable[V]",478 case_sensitive: bool = False,479- attribute: t.Optional[t.Union[str, int]] = None,479+ attribute: str | int | None = None,480 ) -> "t.Iterator[V]":481 return sync_do_unique(482 environment, await auto_to_list(value), case_sensitive, attribute483 )3 unmodified lines487 environment: "Environment",488 value: "t.Iterable[V]",489 func: "t.Callable[..., V]",490 case_sensitive: bool,491- attribute: t.Optional[t.Union[str, int]],492-) -> "t.Union[V, Undefined]":491+ attribute: str | int | None,492+) -> "V | Undefined":493 it = iter(value)494 495 try:496 first = next(it)10 unmodified lines507 def do_min(508 environment: "Environment",509 value: "t.Iterable[V]",510 case_sensitive: bool = False,511- attribute: t.Optional[t.Union[str, int]] = None,512-) -> "t.Union[V, Undefined]":511+ attribute: str | int | None = None,512+) -> "V | Undefined":513 """Return the smallest item from the sequence.514 515 .. sourcecode:: jinja516 10 unmodified lines527 def do_max(528 environment: "Environment",529 value: "t.Iterable[V]",530 case_sensitive: bool = False,531- attribute: t.Optional[t.Union[str, int]] = None,532-) -> "t.Union[V, Undefined]":531+ attribute: str | int | None = None,532+) -> "V | Undefined":533 """Return the largest item from the sequence.534 535 .. sourcecode:: jinja536 43 unmodified lines580 def sync_do_join(581 eval_ctx: "EvalContext",582 value: t.Iterable[t.Any],583 d: str = "",584- attribute: t.Optional[t.Union[str, int]] = None,584+ attribute: str | int | None = None,585 ) -> str:586 """Return a string which is the concatenation of the strings in the587 sequence. The separator between elements is an empty string per588 default, you can define it with the optional parameter:47 unmodified lines636 637 @async_variant(sync_do_join) # type: ignore638 async def do_join(639 eval_ctx: "EvalContext",640- value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],640+ value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],641 d: str = "",642- attribute: t.Optional[t.Union[str, int]] = None,642+ attribute: str | int | None = None,643 ) -> str:644 return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)645 646 2 unmodified lines649 return soft_str(value).center(width)650 651 652 @pass_environment653-def sync_do_first(654- environment: "Environment", seq: "t.Iterable[V]"655-) -> "t.Union[V, Undefined]":653+def sync_do_first(environment: "Environment", seq: "t.Iterable[V]") -> "V | Undefined":654 """Return the first item of a sequence."""655 try:656 return next(iter(seq))657 except StopIteration:1 unmodified line659 660 661 @async_variant(sync_do_first) # type: ignore662 async def do_first(665- environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"666-) -> "t.Union[V, Undefined]":663+ environment: "Environment", seq: "t.AsyncIterable[V] | t.Iterable[V]"664+) -> "V | Undefined":665 try:666 return await auto_aiter(seq).__anext__()667 except StopAsyncIteration:668 return environment.undefined("No first item, sequence was empty.")669 670 671 @pass_environment674-def do_last(675- environment: "Environment", seq: "t.Reversible[V]"676-) -> "t.Union[V, Undefined]":672+def do_last(environment: "Environment", seq: "t.Reversible[V]") -> "V | Undefined":673 """Return the last item of a sequence.674 675 Note: Does not work with generators. You may want to explicitly676 convert it to a list:11 unmodified lines688 # No async do_last, it may not be safe in async mode.689 690 691 @pass_context696-def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":692+def do_random(context: "Context", seq: "t.Sequence[V]") -> "V | Undefined":693 """Return a random item from the sequence."""694 try:695 return random.choice(seq)696 except IndexError:697 return context.environment.undefined("No random item, sequence was empty.")698 699 704-def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:700+def do_filesizeformat(value: str | float | int, binary: bool = False) -> str:701 """Format the value like a 'human-readable' file size (i.e. 13 kB,702 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,703 Giga, etc.), if the second parameter is set to `True` the binary704 prefixes are used (Mebi, Gibi).36 unmodified lines741 @pass_eval_context742 def do_urlize(743 eval_ctx: "EvalContext",744 value: str,749- trim_url_limit: t.Optional[int] = None,745+ trim_url_limit: int | None = None,746 nofollow: bool = False,751- target: t.Optional[str] = None,752- rel: t.Optional[str] = None,753- extra_schemes: t.Optional[t.Iterable[str]] = None,747+ target: str | None = None,748+ rel: str | None = None,749+ extra_schemes: t.Iterable[str] | None = None,750 ) -> str:751 """Convert URLs in text into clickable links.752 753 This may not recognize links in some situations. Usually, a more64 unmodified lines818 return rv819 820 821 def do_indent(826- s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False822+ s: str, width: int | str = 4, first: bool = False, blank: bool = False823 ) -> str:824 """Return a copy of the string with each line indented by 4 spaces. The825 first line and blank lines are not indented by default.826 45 unmodified lines872 s: str,873 length: int = 255,874 killwords: bool = False,875 end: str = "...",880- leeway: t.Optional[int] = None,876+ leeway: int | None = None,877 ) -> str:878 """Return a truncated copy of the string. The length is specified879 with the first parameter which defaults to ``255``. If the second880 parameter is ``true`` the filter will cut the text at length. Otherwise38 unmodified lines919 environment: "Environment",920 s: str,921 width: int = 79,922 break_long_words: bool = True,927- wrapstring: t.Optional[str] = None,923+ wrapstring: str | None = None,924 break_on_hyphens: bool = True,925 ) -> str:926 """Wrap a string to the given width. Existing newlines are treated927 as paragraphs to be wrapped separately.110 unmodified lines1038 1039 return soft_str(value) % (kwargs or args)1040 1041 1046-def do_trim(value: str, chars: t.Optional[str] = None) -> str:1042+def do_trim(value: str, chars: str | None = None) -> str:1043 """Strip leading and trailing characters, by default whitespace."""1044 return soft_str(value).strip(chars)1045 1046 1051-def do_striptags(value: "t.Union[str, HasHTML]") -> str:1047+def do_striptags(value: "str | HasHTML") -> str:1048 """Strip SGML/XML tags and replace adjacent whitespace by one space."""1049 if hasattr(value, "__html__"):1050 value = t.cast("HasHTML", value).__html__()1051 1052 return Markup(str(value)).striptags()1053 1054 1055 def sync_do_slice(1060- value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None1056+ value: "t.Collection[V]", slices: int, fill_with: "V | None" = None1057 ) -> "t.Iterator[list[V]]":1058 """Slice an iterator and return a list of lists containing1059 those items. Useful if you want to create a div containing1060 three ul tags that represent columns:35 unmodified lines1096 1097 1098 @async_variant(sync_do_slice) # type: ignore1099 async def do_slice(1104- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1100+ value: "t.AsyncIterable[V] | t.Iterable[V]",1101 slices: int,1106- fill_with: t.Optional[t.Any] = None,1102+ fill_with: t.Any | None = None,1103 ) -> "t.Iterator[list[V]]":1104 return sync_do_slice(await auto_to_list(value), slices, fill_with)1105 1106 1107 def do_batch(1112- value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None1108+ value: "t.Iterable[V]", linecount: int, fill_with: "V | None" = None1109 ) -> "t.Iterator[list[V]]":1110 """1111 A filter that batches items. It works pretty much like `slice`1112 just the other way round. It returns a list of lists with the84 unmodified lines1197 @pass_environment1198 def sync_do_groupby(1199 environment: "Environment",1200 value: "t.Iterable[V]",1205- attribute: t.Union[str, int],1206- default: t.Optional[t.Any] = None,1201+ attribute: str | int,1202+ default: t.Any | None = None,1203 case_sensitive: bool = False,1204 ) -> "list[_GroupTuple]":1205 """Group a sequence of objects by an attribute using Python's1206 :func:`itertools.groupby`. The attribute can use dot notation for73 unmodified lines1280 1281 @async_variant(sync_do_groupby) # type: ignore1282 async def do_groupby(1283 environment: "Environment",1288- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1289- attribute: t.Union[str, int],1290- default: t.Optional[t.Any] = None,1284+ value: "t.AsyncIterable[V] | t.Iterable[V]",1285+ attribute: str | int,1286+ default: t.Any | None = None,1287 case_sensitive: bool = False,1288 ) -> "list[_GroupTuple]":1289 expr = make_attrgetter(1290 environment,17 unmodified lines1308 @pass_environment1309 def sync_do_sum(1310 environment: "Environment",1311 iterable: "t.Iterable[V]",1316- attribute: t.Optional[t.Union[str, int]] = None,1312+ attribute: str | int | None = None,1313 start: V = 0, # type: ignore1314 ) -> V:1315 """Returns the sum of a sequence of numbers plus the value of parameter1316 'start' (which defaults to 0). When the sequence is empty it returns17 unmodified lines1334 1335 @async_variant(sync_do_sum) # type: ignore1336 async def do_sum(1337 environment: "Environment",1342- iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1343- attribute: t.Optional[t.Union[str, int]] = None,1338+ iterable: "t.AsyncIterable[V] | t.Iterable[V]",1339+ attribute: str | int | None = None,1340 start: V = 0, # type: ignore1341 ) -> V:1342 rv = start1343 17 unmodified lines1361 return list(value)1362 1363 1364 @async_variant(sync_do_list) # type: ignore1369-async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "list[V]":1365+async def do_list(value: "t.AsyncIterable[V] | t.Iterable[V]") -> "list[V]":1366 return await auto_to_list(value)1367 1368 1369 def do_mark_safe(value: str) -> Markup:15 unmodified lines1385 @typing.overload1386 def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...1387 1388 1393-def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:1389+def do_reverse(value: str | t.Iterable[V]) -> str | t.Iterable[V]:1390 """Reverse the object or return an iterator that iterates over it the other1391 way round.1392 """1393 if isinstance(value, str):10 unmodified lines1404 raise FilterArgumentError("argument must be iterable") from e1405 1406 1407 @pass_environment1412-def do_attr(1413- environment: "Environment", obj: t.Any, name: str1414-) -> t.Union[Undefined, t.Any]:1408+def do_attr(environment: "Environment", obj: t.Any, name: str) -> Undefined | t.Any:1409 """Get an attribute of an object. ``foo|attr("bar")`` works like1410 ``foo.bar``, but returns undefined instead of falling back to ``foo["bar"]``1411 if the attribute doesn't exist.1412 29 unmodified lines1442 context: "Context",1443 value: t.Iterable[t.Any],1444 *,1445 attribute: str = ...,1452- default: t.Optional[t.Any] = None,1446+ default: t.Any | None = None,1447 ) -> t.Iterable[t.Any]: ...1448 1449 1450 @pass_context48 unmodified lines1499 1500 @typing.overload1501 def do_map(1502 context: "Context",1509- value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1503+ value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],1504 name: str,1505 *args: t.Any,1506 **kwargs: t.Any,1507 ) -> t.Iterable[t.Any]: ...1 unmodified line1509 1510 @typing.overload1511 def do_map(1512 context: "Context",1519- value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1513+ value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],1514 *,1515 attribute: str = ...,1522- default: t.Optional[t.Any] = None,1516+ default: t.Any | None = None,1517 ) -> t.Iterable[t.Any]: ...1518 1519 1520 @async_variant(sync_do_map) # type: ignore1521 async def do_map(1522 context: "Context",1529- value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1523+ value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],1524 *args: t.Any,1525 **kwargs: t.Any,1526 ) -> t.AsyncIterable[t.Any]:1527 if value:36 unmodified lines1564 1565 @async_variant(sync_do_select) # type: ignore1566 async def do_select(1567 context: "Context",1574- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1568+ value: "t.AsyncIterable[V] | t.Iterable[V]",1569 *args: t.Any,1570 **kwargs: t.Any,1571 ) -> "t.AsyncIterator[V]":1572 return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)27 unmodified lines1600 1601 @async_variant(sync_do_reject) # type: ignore1602 async def do_reject(1603 context: "Context",1610- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1604+ value: "t.AsyncIterable[V] | t.Iterable[V]",1605 *args: t.Any,1606 **kwargs: t.Any,1607 ) -> "t.AsyncIterator[V]":1608 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)31 unmodified lines1640 1641 @async_variant(sync_do_selectattr) # type: ignore1642 async def do_selectattr(1643 context: "Context",1650- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1644+ value: "t.AsyncIterable[V] | t.Iterable[V]",1645 *args: t.Any,1646 **kwargs: t.Any,1647 ) -> "t.AsyncIterator[V]":1648 return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)29 unmodified lines1678 1679 @async_variant(sync_do_rejectattr) # type: ignore1680 async def do_rejectattr(1681 context: "Context",1688- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1682+ value: "t.AsyncIterable[V] | t.Iterable[V]",1683 *args: t.Any,1684 **kwargs: t.Any,1685 ) -> "t.AsyncIterator[V]":1686 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)1687 1688 1689 @pass_eval_context1690 def do_tojson(1697- eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None1691+ eval_ctx: "EvalContext", value: t.Any, indent: int | None = None1692 ) -> Markup:1693 """Serialize an object to a string of JSON, and mark it safe to1694 render in HTML. This filter is only for use in HTML documents.1695 98 unmodified lines1794 1795 1796 async def async_select_or_reject(1797 context: "Context",1804- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1798+ value: "t.AsyncIterable[V] | t.Iterable[V]",1799 args: tuple[t.Any, ...],1800 kwargs: dict[str, t.Any],1801 modfunc: t.Callable[[t.Any], t.Any],1802 lookup_attr: bool,65 unmodified linesmodified:src/jinja2/idtracking.py+6 added-8 removed
30 unmodified lines31 32 33 class Symbols:34 def __init__(35- self, parent: t.Optional["Symbols"] = None, level: t.Optional[int] = None35+ self, parent: t.Optional["Symbols"] = None, level: int | None = None36 ) -> None:37 if level is None:38 if parent is None:39 level = 09 unmodified lines49 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[tuple[str, t.Optional[str]]] = None55- ) -> str:53+ def _define_ref(self, name: str, load: tuple[str, str | None] | None = None) -> str:54 ident = f"l_{self.level}_{name}"55 self.refs[name] = ident56 if load is not None:57 self.loads[ident] = load58 return ident59 62- def find_load(self, target: str) -> t.Optional[t.Any]:60+ def find_load(self, target: str) -> t.Any | None:61 if target in self.loads:62 return self.loads[target]63 64 if self.parent is not None:65 return self.parent.find_load(target)66 67 return None68 71- def find_ref(self, name: str) -> t.Optional[str]:69+ def find_ref(self, name: str) -> str | None:70 if name in self.refs:71 return self.refs[name]72 73 if self.parent is not None:69 unmodified lines143 self.loads[target] = (VAR_LOAD_RESOLVE, name)144 145 def dump_stores(self) -> dict[str, str]:146 rv: dict[str, str] = {}149- node: t.Optional[Symbols] = self147+ node: Symbols | None = self148 149 while node is not None:150 for name in sorted(node.stores):151 if name not in rv:4 unmodified lines156 return rv157 158 def dump_param_targets(self) -> set[str]:159 rv = set()162- node: t.Optional[Symbols] = self160+ node: Symbols | None = self161 162 while node is not None:163 for target, (instr, _) in self.loads.items():164 if instr == VAR_LOAD_PARAMETER:152 unmodified linesmodified:src/jinja2/lexer.py+14 added-14 removed
260 unmodified lines261 ) -> None:262 self.message = message263 self.error_class = cls264 265- def __call__(self, lineno: int, filename: t.Optional[str]) -> "te.NoReturn":265+ def __call__(self, lineno: int, filename: str | None) -> "te.NoReturn":266 raise self.error_class(self.message, lineno, filename)267 268 269 class Token(t.NamedTuple):54 unmodified lines324 325 def __init__(326 self,327 generator: t.Iterable[Token],328- name: t.Optional[str],329- filename: t.Optional[str],328+ name: str | None,329+ filename: str | None,330 ):331 self._iter = iter(generator)332 self._pushed: deque[Token] = deque()333 self.name = name29 unmodified lines363 """Got n tokens ahead."""364 for _ in range(n):365 next(self)366 367- def next_if(self, expr: str) -> t.Optional[Token]:367+ def next_if(self, expr: str) -> Token | None:368 """Perform the token test and return the token if it matched.369 Otherwise the return value is `None`.370 """371 if self.current.test(expr):91 unmodified lines463 464 465 class _Rule(t.NamedTuple):466 pattern: t.Pattern[str]467- tokens: t.Union[str, tuple[str, ...], tuple[Failure]]468- command: t.Optional[str]467+ tokens: str | tuple[str, ...] | tuple[Failure]468+ command: str | None469 470 471 class Lexer:472 """Class that implements a lexer for a given environment. Automatically130 unmodified lines603 604 def tokenize(605 self,606 source: str,607- name: t.Optional[str] = None,608- filename: t.Optional[str] = None,609- state: t.Optional[str] = None,607+ name: str | None = None,608+ filename: str | None = None,609+ state: str | None = None,610 ) -> TokenStream:611 """Calls tokeniter + tokenize and wraps it in a token stream."""612 stream = self.tokeniter(source, name, filename, state)613 return TokenStream(self.wrap(stream, name, filename), name, filename)614 615 def wrap(616 self,617 stream: t.Iterable[tuple[int, str, str]],618- name: t.Optional[str] = None,619- filename: t.Optional[str] = None,618+ name: str | None = None,619+ filename: str | None = None,620 ) -> t.Iterator[Token]:621 """This is called with the stream as returned by `tokenize` and wraps622 every token in a :class:`Token` and converts the value.623 """44 unmodified lines668 669 def tokeniter(670 self,671 source: str,672- name: t.Optional[str],673- filename: t.Optional[str] = None,674- state: t.Optional[str] = None,672+ name: str | None,673+ filename: str | None = None,674+ state: str | None = None,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 190 unmodified linesmodified:src/jinja2/loaders.py+11 added-15 removed
72 unmodified lines73 has_source_access = True74 75 def get_source(76 self, environment: "Environment", template: str77- ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:77+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]: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.26 unmodified lines108 def load(109 self,110 environment: "Environment",111 name: str,112- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,112+ globals: t.MutableMapping[str, t.Any] | None = None,113 ) -> "Template":114 """Loads a template. This method looks up the template in the cache115 or loads one by calling :meth:`get_source`. Subclasses should not116 override this method as loaders working on collections of other246 unmodified lines363 self._template_root = template_root364 365 def get_source(366 self, environment: "Environment", template: str367- ) -> tuple[str, str, t.Optional[t.Callable[[], bool]]]:367+ ) -> tuple[str, str, t.Callable[[], bool] | None]: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(372 posixpath.join(self._template_root, *split_template_path(template))373 )374- up_to_date: t.Optional[t.Callable[[], bool]]374+ up_to_date: t.Callable[[], bool] | None375 376 if self._archive is None:377 # Package is a directory.378 if not os.path.isfile(p):95 unmodified lines474 def __init__(475 self,476 load_func: t.Callable[477 [str],478- t.Optional[479- t.Union[480- str, tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]481- ]482- ],478+ str | tuple[str, str | None, t.Callable[[], bool] | None] | None,479 ],480 ) -> None:481 self.load_func = load_func482 483 def get_source(484 self, environment: "Environment", template: str489- ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:485+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:486 rv = self.load_func(template)487 488 if rv is None:489 raise TemplateNotFound(template)34 unmodified lines524 return loader, name525 526 def get_source(527 self, environment: "Environment", template: str532- ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:528+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:529 loader, name = self.get_loader(template)530 try:531 return loader.get_source(environment, name)532 except TemplateNotFound as e:5 unmodified lines538 def load(539 self,540 environment: "Environment",541 name: str,546- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,542+ globals: t.MutableMapping[str, t.Any] | None = None,543 ) -> "Template":544 loader, local_name = self.get_loader(name)545 try:546 return loader.load(environment, local_name, globals)28 unmodified lines575 self.loaders = loaders576 577 def get_source(578 self, environment: "Environment", template: str583- ) -> tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:579+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:580 for loader in self.loaders:581 try:582 return loader.get_source(environment, template)583 except TemplateNotFound:4 unmodified lines588 def load(589 self,590 environment: "Environment",591 name: str,596- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,592+ globals: t.MutableMapping[str, t.Any] | None = None,593 ) -> "Template":594 for loader in self.loaders:595 try:596 return loader.load(environment, name, globals)63 unmodified lines660 def load(661 self,662 environment: "Environment",663 name: str,668- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,664+ globals: t.MutableMapping[str, t.Any] | None = None,665 ) -> "Template":666 key = self.get_template_key(name)667 module = f"{self.package_name}.{key}"668 mod = getattr(self.module, module, None)17 unmodified linesmodified:src/jinja2/meta.py+2 added-2 removed
54 unmodified lines55 return codegen.undeclared_identifiers56 57 58 _ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)59-_RefType = t.Union[nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include]59+_RefType = nodes.Extends | nodes.FromImport | nodes.Import | nodes.Include60 61 62-def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]:62+def find_referenced_templates(ast: nodes.Template) -> t.Iterator[str | None]:63 """Finds all the referenced templates from the AST. This will return an64 iterator over all the hardcoded template extensions, inclusions and65 imports. If dynamic inheritance or inclusion is used, `None` will be66 yielded.46 unmodified linesmodified:src/jinja2/nativetypes.py+1 added-1 removed
11 unmodified lines12 from .environment import Environment13 from .environment import Template14 15 16-def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:16+def native_concat(values: t.Iterable[t.Any]) -> t.Any | None:17 """Return a native Python type from the list of compiled nodes. If18 the result is a single node, its value is returned. Otherwise, the19 nodes are concatenated as strings. If the result can be parsed with20 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,110 unmodified linesmodified:src/jinja2/nodes.py+47 added-49 removed
72 unmodified lines73 to it in extensions.74 """75 76 def __init__(77- self, environment: "Environment", template_name: t.Optional[str] = None77+ self, environment: "Environment", template_name: str | None = None78 ) -> None:79 self.environment = environment80 if callable(environment.autoescape):81 self.autoescape = environment.autoescape(template_name)8 unmodified lines90 self.__dict__.clear()91 self.__dict__.update(old)92 93 94-def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:94+def get_eval_context(node: "Node", ctx: EvalContext | None) -> EvalContext:95 if ctx is None:96 if node.environment is None:97 raise RuntimeError(98 "if no eval context is passed, the node must have an"37 unmodified lines136 raise TypeError(137 f"{type(self).__name__!r} takes 0 or {len(self.fields)}"138 f" argument{'s' if len(self.fields) != 1 else ''}"139 )140- for name, arg in zip(self.fields, fields):140+ for name, arg in zip(self.fields, fields, strict=False):141 setattr(self, name, arg)142 for attr in self.attributes:143 setattr(self, attr, attributes.pop(attr, None))144 if attributes:145 raise TypeError(f"unknown attribute {next(iter(attributes))!r}")146 147 def iter_fields(148 self,149- exclude: t.Optional[t.Container[str]] = None,150- only: t.Optional[t.Container[str]] = None,149+ exclude: t.Container[str] | None = None,150+ only: t.Container[str] | None = None,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`12 unmodified lines167 pass168 169 def iter_child_nodes(170 self,171- exclude: t.Optional[t.Container[str]] = None,172- only: t.Optional[t.Container[str]] = None,171+ exclude: t.Container[str] | None = None,172+ only: t.Container[str] | None = None,173 ) -> t.Iterator["Node"]:174 """Iterates over all direct child nodes of the node. This iterates175 over all fields and yields the values of they are nodes. If the value176 of a field is a list all the nodes in that list are returned.5 unmodified lines182 yield n183 elif isinstance(item, Node):184 yield item185 186- def find(self, node_type: type[_NodeBound]) -> t.Optional[_NodeBound]:186+ def find(self, node_type: type[_NodeBound]) -> _NodeBound | None: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[type[_NodeBound], tuple[type[_NodeBound], ...]]196+ self, node_type: 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 """48 unmodified lines249 args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)250 return f"{type(self).__name__}({args_str})"251 252 def dump(self) -> str:253- def _dump(node: t.Union[Node, t.Any]) -> None:253+ def _dump(node: Node | t.Any) -> None:254 if not isinstance(node, Node):255 buf.append(repr(node))256 return257 71 unmodified lines329 target: Node330 iter: Node331 body: list[Node]332 else_: list[Node]333- test: t.Optional[Node]333+ test: Node | None334 recursive: bool335 336 337 class If(Stmt):97 unmodified lines435 """436 437 fields = ("template", "names", "with_context")438 template: "Expr"439- names: list[t.Union[str, tuple[str, str]]]439+ names: list[str | tuple[str, str]]440 with_context: bool441 442 443 class ExprStmt(Stmt):24 unmodified lines468 """Baseclass for all expressions."""469 470 abstract = True471 472- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:472+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:473 """Return the value of the expression as constant or raise474 :exc:`Impossible` if this was not possible.475 476 An :class:`EvalContext` can be provided, if none is given18 unmodified lines495 right: Expr496 operator: str497 abstract = True498 499- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:499+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:500 eval_ctx = get_eval_context(self, eval_ctx)501 502 # intercepted operators cannot be folded at compile time503 if (15 unmodified lines519 node: Expr520 operator: str521 abstract = True522 523- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:523+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:524 eval_ctx = get_eval_context(self, eval_ctx)525 526 # intercepted operators cannot be folded at compile time527 if (55 unmodified lines583 584 fields = ("value",)585 value: t.Any586 587- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:587+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:588 return self.value589 590 @classmethod591 def from_untrusted(592 cls,593 value: t.Any,594- lineno: t.Optional[int] = None,595- environment: "t.Optional[Environment]" = None,594+ lineno: int | None = None,595+ environment: "Environment | None" = None,596 ) -> "Const":597 """Return a const object if the value is representable as598 constant value in the generated code, otherwise it will raise599 an `Impossible` exception.10 unmodified lines610 611 fields = ("data",)612 data: str613 614- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:614+ def as_const(self, eval_ctx: EvalContext | None = None) -> str:615 eval_ctx = get_eval_context(self, eval_ctx)616 if eval_ctx.volatile:617 raise Impossible()618 if eval_ctx.autoescape:10 unmodified lines629 fields = ("items", "ctx")630 items: list[Expr]631 ctx: str632 633- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> tuple[t.Any, ...]:633+ def as_const(self, eval_ctx: EvalContext | None = 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:8 unmodified lines646 647 fields = ("items",)648 items: list[Expr]649 650- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> list[t.Any]:650+ def as_const(self, eval_ctx: EvalContext | None = 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 4 unmodified lines659 660 fields = ("items",)661 items: list["Pair"]662 663- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> dict[t.Any, t.Any]:663+ def as_const(self, eval_ctx: EvalContext | None = 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 675- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> tuple[t.Any, t.Any]:675+ def as_const(self, eval_ctx: EvalContext | None = 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 687- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> tuple[str, t.Any]:687+ def as_const(self, eval_ctx: EvalContext | None = 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 4 unmodified lines696 697 fields = ("test", "expr1", "expr2")698 test: Expr699 expr1: Expr700- expr2: t.Optional[Expr]700+ expr2: Expr | None701 702- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:702+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:703 eval_ctx = get_eval_context(self, eval_ctx)704 if self.test.as_const(eval_ctx):705 return self.expr1.as_const(eval_ctx)706 4 unmodified lines711 return self.expr2.as_const(eval_ctx)712 713 714 def args_as_const(715- node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]715+ node: t.Union["_FilterTestCommon", "Call"], eval_ctx: EvalContext | None716 ) -> 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 17 unmodified lines737 node: Expr738 name: str739 args: list[Expr]740 kwargs: list[Pair]741- dyn_args: t.Optional[Expr]742- dyn_kwargs: t.Optional[Expr]741+ dyn_args: Expr | None742+ dyn_kwargs: Expr | None743 abstract = True744 _is_filter = True745 746- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:746+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:747 eval_ctx = get_eval_context(self, eval_ctx)748 749 if eval_ctx.volatile:750 raise Impossible()36 unmodified lines787 If ``node`` is ``None``, the filter is being used in a filter block788 and is applied to the content of the block.789 """790 791- node: t.Optional[Expr] # type: ignore791+ node: Expr | None # type: ignore792 793- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:793+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:794 if self.node is None:795 raise Impossible()796 797 return super().as_const(eval_ctx=eval_ctx)23 unmodified lines821 fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")822 node: Expr823 args: list[Expr]824 kwargs: list[Keyword]825- dyn_args: t.Optional[Expr]826- dyn_kwargs: t.Optional[Expr]825+ dyn_args: Expr | None826+ dyn_kwargs: Expr | None827 828 829 class Getitem(Expr):830 """Get an attribute or item from an expression and prefer the item."""2 unmodified lines833 node: Expr834 arg: Expr835 ctx: str836 837- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:837+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:838 if self.ctx != "load":839 raise Impossible()840 841 eval_ctx = get_eval_context(self, eval_ctx)15 unmodified lines857 node: Expr858 attr: str859 ctx: str860 861- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:861+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:862 if self.ctx != "load":863 raise Impossible()864 865 eval_ctx = get_eval_context(self, eval_ctx)9 unmodified lines875 :class:`Subscript`.876 """877 878 fields = ("start", "stop", "step")879- start: t.Optional[Expr]880- stop: t.Optional[Expr]881- step: t.Optional[Expr]879+ start: Expr | None880+ stop: Expr | None881+ step: Expr | None882 883- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:883+ def as_const(self, eval_ctx: EvalContext | None = None) -> slice:884 eval_ctx = get_eval_context(self, eval_ctx)885 886- def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:886+ def const(obj: Expr | None) -> t.Any | None:887 if obj is None:888 return None889 return obj.as_const(eval_ctx)890 7 unmodified lines898 899 fields = ("nodes",)900 nodes: list[Expr]901 902- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:902+ def as_const(self, eval_ctx: EvalContext | None = 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)905 906 5 unmodified lines912 fields = ("expr", "ops")913 expr: Expr914 ops: list["Operand"]915 916- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:916+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:917 eval_ctx = get_eval_context(self, eval_ctx)918 result = value = self.expr.as_const(eval_ctx)919 920 try:67 unmodified lines988 """Short circuited AND."""989 990 operator = "and"991 992- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:992+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:993 eval_ctx = get_eval_context(self, eval_ctx)994 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)995 996 1 unmodified line998 """Short circuited OR."""999 1000 operator = "or"1001 1002- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:1002+ def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:1003 eval_ctx = get_eval_context(self, eval_ctx)1004 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)1005 1006 74 unmodified lines1081 1082 fields = ("expr",)1083 expr: Expr1084 1085- def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:1085+ def as_const(self, eval_ctx: EvalContext | None = None) -> Markup:1086 eval_ctx = get_eval_context(self, eval_ctx)1087 return Markup(self.expr.as_const(eval_ctx))1088 1089 6 unmodified lines1096 1097 fields = ("expr",)1098 expr: Expr1099 1100- def as_const(1101- self, eval_ctx: t.Optional[EvalContext] = None1102- ) -> t.Union[Markup, t.Any]:1100+ def as_const(self, eval_ctx: EvalContext | None = None) -> Markup | t.Any:1101 eval_ctx = get_eval_context(self, eval_ctx)1102 if eval_ctx.volatile:1103 raise Impossible()1104 expr = self.expr.as_const(eval_ctx)96 unmodified linesmodified:src/jinja2/optimizer.py+1 added-1 removed
23 unmodified lines24 return t.cast(nodes.Node, optimizer.visit(node))25 26 27 class Optimizer(NodeTransformer):28- def __init__(self, environment: "t.Optional[Environment]") -> None:28+ def __init__(self, environment: "Environment | None") -> None:29 self.environment = environment30 31 def generic_visit(32 self, node: nodes.Node, *args: t.Any, **kwargs: t.Any16 unmodified linesmodified:src/jinja2/parser.py+29 added-35 removed
52 unmodified lines53 def __init__(54 self,55 environment: "Environment",56 source: str,57- name: t.Optional[str] = None,58- filename: t.Optional[str] = None,59- state: t.Optional[str] = None,57+ name: str | None = None,58+ filename: str | None = None,59+ state: str | None = None,60 ) -> None:61 self.environment = environment62 self.stream = environment._tokenize(source, name, filename, state)63 self.name = name64 self.filename = filename65 self.closed = False66 self.extensions: dict[67- str, t.Callable[[Parser], t.Union[nodes.Node, list[nodes.Node]]]67+ str, t.Callable[[Parser], nodes.Node | list[nodes.Node]]68 ] = {}69 for extension in environment.iter_extensions():70 for tag in extension.tags:71 self.extensions[tag] = extension.parse3 unmodified lines75 76 def fail(77 self,78 msg: str,79- lineno: t.Optional[int] = None,79+ lineno: int | None = None,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 and4 unmodified lines88 raise exc(msg, lineno, self.name, self.filename)89 90 def _fail_ut_eof(91 self,92- name: t.Optional[str],92+ name: str | None,93 end_token_stack: list[tuple[str, ...]],94- lineno: t.Optional[int],94+ lineno: int | None,95 ) -> "te.NoReturn":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(100+ currently_looking: str | None = " or ".join(101 map(repr, map(describe_token_expr, end_token_stack[-1]))102 )103 else:104 currently_looking = None21 unmodified lines126 )127 128 self.fail(" ".join(message), lineno)129 130- def fail_unknown_tag(131- self, name: str, lineno: t.Optional[int] = None132- ) -> "te.NoReturn":130+ def fail_unknown_tag(self, name: str, lineno: int | None = None) -> "te.NoReturn":131 """Called if the parser encounters an unknown tag. Tries to fail132 with a human readable error message that could help to identify133 the problem.134 """135 self._fail_ut_eof(name, self._end_token_stack, lineno)136 137 def fail_eof(138 self,141- end_tokens: t.Optional[tuple[str, ...]] = None,142- lineno: t.Optional[int] = None,139+ end_tokens: tuple[str, ...] | None = None,140+ lineno: int | None = None,141 ) -> "te.NoReturn":142 """Like fail_unknown_tag but for end of template situations."""143 stack = list(self._end_token_stack)144 if end_tokens is not None:145 stack.append(end_tokens)146 self._fail_ut_eof(None, stack, lineno)147 150- def is_tuple_end(self, extra_end_rules: t.Optional[tuple[str, ...]] = None) -> bool:148+ def is_tuple_end(self, extra_end_rules: tuple[str, ...] | None = None) -> bool:149 """Are we at the end of a tuple?"""150 if self.stream.current.type in ("variable_end", "block_end", "rparen"):151 return True152 elif extra_end_rules is not None:153 return self.stream.current.test_any(extra_end_rules) # type: ignore154 return False155 158- def free_identifier(self, lineno: t.Optional[int] = None) -> nodes.InternalName:156+ def free_identifier(self, lineno: int | None = None) -> nodes.InternalName:157 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""158 self._last_identifier += 1159 rv = object.__new__(nodes.InternalName)160 nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)161 return rv162 165- def parse_statement(self) -> t.Union[nodes.Node, list[nodes.Node]]:163+ def parse_statement(self) -> nodes.Node | list[nodes.Node]:164 """Parse a single statement."""165 token = self.stream.current166 if token.type != "name":167 self.fail("tag name expected", token.lineno)49 unmodified lines217 if drop_needle:218 next(self.stream)219 return result220 223- def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:221+ def parse_set(self) -> nodes.Assign | nodes.AssignBlock:222 """Parse an assign statement."""223 lineno = next(self.stream).lineno224 target = self.parse_assign_target(with_namespace=True)225 if self.stream.skip_if("assign"):235 unmodified lines461 def parse_assign_target(462 self,463 with_tuple: bool = True,464 name_only: bool = False,467- extra_end_rules: t.Optional[tuple[str, ...]] = None,465+ extra_end_rules: tuple[str, ...] | None = None,466 with_namespace: bool = False,469- ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...467+ ) -> nodes.NSRef | nodes.Name | nodes.Tuple: ...468 469 def parse_assign_target(470 self,471 with_tuple: bool = True,472 name_only: bool = False,475- extra_end_rules: t.Optional[tuple[str, ...]] = None,473+ extra_end_rules: tuple[str, ...] | None = None,474 with_namespace: bool = False,477- ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:475+ ) -> nodes.NSRef | nodes.Name | nodes.Tuple:476 """Parse an assignment target. As Jinja allows assignments to477 tuples, this function can parse all allowed assignment targets. Per478 default assignments to tuples are parsed, that can be disable however479 by setting `with_tuple` to `False`. If only assignments to names are36 unmodified lines516 517 def parse_condexpr(self) -> nodes.Expr:518 lineno = self.stream.current.lineno519 expr1 = self.parse_or()522- expr3: t.Optional[nodes.Expr]520+ expr3: nodes.Expr | None521 522 while self.stream.skip_if("name:if"):523 expr2 = self.parse_or()524 if self.stream.skip_if("name:else"):156 unmodified lines681 def parse_tuple(682 self,683 simplified: bool = False,684 with_condexpr: bool = True,687- extra_end_rules: t.Optional[tuple[str, ...]] = None,685+ extra_end_rules: tuple[str, ...] | None = None,686 explicit_parentheses: bool = False,687 with_namespace: bool = False,690- ) -> t.Union[nodes.Tuple, nodes.Expr]:688+ ) -> nodes.Tuple | nodes.Expr:689 """Works like `parse_expression` but if multiple expressions are690 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.691 This method could also return a regular expression instead of a tuple692 if no commas where found.108 unmodified lines801 else:802 break803 return node804 807- def parse_subscript(808- self, node: nodes.Expr809- ) -> t.Union[nodes.Getattr, nodes.Getitem]:805+ def parse_subscript(self, node: nodes.Expr) -> nodes.Getattr | nodes.Getitem:806 token = next(self.stream)807 arg: nodes.Expr808 809 if token.type == "dot":22 unmodified lines832 self.fail("expected subscript expression", token.lineno)833 834 def parse_subscribed(self) -> nodes.Expr:835 lineno = self.stream.current.lineno840- args: list[t.Optional[nodes.Expr]]836+ args: list[nodes.Expr | None]837 838 if self.stream.current.type == "colon":839 next(self.stream)840 args = [None]26 unmodified lines867 self,868 ) -> tuple[869 list[nodes.Expr],870 list[nodes.Keyword],875- t.Union[nodes.Expr, None],876- t.Union[nodes.Expr, None],871+ nodes.Expr | None,872+ nodes.Expr | None,873 ]:874 token = self.stream.expect("lparen")875 args = []876 kwargs = []49 unmodified lines926 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()927 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)928 929 def parse_filter(934- self, node: t.Optional[nodes.Expr], start_inline: bool = False935- ) -> t.Optional[nodes.Expr]:930+ self, node: nodes.Expr | None, start_inline: bool = False931+ ) -> nodes.Expr | None:932 while self.stream.current.type == "pipe" or start_inline:933 if not start_inline:934 next(self.stream)935 token = self.stream.expect("name")50 unmodified lines986 if negated:987 node = nodes.Not(node, lineno=token.lineno)988 return node989 994- def subparse(995- self, end_tokens: t.Optional[tuple[str, ...]] = None996- ) -> list[nodes.Node]:990+ def subparse(self, end_tokens: tuple[str, ...] | None = None) -> list[nodes.Node]:991 body: list[nodes.Node] = []992 data_buffer: list[nodes.Node] = []993 add_data = data_buffer.append994 47 unmodified linesmodified:src/jinja2/runtime.py+12 added-12 removed
90 unmodified lines91 92 93 def new_context(94 environment: "Environment",95- template_name: t.Optional[str],95+ template_name: str | None,96 blocks: dict[str, t.Callable[["Context"], t.Iterator[str]]],97- vars: t.Optional[dict[str, t.Any]] = None,97+ vars: dict[str, t.Any] | None = 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,99+ globals: t.MutableMapping[str, t.Any] | None = None,100+ locals: t.Mapping[str, t.Any] | None = None,101 ) -> "Context":102 """Internal helper for context creation."""103 if vars is None:104 vars = {}60 unmodified lines165 def __init__(166 self,167 environment: "Environment",168 parent: dict[str, t.Any],169- name: t.Optional[str],169+ name: str | None,170 blocks: dict[str, t.Callable[["Context"], t.Iterator[str]]],171- globals: t.Optional[t.MutableMapping[str, t.Any]] = None,171+ globals: t.MutableMapping[str, t.Any] | None = None,172 ):173 self.parent = parent174 self.vars: dict[str, t.Any] = {}175 self.environment: Environment = environment130 unmodified lines306 "value was undefined because a callable raised a"307 " StopIteration exception"308 )309 310- def derived(self, locals: t.Optional[dict[str, t.Any]] = None) -> "Context":310+ def derived(self, locals: dict[str, t.Any] | None = 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 """83 unmodified lines398 399 #: Current iteration of the loop, starting at 0.400 index0 = -1401 402- _length: t.Optional[int] = None402+ _length: int | None = None403 _after: t.Any = missing404 _current: t.Any = missing405 _before: t.Any = missing406 _last_changed_value: t.Any = missing185 unmodified lines592 _iterator: t.AsyncIterator[t.Any] # type: ignore593 594 @staticmethod595 def _to_iterator( # type: ignore596- iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]],596+ iterable: t.Iterable[V] | t.AsyncIterable[V],597 ) -> t.AsyncIterator[V]:598 return auto_aiter(iterable)599 600 @property69 unmodified lines670 arguments: list[str],671 catch_kwargs: bool,672 catch_varargs: bool,673 caller: bool,674- default_autoescape: t.Optional[bool] = None,674+ default_autoescape: bool | None = None,675 ):676 self._environment = environment677 self._func = func678 self._argument_count = len(arguments)137 unmodified lines816 )817 818 def __init__(819 self,820- hint: t.Optional[str] = None,820+ hint: str | None = None,821 obj: t.Any = missing,822- name: t.Optional[str] = None,822+ name: str | None = None,823 exc: type[TemplateRuntimeError] = UndefinedError,824 ) -> None:825 self._undefined_hint = hint826 self._undefined_obj = obj236 unmodified linesmodified:src/jinja2/sandbox.py+3 added-5 removed
283 unmodified lines284 .. versionadded:: 2.6285 """286 return self.unop_table[operator](arg)287 288- def getitem(289- self, obj: t.Any, argument: t.Union[str, t.Any]290- ) -> t.Union[t.Any, Undefined]:288+ def getitem(self, obj: t.Any, argument: str | t.Any) -> t.Any | Undefined:289 """Subscribe an object from sandboxed code."""290 try:291 return obj[argument]292 except (TypeError, LookupError):15 unmodified lines308 return value309 return self.unsafe_undefined(obj, argument)310 return self.undefined(obj=obj, name=argument)311 314- def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:312+ def getattr(self, obj: t.Any, attribute: str) -> t.Any | Undefined:313 """Subscribe an object from sandboxed code and prefer the314 attribute. The attribute passed *must* be a bytestring.315 """316 try:21 unmodified lines338 obj=obj,339 exc=SecurityError,340 )341 344- def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:342+ def wrap_str_format(self, value: t.Any) -> t.Callable[..., str] | None:343 """If the given value is a ``str.format`` or ``str.format_map`` method,344 return a new function than handles sandboxing. This is done at access345 rather than in :meth:`call`, so that calls made without ``call`` are346 also sandboxed.88 unmodified linesmodified:src/jinja2/utils.py+8 added-8 removed
159 unmodified lines160 if not silent:161 raise162 163 164-def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO[t.Any]]:164+def open_if_exists(filename: str, mode: str = "rb") -> t.IO[t.Any] | None:165 """Returns a file descriptor for the filename if that file exists,166 otherwise ``None``.167 """168 if not os.path.isfile(filename):59 unmodified lines228 229 230 def urlize(231 text: str,232- trim_url_limit: t.Optional[int] = None,233- rel: t.Optional[str] = None,234- target: t.Optional[str] = None,235- extra_schemes: t.Optional[t.Iterable[str]] = None,232+ trim_url_limit: int | None = None,233+ rel: str | None = None,234+ target: str | None = None,235+ extra_schemes: t.Iterable[str] | None = None,236 ) -> str:237 """Convert URLs in text into clickable links.238 239 This may not recognize links in some situations. Usually, a more342 unmodified lines582 enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),583 disabled_extensions: t.Collection[str] = (),584 default_for_string: bool = True,585 default: bool = False,586-) -> t.Callable[[t.Optional[str]], bool]:586+) -> t.Callable[[str | None], bool]:587 """Intelligently sets the initial value of autoescaping based on the588 filename of the template. This is the recommended way to configure589 autoescaping if you do not want to write a custom function yourself.590 29 unmodified lines620 """621 enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)622 disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)623 624- def autoescape(template_name: t.Optional[str]) -> bool:624+ def autoescape(template_name: str | None) -> bool:625 if template_name is None:626 return default_for_string627 template_name = template_name.lower()628 if template_name.endswith(enabled_patterns):5 unmodified lines634 return autoescape635 636 637 def htmlsafe_json_dumps(638- obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any638+ obj: t.Any, dumps: t.Callable[..., str] | None = None, **kwargs: t.Any639 ) -> markupsafe.Markup:640 """Serialize an object to a string of JSON with :func:`json.dumps`,641 then replace HTML-unsafe characters with Unicode escapes and mark642 the result safe with :class:`~markupsafe.Markup`.124 unmodified linesmodified:src/jinja2/visitor.py+1 added-1 removed
23 unmodified lines24 the `get_visitor` function. If no visitor function exists for a node25 (return value `None`) the `generic_visit` visitor is used instead.26 """27 28- def get_visitor(self, node: Node) -> "t.Optional[VisitCallable]":28+ def get_visitor(self, node: Node) -> "VisitCallable | None":29 """Return the visitor function for this node or `None` if no visitor30 exists for this node. In that case the generic visit function is31 used instead.32 """60 unmodified lines