Skip to content
Myr

Merge pull request #1247 from MLH-Fellowship/type-hints

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Setup mypy

authored by David Lord · committed by GitHub · parents 64ade52, 50ae5b6 · Browse files · 15 files+72 added−32 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+72 added−32 removed

  • tests:+6 added−4 removed
  • other:+66 added−28 removed

15 files+72 added−32 removed

modified:.github/workflows/tests.yaml+1 added
modified:src/jinja2/compiler.py+12 added-12 removed
1510 unmodified lines
1511 self.write(")")15121513 return visitor15141515 visit_Add = binop("+")1516 visit_Sub = binop("-")1517 visit_Mul = binop("*")1518 visit_Div = binop("/")1519 visit_FloorDiv = binop("//")1520 visit_Pow = binop("**")1521 visit_Mod = binop("%")1522 visit_And = binop("and", interceptable=False)1523 visit_Or = binop("or", interceptable=False)1524 visit_Pos = uaop("+")1525 visit_Neg = uaop("-")1526 visit_Not = uaop("not ", interceptable=False)1515 visit_Add = binop("+") # type:ignore1516 visit_Sub = binop("-") # type:ignore1517 visit_Mul = binop("*") # type:ignore1518 visit_Div = binop("/") # type:ignore1519 visit_FloorDiv = binop("//") # type:ignore1520 visit_Pow = binop("**") # type:ignore1521 visit_Mod = binop("%") # type:ignore1522 visit_And = binop("and", interceptable=False) # type:ignore1523 visit_Or = binop("or", interceptable=False) # type:ignore1524 visit_Pos = uaop("+") # type:ignore1525 visit_Neg = uaop("-") # type:ignore1526 visit_Not = uaop("not ", interceptable=False) # type:ignore1527 del binop, uaop15281529 @optimizeconst1530 def visit_Concat(self, node, frame):
224 unmodified lines
modified:src/jinja2/environment.py+4 added-1 removed
4 unmodified lines
5import sys6import weakref7from functools import partial8from functools import reduce9from typing import Any1011from markupsafe import Markup1213from . import nodes
257 unmodified lines
271 #: the class that is used for code generation. See272 #: :class:`~jinja2.compiler.CodeGenerator` for more information.273 code_generator_class = CodeGenerator274274 #: the context class thatis used for templates. See275 #: the context class that is used for templates. See276 #: :class:`~jinja2.runtime.Context` for more information.277 context_class = Context278279 template_class = Any280281 def __init__(282 self,283 block_start_string=BLOCK_START_STRING,284 block_end_string=BLOCK_END_STRING,
1050 unmodified lines
modified:src/jinja2/ext.py+2 added-1 removed
1"""Extension API for adding custom tags and behavior."""2import pprint3import re4from sys import version_info5from typing import Set67from markupsafe import Markup89from . import nodes
51 unmodified lines
61 name as includes the name of the extension (fragment cache).62 """6364 #: if this extension parses this is the list of tags it's listening to.64 tags = set()65 tags: Set[str] = set()6667 #: the priority of that extension. This is especially useful for68 #: extensions that preprocess values. A lower value means higher69 #: priority.
632 unmodified lines
modified:src/jinja2/filters.py+2 added-2 removed
920 unmodified lines
921# we do not want to accidentally expose an auto generated repr in case922# people start to print this out in comments or something similar for923# debugging.924_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])925_GroupTuple.__repr__ = tuple.__repr__926_GroupTuple.__str__ = tuple.__str__925_GroupTuple.__repr__ = tuple.__repr__ # type: ignore926_GroupTuple.__str__ = tuple.__str__ # type: ignore927928929@environmentfilter930def do_groupby(environment, value, attribute):
431 unmodified lines
modified:src/jinja2/nativetypes.py+2 added
1from ast import literal_eval2from itertools import chain3from itertools import islice4from typing import Any56from . import nodes7from .compiler import CodeGenerator8from .compiler import has_safe_repr
61 unmodified lines
70class NativeEnvironment(Environment):71 """An environment that renders templates to native Python types."""7273 code_generator_class = NativeCodeGenerator74 template_class: Any757677class NativeTemplate(Template):78 environment_class = NativeEnvironment
17 unmodified lines
modified:src/jinja2/nodes.py+6 added-4 removed
2 unmodified lines
3to normalize nodes.4"""5import operator6from collections import deque7from typing import Any8from typing import Tuple as TupleType910from markupsafe import Markup1112_binop_to_func = {
93 unmodified lines
106 The `environment` attribute is set at the end of the parsing process for107 all nodes automatically.108 """109108 fields = ()110 fields: TupleType = ()111 attributes = ("lineno", "environment")112 abstract = True113114 def __init__(self, *fields, **attributes):
300 unmodified lines
415class BinExpr(Expr):416 """Baseclass for all binary expressions."""417418 fields = ("left", "right")417 operator = None419 operator: Any = None420 abstract = True421422 def as_const(self, eval_ctx=None):423 eval_ctx = get_eval_context(self, eval_ctx)
13 unmodified lines
437class UnaryExpr(Expr):438 """Baseclass for all unary expressions."""439440 fields = ("node",)439 operator = None441 operator: Any = None442 abstract = True443444 def as_const(self, eval_ctx=None):445 eval_ctx = get_eval_context(self, eval_ctx)
603 unmodified lines
1049def _failing_new(*args, **kwargs):1050 raise TypeError("can't create custom node types")105110521051NodeType.__new__ = staticmethod(_failing_new)1053NodeType.__new__ = staticmethod(_failing_new) # type: ignore1054del _failing_new
modified:src/jinja2/runtime.py+4 added-3 removed
306 unmodified lines
307 context.eval_ctx = self.eval_ctx308 context.blocks.update((k, list(v)) for k, v in self.blocks.items())309 return context310311 # ignore: true312 def _all(meth): # noqa: B902313 def proxy(self):314 return getattr(self.get_all(), meth)()315316 proxy.__doc__ = getattr(dict, meth).__doc__317 proxy.__name__ = meth318 return proxy319319 keys = _all("keys")320 values = _all("values")321 items = _all("items")320 keys = _all("keys") # type:ignore321 values = _all("values") # type:ignore322 items = _all("items") # type:ignore323 del _all324325 def __contains__(self, name):326 return name in self.vars or name in self.parent
594 unmodified lines
modified:src/jinja2/sandbox.py+7 added-5 removed
1 unmodified line
2Useful when the template itself comes from an untrusted source.3"""4import operator5import types6from _string import formatter_field_name_split6from _string import formatter_field_name_split # type: ignore7from collections import abc8from collections import deque9from string import Formatter10from typing import FrozenSet11from typing import Set1213from markupsafe import EscapeFormatter14from markupsafe import Markup15
3 unmodified lines
19#: maximum number of items a range may produce20MAX_RANGE = 1000002122#: Unsafe function attributes.21UNSAFE_FUNCTION_ATTRIBUTES = set()23UNSAFE_FUNCTION_ATTRIBUTES: Set = set()2425#: Unsafe method attributes. Function attributes are unsafe for methods too.24UNSAFE_METHOD_ATTRIBUTES = set()26UNSAFE_METHOD_ATTRIBUTES: Set = set()2728#: unsafe generator attributes.29UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}30
190 unmodified lines
221 #: operator call, so make sure only to intercept the ones you are222 #: interested in.223 #:224 #: .. versionadded:: 2.6223 intercepted_binops = frozenset()225 intercepted_binops: FrozenSet = frozenset()226227 #: a set of unary operators that should be intercepted. Each operator228 #: that is added to this set (empty by default) is delegated to the229 #: :meth:`call_unop` method that will perform the operator. The default
6 unmodified lines
236 #: operator call, so make sure only to intercept the ones you are237 #: interested in.238 #:239 #: .. versionadded:: 2.6238 intercepted_unops = frozenset()240 intercepted_unops: FrozenSet = frozenset()241242 def intercept_unop(self, operator):243 """Called during template compilation with the name of a unary244 operator to check if it should be intercepted at runtime. If this
177 unmodified lines
modified:tests/test_api.py+1 added-1 removed
271 unmodified lines
272 # property that resolves the wrapped function. If that wrapped273 # function raises an AttributeError, printing the repr of the274 # object in the undefined message would cause a RecursionError.275 class Error:276 @property276 @property # type: ignore277 def __class__(self):278 raise AttributeError()279280 u = Undefined(obj=Error(), name="hello")
153 unmodified lines
modified:tests/test_asyncfilters.py+1 added-1 removed
140 unmodified lines
141 tmpl = env_async.from_string('{{ items()|select|join("|") }}')142 assert tmpl.render(items=items) == "1|2|3|4|5"143144145def make_users():145def make_users(): # type: ignore146 User = namedtuple("User", "name,is_active")147 return [148 User("john", True),149 User("jane", True),
75 unmodified lines
modified:tests/test_ext.py+4 added-2 removed
88 unmodified lines
8990newstyle_i18n_env = Environment(91 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]92)93newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)93newstyle_i18n_env.install_gettext_callables( # type: ignore94 gettext, ngettext, newstyle=True95)969798class ExampleExtension(Extension):99 tags = {"test"}
22 unmodified lines
122 )123124125class DerivedExampleExtension(ExampleExtension):124 context_reference_node_cls = nodes.DerivedContextReference126 context_reference_node_cls = nodes.DerivedContextReference # type: ignore127128129class PreprocessorExtension(Extension):130 def preprocess(self, source, name, filename=None):
512 unmodified lines
modified:.gitignore+1 added
16 unmodified lines
17.coverage.*18htmlcov19.pytest_cache/20/.vscode/21.mypy_cache
modified:setup.cfg+19 added
75 unmodified lines
76max-line-length = 8077per-file-ignores =78 # __init__ module exports names79 src/jinja2/__init__.py: F4018081[mypy]82allow_redefinition = True83disallow_subclassing_any = True84# disallow_untyped_defs = True85strict_equality = True86strict_optional = False87warn_redundant_casts = True88warn_unused_configs = True89warn_unused_ignores = True9091[mypy-_pytest.*]92ignore_missing_imports = True9394[mypy-pytest.*]95ignore_missing_imports = True9697[mypy-requests_unixsocket.*]98ignore_missing_imports = True
modified:tox.ini+6 added
1 unmodified line
2envlist =3 py{38,37,36,py3}4 style5 docs6 mypy7skip_missing_interpreters = true89[testenv]10deps = -r requirements/tests.txt
6 unmodified lines
1718[testenv:docs]19deps = -r requirements/docs.txt20commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html2122[testenv:mypy]23deps = mypy24commands =25 mypy src/jinja2 tests