Skip to content

Commit

Permalink
satisfy formatter, linter, and strict mypy
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism committed Apr 23, 2024
1 parent 20477c6 commit 0ee5eb4
Show file tree
Hide file tree
Showing 21 changed files with 151 additions and 113 deletions.
1 change: 1 addition & 0 deletions src/jinja2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
non-XML syntax that supports inline expressions and an optional
sandboxed environment.
"""

from .bccache import BytecodeCache as BytecodeCache
from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache
from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache
Expand Down
2 changes: 1 addition & 1 deletion src/jinja2/async_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def wrapper(*args, **kwargs): # type: ignore
if need_eval_context:
wrapper = pass_eval_context(wrapper)

wrapper.jinja_async_variant = True
wrapper.jinja_async_variant = True # type: ignore[attr-defined]
return wrapper

return decorator
Expand Down
10 changes: 6 additions & 4 deletions src/jinja2/bccache.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Situations where this is useful are often forking web applications that
are initialized on the first request.
"""

import errno
import fnmatch
import marshal
Expand All @@ -20,14 +21,15 @@

if t.TYPE_CHECKING:
import typing_extensions as te

from .environment import Environment

class _MemcachedClient(te.Protocol):
def get(self, key: str) -> bytes:
...
def get(self, key: str) -> bytes: ...

def set(self, key: str, value: bytes, timeout: t.Optional[int] = None) -> None:
...
def set(
self, key: str, value: bytes, timeout: t.Optional[int] = None
) -> None: ...


bc_version = 5
Expand Down
24 changes: 14 additions & 10 deletions src/jinja2/compiler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Compiles nodes from the parser into Python code."""

import typing as t
from contextlib import contextmanager
from functools import update_wrapper
Expand All @@ -24,6 +25,7 @@

if t.TYPE_CHECKING:
import typing_extensions as te

from .environment import Environment

F = t.TypeVar("F", bound=t.Callable[..., t.Any])
Expand Down Expand Up @@ -60,8 +62,7 @@ def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"]
@optimizeconst
def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:
if (
self.environment.sandboxed
and op in self.environment.intercepted_binops # type: ignore
self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore
):
self.write(f"environment.call_binop(context, {op!r}, ")
self.visit(node.left, frame)
Expand All @@ -84,8 +85,7 @@ def _make_unop(
@optimizeconst
def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:
if (
self.environment.sandboxed
and op in self.environment.intercepted_unops # type: ignore
self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore
):
self.write(f"environment.call_unop(context, {op!r}, ")
self.visit(node.node, frame)
Expand Down Expand Up @@ -133,7 +133,7 @@ def has_safe_repr(value: t.Any) -> bool:
if type(value) in {tuple, list, set, frozenset}:
return all(has_safe_repr(v) for v in value)

if type(value) is dict:
if type(value) is dict: # noqa E721
return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())

return False
Expand Down Expand Up @@ -551,10 +551,13 @@ def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None:
for node in nodes:
visitor.visit(node)

for id_map, names, dependency in (self.filters, visitor.filters, "filters"), (
self.tests,
visitor.tests,
"tests",
for id_map, names, dependency in (
(self.filters, visitor.filters, "filters"),
(
self.tests,
visitor.tests,
"tests",
),
):
for name in sorted(names):
if name not in id_map:
Expand Down Expand Up @@ -829,7 +832,8 @@ def visit_Template(
assert frame is None, "no root frame allowed"
eval_ctx = EvalContext(self.environment, self.name)

from .runtime import exported, async_exported
from .runtime import async_exported
from .runtime import exported

if self.environment.is_async:
exported_names = sorted(exported + async_exported)
Expand Down
48 changes: 28 additions & 20 deletions src/jinja2/environment.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Classes for managing templates and their runtime and compile time
options.
"""

import os
import typing
import typing as t
Expand All @@ -20,10 +21,10 @@
from .defaults import BLOCK_START_STRING
from .defaults import COMMENT_END_STRING
from .defaults import COMMENT_START_STRING
from .defaults import DEFAULT_FILTERS
from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]
from .defaults import DEFAULT_NAMESPACE
from .defaults import DEFAULT_POLICIES
from .defaults import DEFAULT_TESTS
from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]
from .defaults import KEEP_TRAILING_NEWLINE
from .defaults import LINE_COMMENT_PREFIX
from .defaults import LINE_STATEMENT_PREFIX
Expand Down Expand Up @@ -55,6 +56,7 @@

if t.TYPE_CHECKING:
import typing_extensions as te

from .bccache import BytecodeCache
from .ext import Extension
from .loaders import BaseLoader
Expand All @@ -79,7 +81,7 @@ def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_b

def create_cache(
size: int,
) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:
"""Return the cache class for the given size."""
if size == 0:
return None
Expand All @@ -91,13 +93,13 @@ def create_cache(


def copy_cache(
cache: t.Optional[t.MutableMapping],
) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:
cache: t.Optional[t.MutableMapping[t.Any, t.Any]],
) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:
"""Create an empty copy of the given cache."""
if cache is None:
return None

