Add type to template function (#82564)

This commit is contained in:
epenet 2022-11-23 21:50:45 +01:00 committed by GitHub
parent f43f0c4bcc
commit d7f0b904d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,7 +20,7 @@ import statistics
from struct import error as StructError, pack, unpack_from from struct import error as StructError, pack, unpack_from
import sys import sys
from types import CodeType from types import CodeType
from typing import Any, NoReturn, TypeVar, cast, overload from typing import Any, Literal, NoReturn, TypeVar, cast, overload
from urllib.parse import urlencode as urllib_urlencode from urllib.parse import urlencode as urllib_urlencode
import weakref import weakref
@ -368,7 +368,7 @@ class Template:
return return
try: try:
self._compiled_code = self._env.compile(self.template) # type: ignore[no-untyped-call] self._compiled_code = self._env.compile(self.template)
except jinja2.TemplateError as err: except jinja2.TemplateError as err:
raise TemplateError(err) from err raise TemplateError(err) from err
@ -2183,7 +2183,36 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
return super().is_safe_attribute(obj, attr, value) return super().is_safe_attribute(obj, attr, value)
def compile(self, source, name=None, filename=None, raw=False, defer_init=False): @overload
def compile( # type: ignore[misc]
self,
source: str | jinja2.nodes.Template,
name: str | None = None,
filename: str | None = None,
raw: Literal[False] = False,
defer_init: bool = False,
) -> CodeType:
...
@overload
def compile(
self,
source: str | jinja2.nodes.Template,
name: str | None = None,
filename: str | None = None,
raw: Literal[True] = ...,
defer_init: bool = False,
) -> str:
...
def compile(
self,
source: str | jinja2.nodes.Template,
name: str | None = None,
filename: str | None = None,
raw: bool = False,
defer_init: bool = False,
) -> CodeType | str:
"""Compile the template.""" """Compile the template."""
if ( if (
name is not None name is not None
@ -2194,8 +2223,15 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
# If there are any non-default keywords args, we do # If there are any non-default keywords args, we do
# not cache. In prodution we currently do not have # not cache. In prodution we currently do not have
# any instance of this. # any instance of this.
return super().compile(source, name, filename, raw, defer_init) return super().compile( # type: ignore[no-any-return,call-overload]
source,
name,
filename,
raw,
defer_init,
)
cached: CodeType | str | None
if (cached := self.template_cache.get(source)) is None: if (cached := self.template_cache.get(source)) is None:
cached = self.template_cache[source] = super().compile(source) cached = self.template_cache[source] = super().compile(source)