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
Provenance
- Commit
27c6575- Tree
421392c- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
64ade52- Parent 2
50ae5b6
15 files changed+72 added−32 removed
modified:.github/workflows/tests.yaml+1 added
20 unmodified lines21222324252627282924 unmodified lines20 unmodified lines - {name: '3.6', python: '3.6', os: ubuntu-latest, tox: py36} - {name: 'PyPy', python: pypy3, os: ubuntu-latest, tox: pypy3} - {name: Style, python: '3.8', os: ubuntu-latest, tox: style} - {name: Docs, python: '3.8', os: ubuntu-latest, tox: docs} - {name: Typing, python: '3.8', os: ubuntu-latest, tox: mypy} - {name: Windows, python: '3.8', os: windows-latest, tox: py38} - {name: Mac, python: '3.8', os: macos-latest, tox: py38} steps: - uses: actions/checkout@v224 unmodified linesmodified:src/jinja2/compiler.py+12 added-12 removed
1510 unmodified lines1511 self.write(")")1512 1513 return visitor1514 1515- 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, uaop1528 1529 @optimizeconst1530 def visit_Concat(self, node, frame):224 unmodified linesmodified:src/jinja2/environment.py+4 added-1 removed
4 unmodified lines5 import sys6 import weakref7 from functools import partial8 from functools import reduce9+from typing import Any10 11 from markupsafe import Markup12 13 from . import nodes257 unmodified lines271 #: the class that is used for code generation. See272 #: :class:`~jinja2.compiler.CodeGenerator` for more information.273 code_generator_class = CodeGenerator274 274- #: 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 = Context278 279+ template_class = Any280+281 def __init__(282 self,283 block_start_string=BLOCK_START_STRING,284 block_end_string=BLOCK_END_STRING,1050 unmodified linesmodified:src/jinja2/ext.py+2 added-1 removed
1 """Extension API for adding custom tags and behavior."""2 import pprint3 import re4 from sys import version_info5+from typing import Set6 7 from markupsafe import Markup8 9 from . import nodes51 unmodified lines61 name as includes the name of the extension (fragment cache).62 """63 64 #: if this extension parses this is the list of tags it's listening to.64- tags = set()65+ tags: Set[str] = set()66 67 #: the priority of that extension. This is especially useful for68 #: extensions that preprocess values. A lower value means higher69 #: priority.632 unmodified linesmodified:src/jinja2/filters.py+2 added-2 removed
920 unmodified lines921 # 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: ignore927 928 929 @environmentfilter930 def do_groupby(environment, value, attribute):431 unmodified linesmodified:src/jinja2/nativetypes.py+2 added
1 from ast import literal_eval2 from itertools import chain3 from itertools import islice4+from typing import Any5 6 from . import nodes7 from .compiler import CodeGenerator8 from .compiler import has_safe_repr61 unmodified lines70 class NativeEnvironment(Environment):71 """An environment that renders templates to native Python types."""72 73 code_generator_class = NativeCodeGenerator74+ template_class: Any75 76 77 class NativeTemplate(Template):78 environment_class = NativeEnvironment17 unmodified linesmodified:src/jinja2/nodes.py+6 added-4 removed
2 unmodified lines3 to normalize nodes.4 """5 import operator6 from collections import deque7+from typing import Any8+from typing import Tuple as TupleType9 10 from markupsafe import Markup11 12 _binop_to_func = {93 unmodified lines106 The `environment` attribute is set at the end of the parsing process for107 all nodes automatically.108 """109 108- fields = ()110+ fields: TupleType = ()111 attributes = ("lineno", "environment")112 abstract = True113 114 def __init__(self, *fields, **attributes):300 unmodified lines415 class BinExpr(Expr):416 """Baseclass for all binary expressions."""417 418 fields = ("left", "right")417- operator = None419+ operator: Any = None420 abstract = True421 422 def as_const(self, eval_ctx=None):423 eval_ctx = get_eval_context(self, eval_ctx)13 unmodified lines437 class UnaryExpr(Expr):438 """Baseclass for all unary expressions."""439 440 fields = ("node",)439- operator = None441+ operator: Any = None442 abstract = True443 444 def as_const(self, eval_ctx=None):445 eval_ctx = get_eval_context(self, eval_ctx)603 unmodified lines1049 def _failing_new(*args, **kwargs):1050 raise TypeError("can't create custom node types")1051 1052 1051-NodeType.__new__ = staticmethod(_failing_new)1053+NodeType.__new__ = staticmethod(_failing_new) # type: ignore1054 del _failing_newmodified:src/jinja2/runtime.py+4 added-3 removed
306 unmodified lines307 context.eval_ctx = self.eval_ctx308 context.blocks.update((k, list(v)) for k, v in self.blocks.items())309 return context310 311+ # ignore: true312 def _all(meth): # noqa: B902313 def proxy(self):314 return getattr(self.get_all(), meth)()315 316 proxy.__doc__ = getattr(dict, meth).__doc__317 proxy.__name__ = meth318 return proxy319 319- 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 _all324 325 def __contains__(self, name):326 return name in self.vars or name in self.parent594 unmodified linesmodified:src/jinja2/sandbox.py+7 added-5 removed
1 unmodified line2 Useful when the template itself comes from an untrusted source.3 """4 import operator5 import types6-from _string import formatter_field_name_split6+from _string import formatter_field_name_split # type: ignore7 from collections import abc8 from collections import deque9 from string import Formatter10+from typing import FrozenSet11+from typing import Set12 13 from markupsafe import EscapeFormatter14 from markupsafe import Markup15 3 unmodified lines19 #: maximum number of items a range may produce20 MAX_RANGE = 10000021 22 #: Unsafe function attributes.21-UNSAFE_FUNCTION_ATTRIBUTES = set()23+UNSAFE_FUNCTION_ATTRIBUTES: Set = set()24 25 #: Unsafe method attributes. Function attributes are unsafe for methods too.24-UNSAFE_METHOD_ATTRIBUTES = set()26+UNSAFE_METHOD_ATTRIBUTES: Set = set()27 28 #: unsafe generator attributes.29 UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}30 190 unmodified lines221 #: 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()226 227 #: a set of unary operators that should be intercepted. Each operator228 #: that is added to this set (empty by default) is delegated to the229 #: :meth:`call_unop` method that will perform the operator. The default6 unmodified lines236 #: operator call, so make sure only to intercept the ones you are237 #: interested in.238 #:239 #: .. versionadded:: 2.6238- intercepted_unops = frozenset()240+ intercepted_unops: FrozenSet = frozenset()241 242 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 this177 unmodified linesmodified:tests/test_api.py+1 added-1 removed
271 unmodified lines272 # 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()279 280 u = Undefined(obj=Error(), name="hello")153 unmodified linesmodified:tests/test_asyncfilters.py+1 added-1 removed
140 unmodified lines141 tmpl = env_async.from_string('{{ items()|select|join("|") }}')142 assert tmpl.render(items=items) == "1|2|3|4|5"143 144 145-def make_users():145+def make_users(): # type: ignore146 User = namedtuple("User", "name,is_active")147 return [148 User("john", True),149 User("jane", True),75 unmodified linesmodified:tests/test_ext.py+4 added-2 removed
88 unmodified lines89 90 newstyle_i18n_env = Environment(91 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]92 )93-newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)93+newstyle_i18n_env.install_gettext_callables( # type: ignore94+ gettext, ngettext, newstyle=True95+)96 97 98 class ExampleExtension(Extension):99 tags = {"test"}22 unmodified lines122 )123 124 125 class DerivedExampleExtension(ExampleExtension):124- context_reference_node_cls = nodes.DerivedContextReference126+ context_reference_node_cls = nodes.DerivedContextReference # type: ignore127 128 129 class PreprocessorExtension(Extension):130 def preprocess(self, source, name, filename=None):512 unmodified linesmodified:.gitignore+1 added
16 unmodified lines17 .coverage.*18 htmlcov19 .pytest_cache/20 /.vscode/21+.mypy_cachemodified:setup.cfg+19 added
75 unmodified lines76 max-line-length = 8077 per-file-ignores =78 # __init__ module exports names79 src/jinja2/__init__.py: F40180+81+[mypy]82+allow_redefinition = True83+disallow_subclassing_any = True84+# disallow_untyped_defs = True85+strict_equality = True86+strict_optional = False87+warn_redundant_casts = True88+warn_unused_configs = True89+warn_unused_ignores = True90+91+[mypy-_pytest.*]92+ignore_missing_imports = True93+94+[mypy-pytest.*]95+ignore_missing_imports = True96+97+[mypy-requests_unixsocket.*]98+ignore_missing_imports = Truemodified:tox.ini+6 added
1 unmodified line2 envlist =3 py{38,37,36,py3}4 style5 docs6+ mypy7 skip_missing_interpreters = true8 9 [testenv]10 deps = -r requirements/tests.txt6 unmodified lines17 18 [testenv:docs]19 deps = -r requirements/docs.txt20 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html21+22+[testenv:mypy]23+deps = mypy24+commands =25+ mypy src/jinja2 tests