if type(cache) is dict:
if type(cache) is dict: # noqa E721
return {}

return LRUCache(cache.capacity) # type: ignore
Expand Down Expand Up @@ -670,7 +672,7 @@ def _tokenize(
stream = ext.filter_stream(stream) # type: ignore

if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename) # type: ignore
stream = TokenStream(stream, name, filename)

return stream

Expand Down Expand Up @@ -711,8 +713,7 @@ def compile( # type: ignore
filename: t.Optional[str] = None,
raw: "te.Literal[False]" = False,
defer_init: bool = False,
) -> CodeType:
...
) -> CodeType: ...

@typing.overload
def compile(
Expand All @@ -722,8 +723,7 @@ def compile(
filename: t.Optional[str] = None,
raw: "te.Literal[True]" = ...,
defer_init: bool = False,
) -> str:
...
) -> str: ...

@internalcode
def compile(
Expand Down Expand Up @@ -814,7 +814,7 @@ def compile_expression(

def compile_templates(
self,
target: t.Union[str, os.PathLike],
target: t.Union[str, "os.PathLike[str]"],
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
zip: t.Optional[str] = "deflated",
Expand Down Expand Up @@ -858,7 +858,10 @@ def write_file(filename: str, data: str) -> None:
f.write(data.encode("utf8"))

if zip is not None:
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
from zipfile import ZIP_DEFLATED
from zipfile import ZIP_STORED
from zipfile import ZipFile
from zipfile import ZipInfo

zip_file = ZipFile(
target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
Expand Down Expand Up @@ -1417,7 +1420,9 @@ async def make_module_async(
"""
ctx = self.new_context(vars, shared, locals)
return TemplateModule(
self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore
self,
ctx,
[x async for x in self.root_render_func(ctx)], # type: ignore
)

@internalcode
Expand Down Expand Up @@ -1588,7 +1593,7 @@ def __init__(self, gen: t.Iterator[str]) -> None:

def dump(
self,
fp: t.Union[str, t.IO],
fp: t.Union[str, t.IO[bytes]],
encoding: t.Optional[str] = None,
errors: t.Optional[str] = "strict",
) -> None:
Expand All @@ -1606,22 +1611,25 @@ def dump(
if encoding is None:
encoding = "utf-8"

fp = open(fp, "wb")
real_fp: t.IO[bytes] = open(fp, "wb")
close = True
else:
real_fp = fp

try:
if encoding is not None:
iterable = (x.encode(encoding, errors) for x in self) # type: ignore
else:
iterable = self # type: ignore

if hasattr(fp, "writelines"):
fp.writelines(iterable)
if hasattr(real_fp, "writelines"):
real_fp.writelines(iterable)
else:
for item in iterable:
fp.write(item)
real_fp.write(item)
finally:
if close:
fp.close()
real_fp.close()

def disable_buffering(self) -> None:
"""Disable the output buffering."""
Expand Down
19 changes: 10 additions & 9 deletions src/jinja2/ext.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Extension API for adding custom tags and behavior."""

import pprint
import re
import typing as t
Expand All @@ -18,23 +19,23 @@

if t.TYPE_CHECKING:
import typing_extensions as te

from .lexer import Token
from .lexer import TokenStream
from .parser import Parser

class _TranslationsBasic(te.Protocol):
def gettext(self, message: str) -> str:
...
def gettext(self, message: str) -> str: ...

def ngettext(self, singular: str, plural: str, n: int) -> str:
pass

class _TranslationsContext(_TranslationsBasic):
def pgettext(self, context: str, message: str) -> str:
...
def pgettext(self, context: str, message: str) -> str: ...

def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:
...
def npgettext(
self, context: str, singular: str, plural: str, n: int
) -> str: ...

_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]

Expand Down Expand Up @@ -218,7 +219,7 @@ def pgettext(


def _make_new_npgettext(
func: t.Callable[[str, str, str, int], str]
func: t.Callable[[str, str, str, int], str],
) -> t.Callable[..., str]:
@pass_context
def npgettext(
Expand Down Expand Up @@ -294,14 +295,14 @@ def _install_null(self, newstyle: t.Optional[bool] = None) -> None:
pgettext = translations.pgettext
else:

def pgettext(c: str, s: str) -> str:
def pgettext(c: str, s: str) -> str: # type: ignore[misc]
return s

if hasattr(translations, "npgettext"):
npgettext = translations.npgettext
else:

def npgettext(c: str, s: str, p: str, n: int) -> str:
def npgettext(c: str, s: str, p: str, n: int) -> str: # type: ignore[misc]
return s if n == 1 else p

self._install_callables(
Expand Down
Loading

0 comments on commit 0ee5eb4

Please sign in to comment.