address mypy strict findings (#5383)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 5a48a0f, 81b3c85 · Browse files · 28 files·+389 added−283 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+389 added−283 removed
- other:+389 added−283 removed
Provenance
- Commit
bae6ee8- Tree
cea2283- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5a48a0f- Parent 2
81b3c85
28 files changed+389 added−283 removed
modified:requirements/dev.txt+29 added-30 removed
2 unmodified lines3 # by the following command:4 #5 # pip-compile dev.in6 #7-alabaster==0.7.137+alabaster==0.7.168 # via sphinx9 asgiref==3.7.210- # via -r tests.in11-babel==2.13.110+ # via11+ # -r tests.in12+ # -r typing.in13+babel==2.14.014 # via sphinx15 build==1.0.316 # via pip-tools17 cachetools==5.3.218 # via tox17-certifi==2023.7.2219+certifi==2023.11.1720 # via requests21 cffi==1.16.022 # via cryptography23 cfgv==3.4.05 unmodified lines29 click==8.1.730 # via pip-tools31 colorama==0.4.632 # via tox31-cryptography==41.0.533+cryptography==41.0.734 # via -r typing.in33-distlib==0.3.735+distlib==0.3.836 # via virtualenv37 docutils==0.18.138 # via39 # sphinx1 unmodified line41 filelock==3.13.142 # via43 # tox44 # virtualenv43-identify==2.5.3145+identify==2.5.3346 # via pre-commit45-idna==3.447+idna==3.648 # via requests49 imagesize==1.4.150 # via sphinx51 iniconfig==2.0.052 # via pytest51-jinja2==3.1.253+jinja2==3.1.354 # via sphinx55 markupsafe==2.1.356 # via jinja255-mypy==1.6.157+mypy==1.8.058 # via -r typing.in59 mypy-extensions==1.0.060 # via mypy61 nodeenv==1.8.09 unmodified lines71 pallets-sphinx-themes==2.1.172 # via -r docs.in73 pip-tools==7.3.074 # via -r dev.in73-platformdirs==3.11.075+platformdirs==4.1.076 # via77 # tox78 # virtualenv79 pluggy==1.3.080 # via81 # pytest82 # tox81-pre-commit==3.5.083+pre-commit==3.6.084 # via -r dev.in85 pycparser==2.2186 # via cffi85-pygments==2.16.187+pygments==2.17.288 # via89 # sphinx90 # sphinx-tabs91 pyproject-api==1.6.192 # via tox93 pyproject-hooks==1.0.094 # via build93-pytest==7.4.395+pytest==7.4.496 # via -r tests.in97 python-dotenv==1.0.096- # via -r tests.in98+ # via99+ # -r tests.in100+ # -r typing.in101 pyyaml==6.0.1102 # via pre-commit103 requests==2.31.0104 # via sphinx4 unmodified lines109 # -r docs.in110 # pallets-sphinx-themes111 # sphinx-issues112 # sphinx-tabs109- # sphinxcontrib-applehelp110- # sphinxcontrib-devhelp111- # sphinxcontrib-htmlhelp113 # sphinxcontrib-log-cabinet113- # sphinxcontrib-qthelp114- # sphinxcontrib-serializinghtml114 sphinx-issues==3.0.1115 # via -r docs.in116 sphinx-tabs==3.4.4117 # via -r docs.in119-sphinxcontrib-applehelp==1.0.7118+sphinxcontrib-applehelp==1.0.8119 # via sphinx121-sphinxcontrib-devhelp==1.0.5120+sphinxcontrib-devhelp==1.0.6121 # via sphinx123-sphinxcontrib-htmlhelp==2.0.4122+sphinxcontrib-htmlhelp==2.0.5123 # via sphinx124 sphinxcontrib-jsmath==1.0.1125 # via sphinx126 sphinxcontrib-log-cabinet==1.0.1127 # via -r docs.in129-sphinxcontrib-qthelp==1.0.6128+sphinxcontrib-qthelp==1.0.7129 # via sphinx131-sphinxcontrib-serializinghtml==1.1.9130+sphinxcontrib-serializinghtml==1.1.10131 # via sphinx133-tox==4.11.3132+tox==4.12.0133 # via -r dev.in134 types-contextvars==2.4.7.3135 # via -r typing.in136 types-dataclasses==0.6.6137 # via -r typing.in139-typing-extensions==4.8.0138+typing-extensions==4.9.0139 # via mypy141-urllib3==2.0.7140+urllib3==2.1.0141 # via requests143-virtualenv==20.24.6142+virtualenv==20.25.0143 # via144 # pre-commit145 # tox147-wheel==0.41.3146+wheel==0.42.0147 # via pip-tools148 149 # The following packages are considered to be unsafe in a requirements file:150 # pip1 unmodified linemodified:requirements/docs.txt+12 added-17 removed
2 unmodified lines3 # by the following command:4 #5 # pip-compile docs.in6 #7-alabaster==0.7.137+alabaster==0.7.168 # via sphinx9-babel==2.13.19+babel==2.14.010 # via sphinx11-certifi==2023.7.2211+certifi==2023.11.1712 # via requests13 charset-normalizer==3.3.214 # via requests15 docutils==0.18.116 # via17 # sphinx18 # sphinx-tabs19-idna==3.419+idna==3.620 # via requests21 imagesize==1.4.122 # via sphinx23-jinja2==3.1.223+jinja2==3.1.324 # via sphinx25 markupsafe==2.1.326 # via jinja227 packaging==23.21 unmodified line29 # pallets-sphinx-themes30 # sphinx31 pallets-sphinx-themes==2.1.132 # via -r docs.in33-pygments==2.16.133+pygments==2.17.234 # via35 # sphinx36 # sphinx-tabs37 requests==2.31.05 unmodified lines43 # -r docs.in44 # pallets-sphinx-themes45 # sphinx-issues46 # sphinx-tabs47- # sphinxcontrib-applehelp48- # sphinxcontrib-devhelp49- # sphinxcontrib-htmlhelp47 # sphinxcontrib-log-cabinet51- # sphinxcontrib-qthelp52- # sphinxcontrib-serializinghtml48 sphinx-issues==3.0.149 # via -r docs.in50 sphinx-tabs==3.4.451 # via -r docs.in57-sphinxcontrib-applehelp==1.0.752+sphinxcontrib-applehelp==1.0.853 # via sphinx59-sphinxcontrib-devhelp==1.0.554+sphinxcontrib-devhelp==1.0.655 # via sphinx61-sphinxcontrib-htmlhelp==2.0.456+sphinxcontrib-htmlhelp==2.0.557 # via sphinx58 sphinxcontrib-jsmath==1.0.159 # via sphinx60 sphinxcontrib-log-cabinet==1.0.161 # via -r docs.in67-sphinxcontrib-qthelp==1.0.662+sphinxcontrib-qthelp==1.0.763 # via sphinx69-sphinxcontrib-serializinghtml==1.1.964+sphinxcontrib-serializinghtml==1.1.1065 # via sphinx71-urllib3==2.0.766+urllib3==2.1.067 # via requestsmodified:requirements/tests.txt+1 added-1 removed
10 unmodified lines11 packaging==23.212 # via pytest13 pluggy==1.3.014 # via pytest15-pytest==7.4.315+pytest==7.4.416 # via -r tests.in17 python-dotenv==1.0.018 # via -r tests.inmodified:requirements/typing.in+2 added
1 mypy2 types-contextvars3 types-dataclasses4+asgiref5 cryptography6+python-dotenvmodified:requirements/typing.txt+7 added-3 removed
2 unmodified lines3 # by the following command:4 #5 # pip-compile typing.in6 #7+asgiref==3.7.28+ # via -r typing.in9 cffi==1.16.010 # via cryptography9-cryptography==41.0.511+cryptography==41.0.712 # via -r typing.in11-mypy==1.6.113+mypy==1.8.014 # via -r typing.in15 mypy-extensions==1.0.016 # via mypy17 pycparser==2.2118 # via cffi19+python-dotenv==1.0.020+ # via -r typing.in21 types-contextvars==2.4.7.322 # via -r typing.in23 types-dataclasses==0.6.624 # via -r typing.in21-typing-extensions==4.8.025+typing-extensions==4.9.026 # via mypymodified:src/flask/json/__init__.py+1 added-1 removed
165 unmodified lines166 security risk in ancient browsers. See :ref:`security-json`.167 168 .. versionadded:: 0.2169 """170- return current_app.json.response(*args, **kwargs)170+ return current_app.json.response(*args, **kwargs) # type: ignore[return-value]modified:src/flask/json/provider.py+3 added-2 removed
9 unmodified lines10 11 from werkzeug.http import http_date12 13 if t.TYPE_CHECKING: # pragma: no cover14+ from werkzeug.sansio.response import Response15+16 from ..sansio.app import App15- from ..wrappers import Response17 18 19 class JSONProvider:20 """A standard set of JSON operations for an application. Subclasses14 unmodified lines35 .. versionadded:: 2.236 """37 38 def __init__(self, app: App) -> None:38- self._app = weakref.proxy(app)39+ self._app: App = weakref.proxy(app)40 41 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:42 """Serialize data as JSON.43 172 unmodified linesmodified:src/flask/json/tag.py+5 added-5 removed
59 unmodified lines60 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""61 62 __slots__ = ("serializer",)63 64- #: The tag to mark the serialized object with. If ``None``, this tag is64+ #: The tag to mark the serialized object with. If empty, this tag is65 #: only used as an intermediate step during tagging.66- key: str | None = None66+ key: str = ""67 68 def __init__(self, serializer: TaggedJSONSerializer) -> None:69 """Create a tagger for the given serializer."""70 self.serializer = serializer11 unmodified lines82 """Convert the JSON representation back to the correct type. The tag83 will already be removed."""84 raise NotImplementedError85 86- def tag(self, value: t.Any) -> t.Any:86+ def tag(self, value: t.Any) -> dict[str, t.Any]:87 """Convert the value to a valid JSON type and add the tag structure88 around it."""89 return {self.key: self.to_json(value)}90 182 unmodified lines273 """274 tag = tag_class(self)275 key = tag.key276 277- if key is not None:277+ if key:278 if not force and key in self.tags:279 raise KeyError(f"Tag '{key}' is already registered.")280 281 self.tags[key] = tag2 unmodified lines284 self.order.append(tag)285 else:286 self.order.insert(index, tag)287 288- def tag(self, value: t.Any) -> dict[str, t.Any]:288+ def tag(self, value: t.Any) -> t.Any:289 """Convert a value to a tagged representation if necessary."""290 for tag in self.order:291 if tag.check(value):292 return tag.tag(value)34 unmodified linesmodified:src/flask/sansio/app.py+16 added-15 removed
203 unmodified lines204 #: default it's implicitly enabled.205 #:206 #: This attribute can also be configured from the config with the207 #: ``TESTING`` configuration key. Defaults to ``False``.208- testing = ConfigAttribute("TESTING")208+ testing = ConfigAttribute[bool]("TESTING")209 210 #: If a secret key is set, cryptographic components can use this to211 #: sign cookies and other things. Set this to a complex random value212 #: when you want to use the secure cookie for instance.213 #:214 #: This attribute can also be configured from the config with the215 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.216- secret_key = ConfigAttribute("SECRET_KEY")216+ secret_key = ConfigAttribute[t.Union[str, bytes, None]]("SECRET_KEY")217 218 #: A :class:`~datetime.timedelta` which is used to set the expiration219 #: date of a permanent session. The default is 31 days which makes a220 #: permanent session survive for roughly one month.221 #:222 #: This attribute can also be configured from the config with the223 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to224 #: ``timedelta(days=31)``225- permanent_session_lifetime = ConfigAttribute(226- "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta225+ permanent_session_lifetime = ConfigAttribute[timedelta](226+ "PERMANENT_SESSION_LIFETIME",227+ get_converter=_make_timedelta, # type: ignore[arg-type]228 )229 230 json_provider_class: type[JSONProvider] = DefaultJSONProvider231 """A subclass of :class:`~flask.json.provider.JSONProvider`. An15 unmodified lines247 #: .. versionchanged:: 1.1.0248 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow249 #: easier configuration.250 #:250- jinja_options: dict = {}251+ jinja_options: dict[str, t.Any] = {}252 253 #: The rule object to use for URL rules created. This is used by254 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.255 #:19 unmodified lines275 #:276 #: .. versionadded:: 1.0277 test_cli_runner_class: type[FlaskCliRunner] | None = None278 278- default_config: dict279+ default_config: dict[str, t.Any]280 response_class: type[Response]281 282 def __init__(283 self,284 import_name: str,285 static_url_path: str | None = None,285- static_folder: str | os.PathLike | None = "static",286+ static_folder: str | os.PathLike[str] | None = "static",287 static_host: str | None = None,288 host_matching: bool = False,289 subdomain_matching: bool = False,289- template_folder: str | os.PathLike | None = "templates",290+ template_folder: str | os.PathLike[str] | None = "templates",291 instance_path: str | None = None,292 instance_relative_config: bool = False,293 root_path: str | None = None,294 ):89 unmodified lines384 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be385 #: ``'foo'``.386 #:387 #: .. versionadded:: 0.7387- self.extensions: dict = {}388+ self.extensions: dict[str, t.Any] = {}389 390 #: The :class:`~werkzeug.routing.Map` for this instance. You can use391 #: this to change the routing converters after the class was created392 #: but before any routes are connected. Example::43 unmodified lines436 437 .. versionadded:: 0.8438 """439 if self.import_name == "__main__":439- fn = getattr(sys.modules["__main__"], "__file__", None)440+ fn: str | None = getattr(sys.modules["__main__"], "__file__", None)441 if fn is None:442 return "__main__"443 return os.path.splitext(os.path.basename(fn))[0]444 return self.import_name115 unmodified lines560 **Do not enable debug mode when deploying in production.**561 562 Default: ``False``563 """563- return self.config["DEBUG"]564+ return self.config["DEBUG"] # type: ignore[no-any-return]565 566 @debug.setter567 def debug(self, value: bool) -> None:568 self.config["DEBUG"] = value81 unmodified lines650 651 # Add the required methods now.652 methods |= required_methods653 653- rule = self.url_rule_class(rule, methods=methods, **options)654- rule.provide_automatic_options = provide_automatic_options # type: ignore654+ rule_obj = self.url_rule_class(rule, methods=methods, **options)655+ rule_obj.provide_automatic_options = provide_automatic_options # type: ignore[attr-defined]656 656- self.url_map.add(rule)657+ self.url_map.add(rule_obj)658 if view_func is not None:659 old_func = self.view_functions.get(endpoint)660 if old_func is not None and old_func != view_func:661 raise AssertionError(249 unmodified lines911 code=code,912 Response=self.response_class, # type: ignore[arg-type]913 )914 914- def inject_url_defaults(self, endpoint: str, values: dict) -> None:915+ def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None:916 """Injects the URL defaults for the given endpoint directly into917 the values dictionary passed. This is used internally and918 automatically called on URL building.919 49 unmodified linesmodified:src/flask/sansio/blueprints.py+20 added-14 removed
12 unmodified lines13 14 if t.TYPE_CHECKING: # pragma: no cover15 from .app import App16 17-DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18-T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)17+DeferredSetupFunction = t.Callable[["BlueprintSetupState"], None]18+T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any])19 T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20 T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)21 T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)22 T_template_context_processor = t.TypeVar(64 unmodified lines87 def add_url_rule(88 self,89 rule: str,90 endpoint: str | None = None,91- view_func: t.Callable | None = None,91+ view_func: ft.RouteCallable | None = None,92 **options: t.Any,93 ) -> None:94 """A helper method to register a rule (and optionally a view function)95 to the application. The endpoint is automatically prefixed with the78 unmodified lines174 def __init__(175 self,176 name: str,177 import_name: str,178- static_folder: str | os.PathLike | None = None,178+ static_folder: str | os.PathLike[str] | None = None,179 static_url_path: str | None = None,180- template_folder: str | os.PathLike | None = None,180+ template_folder: str | os.PathLike[str] | None = None,181 url_prefix: str | None = None,182 subdomain: str | None = None,183- url_defaults: dict | None = None,183+ url_defaults: dict[str, t.Any] | None = None,184 root_path: str | None = None,185- cli_group: str | None = _sentinel, # type: ignore185+ cli_group: str | None = _sentinel, # type: ignore[assignment]186 ):187 super().__init__(188 import_name=import_name,189 static_folder=static_folder,17 unmodified lines207 url_defaults = {}208 209 self.url_values_defaults = url_defaults210 self.cli_group = cli_group211- self._blueprints: list[tuple[Blueprint, dict]] = []211+ self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []212 213 def _check_setup_finished(self, f_name: str) -> None:214 if self._got_registered_once:215 raise AssertionError(4 unmodified lines220 " the blueprint are done before registering it."221 )222 223 @setupmethod224- def record(self, func: t.Callable) -> None:224+ def record(self, func: DeferredSetupFunction) -> None:225 """Registers a function that is called when the blueprint is226 registered on the application. This function is called with the227 state as argument as returned by the :meth:`make_setup_state`228 method.229 """230 self.deferred_functions.append(func)231 232 @setupmethod233- def record_once(self, func: t.Callable) -> None:233+ def record_once(self, func: DeferredSetupFunction) -> None:234 """Works like :meth:`record` but wraps the function in another235 function that will ensure the function is only called once. If the236 blueprint is registered a second time on the application, the237 function passed is not called.5 unmodified lines243 244 self.record(update_wrapper(wrapper, func))245 246 def make_setup_state(247- self, app: App, options: dict, first_registration: bool = False247+ self, app: App, options: dict[str, t.Any], first_registration: bool = False248 ) -> BlueprintSetupState:249 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`250 object that is later passed to the register callback functions.251 Subclasses can override this to return a subclass of the setup state.17 unmodified lines269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272 273- def register(self, app: App, options: dict) -> None:273+ def register(self, app: App, options: dict[str, t.Any]) -> None:274 """Called by :meth:`Flask.register_blueprint` to register all275 views and callbacks registered on the blueprint with the276 application. Creates a :class:`.BlueprintSetupState` and calls277 each :meth:`record` callback with it.98 unmodified lines376 bp_options["name_prefix"] = name377 blueprint.register(app, bp_options)378 379 def _merge_blueprint_funcs(self, app: App, name: str) -> None:380- def extend(bp_dict, parent_dict):380+ def extend(381+ bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],382+ parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],383+ ) -> None:384 for key, values in bp_dict.items():385 key = name if key is None else f"{name}.{key}"386 parent_dict[key].extend(values)387 212 unmodified lines600 the blueprint. Equivalent to :meth:`.Flask.errorhandler`.601 """602 603 def decorator(f: T_error_handler) -> T_error_handler:601- self.record_once(lambda s: s.app.errorhandler(code)(f))604+ def from_blueprint(state: BlueprintSetupState) -> None:605+ state.app.errorhandler(code)(f)606+607+ self.record_once(from_blueprint)608 return f609 610 return decorator611 21 unmodified linesmodified:src/flask/sansio/scaffold.py+35 added-33 removed
6 unmodified lines7 import typing as t8 from collections import defaultdict9 from functools import update_wrapper10 11+import click12 from jinja2 import FileSystemLoader13 from werkzeug.exceptions import default_exceptions14 from werkzeug.exceptions import HTTPException15 from werkzeug.utils import cached_property6 unmodified lines22 # a singleton sentinel value for parameter defaults23 _sentinel = object()24 25 F = t.TypeVar("F", bound=t.Callable[..., t.Any])25-T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)26+T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any])27 T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)28 T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)29 T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)30 T_template_context_processor = t.TypeVar(8 unmodified lines39 40 def setupmethod(f: F) -> F:41 f_name = f.__name__42 42- def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:43+ def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any:44 self._check_setup_finished(f_name)45 return f(self, *args, **kwargs)46 47 return t.cast(F, update_wrapper(wrapper_func, f))23 unmodified lines71 72 def __init__(73 self,74 import_name: str,74- static_folder: str | os.PathLike | None = None,75+ static_folder: str | os.PathLike[str] | None = None,76 static_url_path: str | None = None,76- template_folder: str | os.PathLike | None = None,77+ template_folder: str | os.PathLike[str] | None = None,78 root_path: str | None = None,79 ):80 #: The name of the package or module that this object belongs81 #: to. Do not change this once it is set by the constructor.17 unmodified lines99 #: The Click command group for registering CLI commands for this100 #: object. The commands are available from the ``flask`` command101 #: once the application has been discovered and blueprints have102 #: been registered.102- self.cli = AppGroup()103+ self.cli: click.Group = AppGroup()104 105 #: A dictionary mapping endpoint names to view functions.106 #:107 #: To register a view function, use the :meth:`route` decorator.108 #:109 #: This data structure is internal. It should not be modified110 #: directly and its format may change at any time.110- self.view_functions: dict[str, t.Callable] = {}111+ self.view_functions: dict[str, ft.RouteCallable] = {}112 113 #: A data structure of registered error handlers, in the format114 #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is115 #: the name of a blueprint the handlers are active for, or36 unmodified lines152 #:153 #: This data structure is internal. It should not be modified154 #: directly and its format may change at any time.155 self.after_request_funcs: dict[155- ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]156+ ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]157 ] = defaultdict(list)158 159 #: A data structure of functions to call at the end of each160 #: request even if an exception is raised, in the format72 unmodified lines233 else:234 return None235 236 @static_folder.setter236- def static_folder(self, value: str | os.PathLike | None) -> None:237+ def static_folder(self, value: str | os.PathLike[str] | None) -> None:238 if value is not None:239 value = os.fspath(value).rstrip(r"\/")240 241 self._static_folder = value45 unmodified lines287 def _method_route(288 self,289 method: str,290 rule: str,290- options: dict,291+ options: dict[str, t.Any],292 ) -> t.Callable[[T_route], T_route]:293 if "methods" in options:294 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")295 404 unmodified lines700 else:701 return exc_class, None702 703 703-def _endpoint_from_view_func(view_func: t.Callable) -> str:704+def _endpoint_from_view_func(view_func: ft.RouteCallable) -> str:705 """Internal helper that returns the default endpoint for a given706 function. This always is the function name.707 """708 assert view_func is not None, "expected view func if endpoint is not provided."8 unmodified lines717 except ValueError:718 return False719 720 720-def _find_package_path(import_name):721+def _find_package_path(import_name: str) -> str:722 """Find the path that contains the package or module."""723 root_mod_name, _, _ = import_name.partition(".")724 725 try:8 unmodified lines734 # - the module name is __main__735 # - we raised `ValueError` due to `root_spec` being `None`736 return os.getcwd()737 738+ if root_spec.submodule_search_locations:737- if root_spec.origin in {"namespace", None}:738- # namespace package739- package_spec = importlib.util.find_spec(import_name)739+ if root_spec.origin is None or root_spec.origin == "namespace":740+ # namespace package741+ package_spec = importlib.util.find_spec(import_name)742 741- if package_spec is not None and package_spec.submodule_search_locations:742- # Pick the path in the namespace that contains the submodule.743- package_path = pathlib.Path(744- os.path.commonpath(package_spec.submodule_search_locations)745- )746- search_location = next(747- location748- for location in root_spec.submodule_search_locations749- if _path_is_relative_to(package_path, location)750- )751- else:752- # Pick the first path.753- search_location = root_spec.submodule_search_locations[0]743+ if package_spec is not None and package_spec.submodule_search_locations:744+ # Pick the path in the namespace that contains the submodule.745+ package_path = pathlib.Path(746+ os.path.commonpath(package_spec.submodule_search_locations)747+ )748+ search_location = next(749+ location750+ for location in root_spec.submodule_search_locations751+ if _path_is_relative_to(package_path, location)752+ )753+ else:754+ # Pick the first path.755+ search_location = root_spec.submodule_search_locations[0]756 755- return os.path.dirname(search_location)756- elif root_spec.submodule_search_locations:757- # package with __init__.py758- return os.path.dirname(os.path.dirname(root_spec.origin))757+ return os.path.dirname(search_location)758+ else:759+ # package with __init__.py760+ return os.path.dirname(os.path.dirname(root_spec.origin))761 else:762 # module761- return os.path.dirname(root_spec.origin)763+ return os.path.dirname(root_spec.origin) # type: ignore[type-var, return-value]764 765 764-def find_package(import_name: str):766+def find_package(import_name: str) -> tuple[str | None, str]:767 """Find the prefix that a package is installed under, and the path768 that it would be imported from.769 770 The prefix is the directory containing the standard directory34 unmodified linesmodified:src/flask/app.py+26 added-19 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import os5 import sys6 import typing as t7 import weakref7-from collections.abc import Iterator as _abc_Iterator8 from datetime import timedelta9 from inspect import iscoroutinefunction10 from itertools import chain11 from types import TracebackType41 unmodified lines53 from .wrappers import Request54 from .wrappers import Response55 56 if t.TYPE_CHECKING: # pragma: no cover57+ from _typeshed.wsgi import StartResponse58+ from _typeshed.wsgi import WSGIEnvironment59+60 from .testing import FlaskClient61 from .testing import FlaskCliRunner62 63 T_shell_context_processor = t.TypeVar(138 unmodified lines202 )203 204 #: The class that is used for request objects. See :class:`~flask.Request`205 #: for more information.203- request_class = Request206+ request_class: type[Request] = Request207 208 #: The class that is used for response objects. See209 #: :class:`~flask.Response` for more information.207- response_class = Response210+ response_class: type[Response] = Response211 212 #: the session interface to use. By default an instance of213 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.214 #:3 unmodified lines218 def __init__(219 self,220 import_name: str,221 static_url_path: str | None = None,219- static_folder: str | os.PathLike | None = "static",222+ static_folder: str | os.PathLike[str] | None = "static",223 static_host: str | None = None,224 host_matching: bool = False,225 subdomain_matching: bool = False,223- template_folder: str | os.PathLike | None = "templates",226+ template_folder: str | os.PathLike[str] | None = "templates",227 instance_path: str | None = None,228 instance_relative_config: bool = False,229 root_path: str | None = None,230 ):53 unmodified lines284 285 if isinstance(value, timedelta):286 return int(value.total_seconds())287 285- return value288+ return value # type: ignore[no-any-return]289 290 def send_static_file(self, filename: str) -> Response:291 """The view function used to serve files from292 :attr:`static_folder`. A route is automatically registered for156 unmodified lines449 or not isinstance(request.routing_exception, RequestRedirect)450 or request.routing_exception.code in {307, 308}451 or request.method in {"GET", "HEAD", "OPTIONS"}452 ):450- raise request.routing_exception # type: ignore453+ raise request.routing_exception # type: ignore[misc]454 455 from .debughelpers import FormDataRoutingRedirect456 457 raise FormDataRoutingRedirect(request)458 456- def update_template_context(self, context: dict) -> None:459+ def update_template_context(self, context: dict[str, t.Any]) -> None:460 """Update the template context with some commonly used variables.461 This injects request, session, config and g into the template462 context as well as everything template context processors want463 to inject. Note that the as of Flask 0.6, the original values19 unmodified lines483 context.update(self.ensure_sync(func)())484 485 context.update(orig_ctx)486 484- def make_shell_context(self) -> dict:487+ def make_shell_context(self) -> dict[str, t.Any]:488 """Returns the shell context for an interactive shell for this489 application. This runs all the registered shell context490 processors.491 234 unmodified lines726 727 handler = self._find_error_handler(e, request.blueprints)728 if handler is None:729 return e727- return self.ensure_sync(handler)(e)730+ return self.ensure_sync(handler)(e) # type: ignore[no-any-return]731 732 def handle_user_exception(733 self, e: Exception734 ) -> HTTPException | ft.ResponseReturnValue:23 unmodified lines758 759 if handler is None:760 raise761 759- return self.ensure_sync(handler)(e)762+ return self.ensure_sync(handler)(e) # type: ignore[no-any-return]763 764 def handle_exception(self, e: Exception) -> Response:765 """Handle an exception that did not have an error handler766 associated with it, or that was raised from an error handler.84 unmodified lines851 ):852 return self.make_default_options_response()853 # otherwise dispatch to the handler for that endpoint854 view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]852- return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)855+ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]856 857 def full_dispatch_request(self) -> Response:858 """Dispatches the request and on top of that performs request859 pre and postprocessing as well as HTTP exception catching and55 unmodified lines915 rv = self.response_class()916 rv.allow.update(methods)917 return rv918 916- def ensure_sync(self, func: t.Callable) -> t.Callable:919+ def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:920 """Ensure that the function is synchronous for WSGI workers.921 Plain ``def`` functions are returned as-is. ``async def``922 functions are wrapped to run and wait for the response.923 6 unmodified lines930 931 return func932 933 def async_to_sync(931- self, func: t.Callable[..., t.Coroutine]934+ self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]935 ) -> t.Callable[..., t.Any]:936 """Return a sync function that will run the coroutine function.937 938 .. code-block:: python229 unmodified lines1168 )1169 1170 # make sure the body is an instance of the response class1171 if not isinstance(rv, self.response_class):1169- if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1172+ if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):1173 # let the response class set the status and headers instead of1174 # waiting to do it manually, so that the class can handle any1175 # special logic1176 rv = self.response_class(65 unmodified lines1242 for before_func in self.before_request_funcs[name]:1243 rv = self.ensure_sync(before_func)()1244 1245 if rv is not None:1243- return rv1246+ return rv # type: ignore[no-any-return]1247 1248 return None1249 1250 def process_response(self, response: Response) -> Response:104 unmodified lines1355 .. versionadded:: 0.91356 """1357 return AppContext(self)1358 1356- def request_context(self, environ: dict) -> RequestContext:1359+ def request_context(self, environ: WSGIEnvironment) -> RequestContext:1360 """Create a :class:`~flask.ctx.RequestContext` representing a1361 WSGI environment. Use a ``with`` block to push the context,1362 which will make :data:`request` point at this request.1363 63 unmodified lines1427 return self.request_context(builder.get_environ())1428 finally:1429 builder.close()1430 1428- def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:1431+ def wsgi_app(1432+ self, environ: WSGIEnvironment, start_response: StartResponse1433+ ) -> cabc.Iterable[bytes]:1434 """The actual WSGI application. This is not implemented in1435 :meth:`__call__` so that middlewares can be applied without1436 losing a reference to the app object. Instead of doing this::1437 39 unmodified lines1477 error = None1478 1479 ctx.pop(error)1480 1476- def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:1481+ def __call__(1482+ self, environ: WSGIEnvironment, start_response: StartResponse1483+ ) -> cabc.Iterable[bytes]:1484 """The WSGI server calls the Flask application object as the1485 WSGI application. This calls :meth:`wsgi_app`, which can be1486 wrapped to apply middleware.1487 """1 unmodified linemodified:src/flask/blueprints.py+1 added-1 removed
37 unmodified lines38 39 if isinstance(value, timedelta):40 return int(value.total_seconds())41 42- return value42+ return value # type: ignore[no-any-return]43 44 def send_static_file(self, filename: str) -> Response:45 """The view function used to serve files from46 :attr:`static_folder`. A route is automatically registered for45 unmodified linesmodified:src/flask/cli.py+88 added-49 removed
1 from __future__ import annotations2 3 import ast4+import collections.abc as cabc5 import importlib.metadata6 import inspect7 import os8 import platform2 unmodified lines11 import traceback12 import typing as t13 from functools import update_wrapper14 from operator import itemgetter15+from types import ModuleType16 17 import click18 from click.core import ParameterSource19 from werkzeug import run_simple4 unmodified lines24 from .helpers import get_debug_flag25 from .helpers import get_load_dotenv26 27 if t.TYPE_CHECKING:28+ import ssl29+30+ from _typeshed.wsgi import StartResponse31+ from _typeshed.wsgi import WSGIApplication32+ from _typeshed.wsgi import WSGIEnvironment33+34 from .app import Flask35 36 37 class NoAppException(click.UsageError):38 """Raised if an application cannot be found or loaded."""39 40 33-def find_best_app(module):41+def find_best_app(module: ModuleType) -> Flask:42 """Given a module instance this tries to find the best possible43 application in the module or raises an exception.44 """45 from . import Flask44 unmodified lines90 " to specify one."91 )92 93 86-def _called_with_wrong_args(f):94+def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool:95 """Check whether calling a function raised a ``TypeError`` because96 the call failed or because something in the factory raised the97 error.98 17 unmodified lines116 # https://docs.python.org/2/library/sys.html#sys.exc_info117 del tb118 119 112-def find_app_by_string(module, app_name):120+def find_app_by_string(module: ModuleType, app_name: str) -> Flask:121 """Check if the given string is a variable name or a function. Call122 a function to get the app instance, or return the variable directly.123 """124 from . import Flask22 unmodified lines147 148 # Parse the positional and keyword arguments as literals.149 try:150 args = [ast.literal_eval(arg) for arg in expr.args]143- kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}151+ kwargs = {152+ kw.arg: ast.literal_eval(kw.value)153+ for kw in expr.keywords154+ if kw.arg is not None155+ }156 except ValueError:157 # literal_eval gives cryptic error messages, show a generic158 # message with the full expression instead.159 raise NoAppException(36 unmodified lines196 f" '{module.__name__}:{app_name}'."197 )198 199 188-def prepare_import(path):200+def prepare_import(path: str) -> str:201 """Given a filename this will try to calculate the python path, add it202 to the search path and return the actual module name that is expected.203 """204 path = os.path.realpath(path)20 unmodified lines225 226 return ".".join(module_name[::-1])227 228 217-def locate_app(module_name, app_name, raise_if_not_found=True):229+@t.overload230+def locate_app(231+ module_name: str, app_name: str | None, raise_if_not_found: t.Literal[True] = True232+) -> Flask:233+ ...234+235+236+@t.overload237+def locate_app(238+ module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...239+) -> Flask | None:240+ ...241+242+243+def locate_app(244+ module_name: str, app_name: str | None, raise_if_not_found: bool = True245+) -> Flask | None:246 try:247 __import__(module_name)248 except ImportError:249 # Reraise the ImportError if it occurred within the imported module.250 # Determine this by checking whether the trace has a depth > 1.223- if sys.exc_info()[2].tb_next:251+ if sys.exc_info()[2].tb_next: # type: ignore[union-attr]252 raise NoAppException(253 f"While importing {module_name!r}, an ImportError was"254 f" raised:\n\n{traceback.format_exc()}"255 ) from None256 elif raise_if_not_found:257 raise NoAppException(f"Could not import {module_name!r}.") from None258 else:231- return259+ return None260 261 module = sys.modules[module_name]262 263 if app_name is None:1 unmodified line265 else:266 return find_app_by_string(module, app_name)267 268 241-def get_version(ctx, param, value):269+def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:270 if not value or ctx.resilient_parsing:271 return272 273 flask_version = importlib.metadata.version("flask")52 unmodified lines326 if self._loaded_app is not None:327 return self._loaded_app328 329 if self.create_app is not None:302- app = self.create_app()330+ app: Flask | None = self.create_app()331 else:332 if self.app_import_path:333 path, name = (334 re.split(r":(?![\\/])", self.app_import_path, maxsplit=1) + [None]4 unmodified lines339 for path in ("wsgi.py", "app.py"):340 import_name = prepare_import(path)341 app = locate_app(import_name, None, raise_if_not_found=False)342 315- if app:343+ if app is not None:344 break345 318- if not app:346+ if app is None:347 raise NoAppException(348 "Could not locate a Flask application. Use the"349 " 'flask --app' option, 'FLASK_APP' environment"350 " variable, or a 'wsgi.py' or 'app.py' file in the"10 unmodified lines361 362 363 pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)364 365+F = t.TypeVar("F", bound=t.Callable[..., t.Any])366 367+338-def with_appcontext(f):368+def with_appcontext(f: F) -> F:369 """Wraps a callback so that it's guaranteed to be executed with the370 script's application context.371 372 Custom commands (and their options) registered under ``app.cli`` or6 unmodified lines379 ``app.cli`` command and parameter callbacks.380 """381 382 @click.pass_context353- def decorator(__ctx, *args, **kwargs):383+ def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any:384 if not current_app:355- app = __ctx.ensure_object(ScriptInfo).load_app()356- __ctx.with_resource(app.app_context())385+ app = ctx.ensure_object(ScriptInfo).load_app()386+ ctx.with_resource(app.app_context())387 358- return __ctx.invoke(f, *args, **kwargs)388+ return ctx.invoke(f, *args, **kwargs)389 360- return update_wrapper(decorator, f)390+ return update_wrapper(decorator, f) # type: ignore[return-value]391 392 393 class AppGroup(click.Group):394 """This works similar to a regular click :class:`~click.Group` but it2 unmodified lines397 398 Not to be confused with :class:`FlaskGroup`.399 """400 371- def command(self, *args, **kwargs):401+ def command( # type: ignore[override]402+ self, *args: t.Any, **kwargs: t.Any403+ ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:404 """This works exactly like the method of the same name on a regular405 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`406 unless it's disabled by passing ``with_appcontext=False``.407 """408 wrap_for_ctx = kwargs.pop("with_appcontext", True)409 378- def decorator(f):410+ def decorator(f: t.Callable[..., t.Any]) -> click.Command:411 if wrap_for_ctx:412 f = with_appcontext(f)381- return click.Group.command(self, *args, **kwargs)(f)413+ return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return]414 415 return decorator416 385- def group(self, *args, **kwargs):417+ def group( # type: ignore[override]418+ self, *args: t.Any, **kwargs: t.Any419+ ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:420 """This works exactly like the method of the same name on a regular421 :class:`click.Group` but it defaults the group class to422 :class:`AppGroup`.423 """424 kwargs.setdefault("cls", AppGroup)391- return click.Group.group(self, *args, **kwargs)425+ return super().group(*args, **kwargs) # type: ignore[no-any-return]426 427 428 def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:429 if value is None:148 unmodified lines578 self.add_command(routes_command)579 580 self._loaded_plugin_commands = False581 548- def _load_plugin_commands(self):582+ def _load_plugin_commands(self) -> None:583 if self._loaded_plugin_commands:584 return585 586 if sys.version_info >= (3, 10):8 unmodified lines595 self.add_command(ep.load(), ep.name)596 597 self._loaded_plugin_commands = True598 565- def get_command(self, ctx, name):599+ def get_command(self, ctx: click.Context, name: str) -> click.Command | None:600 self._load_plugin_commands()601 # Look up built-in and plugin commands, which should be602 # available even if the app fails to load.603 rv = super().get_command(ctx, name)13 unmodified lines617 618 # Push an app context for the loaded app unless it is already619 # active somehow. This makes the context available to parameter620 # and command callbacks without needing @with_appcontext.587- if not current_app or current_app._get_current_object() is not app:621+ if not current_app or current_app._get_current_object() is not app: # type: ignore[attr-defined]622 ctx.with_resource(app.app_context())623 624 return app.cli.get_command(ctx, name)625 592- def list_commands(self, ctx):626+ def list_commands(self, ctx: click.Context) -> list[str]:627 self._load_plugin_commands()628 # Start with the built-in and plugin commands.629 rv = set(super().list_commands(ctx))630 info = ctx.ensure_object(ScriptInfo)47 unmodified lines678 679 return super().parse_args(ctx, args)680 681 648-def _path_is_ancestor(path, other):682+def _path_is_ancestor(path: str, other: str) -> bool:683 """Take ``other`` and remove the length of ``path`` from it. Then join it684 to ``path``. If it is the original value, ``path`` is an ancestor of685 ``other``."""686 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other687 688 655-def load_dotenv(path: str | os.PathLike | None = None) -> bool:689+def load_dotenv(path: str | os.PathLike[str] | None = None) -> bool:690 """Load "dotenv" files in order of precedence to set environment variables.691 692 If an env var is already set it is not overwritten, so earlier files in the693 list are preferred over later files.52 unmodified lines746 747 return loaded # True if at least one file was located and loaded.748 749 716-def show_server_banner(debug, app_import_path):750+def show_server_banner(debug: bool, app_import_path: str | None) -> None:751 """Show extra startup messages the first time the server is run,752 ignoring the reloader.753 """754 if is_running_from_reloader():13 unmodified lines768 """769 770 name = "path"771 738- def __init__(self):772+ def __init__(self) -> None:773 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)774 741- def convert(self, value, param, ctx):775+ def convert(776+ self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None777+ ) -> t.Any:778 try:779 import ssl780 except ImportError:781 raise click.BadParameter(26 unmodified lines808 809 raise810 811 776-def _validate_key(ctx, param, value):812+def _validate_key(ctx: click.Context, param: click.Parameter, value: t.Any) -> t.Any:813 """The ``--key`` option must be specified when ``--cert`` is a file.814 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.815 """816 cert = ctx.params.get("cert")36 unmodified lines853 OS's path separator (``:``, ``;`` on Windows). Each value is854 validated as a :class:`click.Path` type.855 """856 821- def convert(self, value, param, ctx):857+ def convert(858+ self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None859+ ) -> t.Any:860 items = self.split_envvar_value(value)823- super_convert = super().convert824- return [super_convert(item, param, ctx) for item in items]861+ return [super().convert(item, param, ctx) for item in items]862 863 864 @click.command("run", short_help="Run a development server.")865 @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")48 unmodified lines914 ),915 )916 @pass_script_info917 def run_command(881- info,882- host,883- port,884- reload,885- debugger,886- with_threads,887- cert,888- extra_files,889- exclude_patterns,890-):918+ info: ScriptInfo,919+ host: str,920+ port: int,921+ reload: bool,922+ debugger: bool,923+ with_threads: bool,924+ cert: ssl.SSLContext | tuple[str, str | None] | t.Literal["adhoc"] | None,925+ extra_files: list[str] | None,926+ exclude_patterns: list[str] | None,927+) -> None:928 """Run a local development server.929 930 This server is for development purposes only. It does not provide931 the stability, security, or performance of production WSGI servers.1 unmodified line933 The reloader and debugger are enabled by default with the '--debug'934 option.935 """936 try:900- app = info.load_app()937+ app: WSGIApplication = info.load_app()938 except Exception as e:939 if is_running_from_reloader():940 # When reloading, print out the error immediately, but raise941 # it later so the debugger or server can handle it.942 traceback.print_exc()943 err = e944 908- def app(environ, start_response):945+ def app(946+ environ: WSGIEnvironment, start_response: StartResponse947+ ) -> cabc.Iterable[bytes]:948 raise err from None949 950 else:951 # When not reloading, raise the error immediately so the42 unmodified lines994 f"Python {sys.version} on {sys.platform}\n"995 f"App: {current_app.import_name}\n"996 f"Instance: {current_app.instance_path}"997 )959- ctx: dict = {}998+ ctx: dict[str, t.Any] = {}999 1000 # Support the regular Python interpreter startup script if someone1001 # is using it.1002 startup = os.environ.get("PYTHONSTARTUP")107 unmodified linesmodified:src/flask/config.py+35 added-10 removed
6 unmodified lines7 import typing as t8 9 from werkzeug.utils import import_string10 11+if t.TYPE_CHECKING:12+ import typing_extensions as te13 14+ from .sansio.app import App15+16+17+T = t.TypeVar("T")18+19+12-class ConfigAttribute:20+class ConfigAttribute(t.Generic[T]):21 """Makes an attribute forward to the config"""22 15- def __init__(self, name: str, get_converter: t.Callable | None = None) -> None:23+ def __init__(24+ self, name: str, get_converter: t.Callable[[t.Any], T] | None = None25+ ) -> None:26 self.__name__ = name27 self.get_converter = get_converter28 19- def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:29+ @t.overload30+ def __get__(self, obj: None, owner: None) -> te.Self:31+ ...32+33+ @t.overload34+ def __get__(self, obj: App, owner: type[App]) -> T:35+ ...36+37+ def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:38 if obj is None:39 return self40+41 rv = obj.config[self.__name__]42+43 if self.get_converter is not None:44 rv = self.get_converter(rv)25- return rv45 46+ return rv # type: ignore[no-any-return]47+27- def __set__(self, obj: t.Any, value: t.Any) -> None:48+ def __set__(self, obj: App, value: t.Any) -> None:49 obj.config[self.__name__] = value50 51 31-class Config(dict):52+class Config(dict): # type: ignore[type-arg]53 """Works exactly like a dict but provides ways to fill it from files54 or special dictionaries. There are two common patterns to populate the55 config.56 36 unmodified lines93 :param defaults: an optional dictionary of default values94 """95 96 def __init__(76- self, root_path: str | os.PathLike, defaults: dict | None = None97+ self,98+ root_path: str | os.PathLike[str],99+ defaults: dict[str, t.Any] | None = None,100 ) -> None:101 super().__init__(defaults or {})102 self.root_path = root_path103 84 unmodified lines188 current[tail] = value189 190 return True191 169- def from_pyfile(self, filename: str | os.PathLike, silent: bool = False) -> bool:192+ def from_pyfile(193+ self, filename: str | os.PathLike[str], silent: bool = False194+ ) -> bool:195 """Updates the values in the config from a Python file. This function196 behaves as if the file was imported as module with the197 :meth:`from_object` function.198 60 unmodified lines259 self[key] = getattr(obj, key)260 261 def from_file(262 self,238- filename: str | os.PathLike,239- load: t.Callable[[t.IO[t.Any]], t.Mapping],263+ filename: str | os.PathLike[str],264+ load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],265 silent: bool = False,266 text: bool = True,267 ) -> bool:268 """Update the values in the config from a file that is loaded104 unmodified linesmodified:src/flask/ctx.py+19 added-10 removed
13 unmodified lines14 from .signals import appcontext_popped15 from .signals import appcontext_pushed16 17 if t.TYPE_CHECKING: # pragma: no cover18+ from _typeshed.wsgi import WSGIEnvironment19+20 from .app import Flask21 from .sessions import SessionMixin22 from .wrappers import Request23 89 unmodified lines113 return f"<flask.g of '{ctx.app.name}'>"114 return object.__repr__(self)115 116 115-def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:117+def after_this_request(118+ f: ft.AfterRequestCallable[t.Any],119+) -> ft.AfterRequestCallable[t.Any]:120 """Executes a function after this request. This is useful to modify121 response objects. The function is passed the response object and has122 to return the same or a new one.123 24 unmodified lines148 ctx._after_request_functions.append(f)149 return f150 151 152+F = t.TypeVar("F", bound=t.Callable[..., t.Any])153+154+148-def copy_current_request_context(f: t.Callable) -> t.Callable:155+def copy_current_request_context(f: F) -> F:156 """A helper function that decorates a function to retain the current157 request context. This is useful when working with greenlets. The moment158 the function is decorated a copy of the request context is created and159 then pushed when the function is called. The current session is also25 unmodified lines185 )186 187 ctx = ctx.copy()188 182- def wrapper(*args, **kwargs):183- with ctx:184- return ctx.app.ensure_sync(f)(*args, **kwargs)189+ def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:190+ with ctx: # type: ignore[union-attr]191+ return ctx.app.ensure_sync(f)(*args, **kwargs) # type: ignore[union-attr]192 186- return update_wrapper(wrapper, f)193+ return update_wrapper(wrapper, f) # type: ignore[return-value]194 195 196 def has_request_context() -> bool:197 """If you have code that wants to test if a request context is there or47 unmodified lines245 def __init__(self, app: Flask) -> None:246 self.app = app247 self.url_adapter = app.create_url_adapter(None)248 self.g: _AppCtxGlobals = app.app_ctx_globals_class()242- self._cv_tokens: list[contextvars.Token] = []249+ self._cv_tokens: list[contextvars.Token[AppContext]] = []250 251 def push(self) -> None:252 """Binds the app context to the current context."""253 self._cv_tokens.append(_cv_app.set(self))54 unmodified lines308 309 def __init__(310 self,311 app: Flask,305- environ: dict,312+ environ: WSGIEnvironment,313 request: Request | None = None,314 session: SessionMixin | None = None,315 ) -> None:316 self.app = app10 unmodified lines327 self.session: SessionMixin | None = session328 # Functions that should be executed after the request on the response329 # object. These will be called before the regular "after_request"330 # functions.324- self._after_request_functions: list[ft.AfterRequestCallable] = []331+ self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []332 326- self._cv_tokens: list[tuple[contextvars.Token, AppContext | None]] = []333+ self._cv_tokens: list[334+ tuple[contextvars.Token[RequestContext], AppContext | None]335+ ] = []336 337 def copy(self) -> RequestContext:338 """Creates a copy of this request context with the same request object.339 This can be used to move a request context to a different greenlet.110 unmodified linesmodified:src/flask/debughelpers.py+26 added-8 removed
1 from __future__ import annotations2 3 import typing as t4 5+from jinja2.loaders import BaseLoader6+from werkzeug.routing import RequestRedirect7+8 from .blueprints import Blueprint9 from .globals import request_ctx10 from .sansio.app import App11 12+if t.TYPE_CHECKING:13+ from .sansio.scaffold import Scaffold14+ from .wrappers import Request15 16+17 class UnexpectedUnicodeError(AssertionError, UnicodeError):18 """Raised in places where we want some better error reporting for19 unexpected unicode or binary data.20 """3 unmodified lines24 """Raised from request.files during debugging. The idea is that it can25 provide a better error message than just a generic KeyError/BadRequest.26 """27 21- def __init__(self, request, key):28+ def __init__(self, request: Request, key: str) -> None:29 form_matches = request.form.getlist(key)30 buf = [31 f"You tried to access the file {key!r} in the request.files"32 " dictionary but it does not exist. The mimetype for the"9 unmodified lines42 f"This was submitted: {names}"43 )44 self.msg = "".join(buf)45 39- def __str__(self):46+ def __str__(self) -> str:47 return self.msg48 49 50 class FormDataRoutingRedirect(AssertionError):2 unmodified lines53 when method is not GET, HEAD or OPTIONS and the status code is not54 307 or 308.55 """56 50- def __init__(self, request):57+ def __init__(self, request: Request) -> None:58 exc = request.routing_exception59+ assert isinstance(exc, RequestRedirect)60 buf = [61 f"A request was sent to '{request.url}', but routing issued"62 f" a redirect to the canonical URL '{exc.new_url}'."63 ]13 unmodified lines77 )78 super().__init__("".join(buf))79 80 73-def attach_enctype_error_multidict(request):81+def attach_enctype_error_multidict(request: Request) -> None:82 """Patch ``request.files.__getitem__`` to raise a descriptive error83 about ``enctype=multipart/form-data``.84 85 :param request: The request to patch.86 :meta private:87 """88 oldcls = request.files.__class__89 82- class newcls(oldcls):83- def __getitem__(self, key):90+ class newcls(oldcls): # type: ignore[valid-type, misc]91+ def __getitem__(self, key: str) -> t.Any:92 try:93 return super().__getitem__(key)94 except KeyError as e:95 if key not in request.form:7 unmodified lines103 newcls.__module__ = oldcls.__module__104 request.files.__class__ = newcls105 106 99-def _dump_loader_info(loader) -> t.Generator:107+def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]:108 yield f"class: {type(loader).__module__}.{type(loader).__name__}"109 for key, value in sorted(loader.__dict__.items()):110 if key.startswith("_"):111 continue8 unmodified lines120 continue121 yield f"{key}: {value!r}"122 123 116-def explain_template_loading_attempts(app: App, template, attempts) -> None:124+def explain_template_loading_attempts(125+ app: App,126+ template: str,127+ attempts: list[128+ tuple[129+ BaseLoader,130+ Scaffold,131+ tuple[str, str | None, t.Callable[[], bool] | None] | None,132+ ]133+ ],134+) -> None:135 """This should help developers understand what failed"""136 info = [f"Locating template {template!r}:"]137 total_found = 0138 blueprint = None40 unmodified linesmodified:src/flask/helpers.py+11 added-12 removed
9 unmodified lines10 11 import werkzeug.utils12 from werkzeug.exceptions import abort as _wz_abort13 from werkzeug.utils import redirect as _wz_redirect14+from werkzeug.wrappers import Response as BaseResponse15 16 from .globals import _cv_request17 from .globals import current_app18 from .globals import request1 unmodified line20 from .globals import session21 from .signals import message_flashed22 23 if t.TYPE_CHECKING: # pragma: no cover23- from werkzeug.wrappers import Response as BaseResponse24-24 from .wrappers import Response25 26 27 def get_debug_flag() -> bool:19 unmodified lines47 return val.lower() in ("0", "false", "no")48 49 50 def stream_with_context(52- generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]]51+ generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],52 ) -> t.Iterator[t.AnyStr]:53 """Request contexts disappear when the response is started on the server.54 This is done for efficiency reasons and to make it less likely to encounter55 memory leaks with badly written WSGI middlewares. The downside is that if27 unmodified lines83 84 .. versionadded:: 0.985 """86 try:88- gen = iter(generator_or_function) # type: ignore87+ gen = iter(generator_or_function) # type: ignore[arg-type]88 except TypeError:89 90 def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:92- gen = generator_or_function(*args, **kwargs) # type: ignore91+ gen = generator_or_function(*args, **kwargs) # type: ignore[operator]92 return stream_with_context(gen)93 95- return update_wrapper(decorator, generator_or_function) # type: ignore94+ return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]95 97- def generator() -> t.Generator:96+ def generator() -> t.Iterator[t.AnyStr | None]:97 ctx = _cv_request.get(None)98 if ctx is None:99 raise RuntimeError(100 "'stream_with_context' can only be used when a request"19 unmodified lines120 # pushed. This item is discarded. Then when the iteration continues the121 # real generator is executed.122 wrapped_g = generator()123 next(wrapped_g)125- return wrapped_g124+ return wrapped_g # type: ignore[return-value]125 126 127 def make_response(*args: t.Any) -> Response:128 """Sometimes it is necessary to set additional headers in a view. Because40 unmodified lines169 if not args:170 return current_app.response_class()171 if len(args) == 1:172 args = args[0]174- return current_app.make_response(args) # type: ignore173+ return current_app.make_response(args)174 175 176 def url_for(177 endpoint: str,333 unmodified lines511 )512 513 514 def send_from_directory(516- directory: os.PathLike | str,517- path: os.PathLike | str,515+ directory: os.PathLike[str] | str,516+ path: os.PathLike[str] | str,517 **kwargs: t.Any,518 ) -> Response:519 """Send a file from within a directory using :func:`send_file`.520 86 unmodified lines607 " provided."608 )609 610 # filepath is import_name.py for a module, or __init__.py for a package.612- return os.path.dirname(os.path.abspath(filepath))611+ return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return]612 613 614 @lru_cache(maxsize=None)615 def _split_blueprint_path(name: str) -> list[str]:6 unmodified linesmodified:src/flask/logging.py+4 added-1 removed
20 unmodified lines21 use this for the stream. If you are using file or dict configuration and22 can't import this directly, you can refer to it as23 ``ext://flask.logging.wsgi_errors_stream``.24 """25+ if request:25- return request.environ["wsgi.errors"] if request else sys.stderr26+ return request.environ["wsgi.errors"] # type: ignore[no-any-return]27 28+ return sys.stderr29 30+31 def has_level_handler(logger: logging.Logger) -> bool:32 """Check if there is a handler in the logging chain that will handle the33 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.34 """45 unmodified linesmodified:src/flask/sessions.py+14 added-11 removed
11 unmodified lines12 13 from .json.tag import TaggedJSONSerializer14 15 if t.TYPE_CHECKING: # pragma: no cover16+ import typing_extensions as te17+18 from .app import Flask19 from .wrappers import Request20 from .wrappers import Response21 22 23+# TODO generic when Python > 3.821-class SessionMixin(MutableMapping):24+class SessionMixin(MutableMapping): # type: ignore[type-arg]25 """Expands a basic dictionary with session attributes."""26 27 @property28 def permanent(self) -> bool:19 unmodified lines48 #: coded to ``True``.49 accessed = True50 51 52+# TODO generic when Python > 3.849-class SecureCookieSession(CallbackDict, SessionMixin):53+class SecureCookieSession(CallbackDict, SessionMixin): # type: ignore[type-arg]54 """Base class for sessions based on signed cookies.55 56 This session backend will set the :attr:`modified` and57 :attr:`accessed` attributes. It cannot reliably track whether a14 unmodified lines72 #: different users.73 accessed = False74 75 def __init__(self, initial: t.Any = None) -> None:72- def on_update(self) -> None:76+ def on_update(self: te.Self) -> None:77 self.modified = True78 self.accessed = True79 80 super().__init__(initial, on_update)100 unmodified lines181 return isinstance(obj, self.null_session_class)182 183 def get_cookie_name(self, app: Flask) -> str:184 """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""181- return app.config["SESSION_COOKIE_NAME"]185+ return app.config["SESSION_COOKIE_NAME"] # type: ignore[no-any-return]186 187 def get_cookie_domain(self, app: Flask) -> str | None:188 """The value of the ``Domain`` parameter on the session cookie. If not set,189 browsers will only send the cookie to the exact domain it was set from.3 unmodified lines193 194 .. versionchanged:: 2.3195 Not set by default, does not fall back to ``SERVER_NAME``.196 """193- rv = app.config["SESSION_COOKIE_DOMAIN"]194- return rv if rv else None197+ return app.config["SESSION_COOKIE_DOMAIN"] # type: ignore[no-any-return]198 199 def get_cookie_path(self, app: Flask) -> str:200 """Returns the path for which the cookie should be valid. The201 default implementation uses the value from the ``SESSION_COOKIE_PATH``202 config var if it's set, and falls back to ``APPLICATION_ROOT`` or203 uses ``/`` if it's ``None``.204 """202- return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]205+ return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"] # type: ignore[no-any-return]206 207 def get_cookie_httponly(self, app: Flask) -> bool:208 """Returns True if the session cookie should be httponly. This209 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``210 config var.211 """209- return app.config["SESSION_COOKIE_HTTPONLY"]212+ return app.config["SESSION_COOKIE_HTTPONLY"] # type: ignore[no-any-return]213 214 def get_cookie_secure(self, app: Flask) -> bool:215 """Returns True if the cookie should be secure. This currently216 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.217 """215- return app.config["SESSION_COOKIE_SECURE"]218+ return app.config["SESSION_COOKIE_SECURE"] # type: ignore[no-any-return]219 217- def get_cookie_samesite(self, app: Flask) -> str:220+ def get_cookie_samesite(self, app: Flask) -> str | None:221 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the222 ``SameSite`` attribute. This currently just returns the value of223 the :data:`SESSION_COOKIE_SAMESITE` setting.224 """222- return app.config["SESSION_COOKIE_SAMESITE"]225+ return app.config["SESSION_COOKIE_SAMESITE"] # type: ignore[no-any-return]226 227 def get_expiration_time(self, app: Flask, session: SessionMixin) -> datetime | None:228 """A helper method that returns an expiration date for the session229 or ``None`` if the session is linked to the browser session. The142 unmodified linesmodified:src/flask/templating.py+8 added-10 removed
55 unmodified lines56 57 def __init__(self, app: App) -> None:58 self.app = app59 60- def get_source( # type: ignore61- self, environment: Environment, template: str62- ) -> tuple[str, str | None, t.Callable | None]:60+ def get_source(61+ self, environment: BaseEnvironment, template: str62+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:63 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:64 return self._get_source_explained(environment, template)65 return self._get_source_fast(environment, template)66 67 def _get_source_explained(68- self, environment: Environment, template: str69- ) -> tuple[str, str | None, t.Callable | None]:68+ self, environment: BaseEnvironment, template: str69+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:70 attempts = []71 rv: tuple[str, str | None, t.Callable[[], bool] | None] | None72 trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None73 14 unmodified lines88 return trv89 raise TemplateNotFound(template)90 91 def _get_source_fast(92- self, environment: Environment, template: str93- ) -> tuple[str, str | None, t.Callable | None]:92+ self, environment: BaseEnvironment, template: str93+ ) -> tuple[str, str | None, t.Callable[[], bool] | None]:94 for _srcobj, loader in self._iter_loaders(template):95 try:96 return loader.get_source(environment, template)97 except TemplateNotFound:98 continue99 raise TemplateNotFound(template)100 101- def _iter_loaders(102- self, template: str103- ) -> t.Generator[tuple[Scaffold, BaseLoader], None, None]:101+ def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:102 loader = self.app.jinja_loader103 if loader is not None:104 yield self.app, loader105 114 unmodified linesmodified:src/flask/testing.py+8 added-5 removed
15 unmodified lines16 from .cli import ScriptInfo17 from .sessions import SessionMixin18 19 if t.TYPE_CHECKING: # pragma: no cover20+ from _typeshed.wsgi import WSGIEnvironment21 from werkzeug.test import TestResponse22 23 from .app import Flask24 109 unmodified lines134 135 @contextmanager136 def session_transaction(137 self, *args: t.Any, **kwargs: t.Any137- ) -> t.Generator[SessionMixin, None, None]:138+ ) -> t.Iterator[SessionMixin]:139 """When used in combination with a ``with`` statement this opens a140 session transaction. This can be used to modify the session that141 the test client uses. Once the ``with`` block is left the session is142 stored back.38 unmodified lines181 ctx.request.path,182 resp.headers.getlist("Set-Cookie"),183 )184 184- def _copy_environ(self, other):185+ def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:186 out = {**self.environ_base, **other}187 188 if self.preserve_context:189 out["werkzeug.debug.preserve_context"] = self._new_contexts.append190 191 return out192 192- def _request_from_builder_args(self, args, kwargs):193+ def _request_from_builder_args(194+ self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]195+ ) -> BaseRequest:196 kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {}))197 builder = EnvironBuilder(self.application, *args, **kwargs)198 199 try:12 unmodified lines212 args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)213 ):214 if isinstance(args[0], werkzeug.test.EnvironBuilder):215 builder = copy(args[0])213- builder.environ_base = self._copy_environ(builder.environ_base or {})216+ builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type]217 request = builder.get_request()218 elif isinstance(args[0], dict):219 request = EnvironBuilder.from_environ(220 args[0], app=self.application, environ_base=self._copy_environ({})68 unmodified lines289 290 :return: a :class:`~click.testing.Result` object.291 """292 if cli is None:290- cli = self.app.cli # type: ignore293+ cli = self.app.cli294 295 if "obj" not in kwargs:296 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)297 1 unmodified linemodified:src/flask/typing.py+4 added-2 removed
66 unmodified lines67 ]68 TemplateFilterCallable = t.Callable[..., t.Any]69 TemplateGlobalCallable = t.Callable[..., t.Any]70 TemplateTestCallable = t.Callable[..., bool]71-URLDefaultCallable = t.Callable[[str, dict], None]72-URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]71+URLDefaultCallable = t.Callable[[str, t.Dict[str, t.Any]], None]72+URLValuePreprocessorCallable = t.Callable[73+ [t.Optional[str], t.Optional[t.Dict[str, t.Any]]], None74+]75 76 # This should take Exception, but that either breaks typing the argument77 # with a specific exception, or decorating multiple times with different78 # exceptions (and using a union type on the argument).12 unmodified linesmodified:src/flask/views.py+6 added-4 removed
4 unmodified lines5 from . import typing as ft6 from .globals import current_app7 from .globals import request8 9+F = t.TypeVar("F", bound=t.Callable[..., t.Any])10+11 http_method_funcs = frozenset(12 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]13 )14 45 unmodified lines60 #: to top, so the first decorator in the list would be the bottom61 #: decorator.62 #:63 #: .. versionadded:: 0.862- decorators: t.ClassVar[list[t.Callable]] = []64+ decorators: t.ClassVar[list[t.Callable[[F], F]]] = []65 66 #: Create a new instance of this view class for every request by67 #: default. If a view subclass sets this to ``False``, the same68 #: instance is used for every request.37 unmodified lines106 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:107 self = view.view_class( # type: ignore[attr-defined]108 *class_args, **class_kwargs109 )108- return current_app.ensure_sync(self.dispatch_request)(**kwargs)110+ return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]111 112 else:113 self = cls(*class_args, **class_kwargs)114 115 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:114- return current_app.ensure_sync(self.dispatch_request)(**kwargs)116+ return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]117 118 if cls.decorators:119 view.__name__ = name120 view.__module__ = cls.__module__66 unmodified lines187 if meth is None and request.method == "HEAD":188 meth = getattr(self, "get", None)189 190 assert meth is not None, f"Unimplemented method {request.method!r}"189- return current_app.ensure_sync(meth)(**kwargs)191+ return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return]modified:src/flask/wrappers.py+5 added-4 removed
1 unmodified line2 3 import typing as t4 5 from werkzeug.exceptions import BadRequest6+from werkzeug.exceptions import HTTPException7 from werkzeug.wrappers import Request as RequestBase8 from werkzeug.wrappers import Response as ResponseBase9 10 from . import json38 unmodified lines49 #: If matching the URL failed, this is the exception that will be50 #: raised / was raised as part of the request handling. This is51 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or52 #: something similar.52- routing_exception: Exception | None = None53+ routing_exception: HTTPException | None = None54 55 @property55- def max_content_length(self) -> int | None: # type: ignore56+ def max_content_length(self) -> int | None: # type: ignore[override]57 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""58 if current_app:58- return current_app.config["MAX_CONTENT_LENGTH"]59+ return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return]60 else:61 return None62 63 @property103 unmodified lines167 See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in168 Werkzeug's docs.169 """170 if current_app:170- return current_app.config["MAX_COOKIE_SIZE"]171+ return current_app.config["MAX_COOKIE_SIZE"] # type: ignore[no-any-return]172 173 # return Werkzeug's default when not in an app context174 return super().max_cookie_sizemodified:.pre-commit-config.yaml+1 added-1 removed
1 ci:2 autoupdate_schedule: monthly3 repos:4 - repo: https://github.com/astral-sh/ruff-pre-commit5- rev: v0.1.55+ rev: v0.1.136 hooks:7 - id: ruff8 - id: ruff-format9 - repo: https://github.com/pre-commit/pre-commit-hooks7 unmodified linesmodified:CHANGES.rst+1 added
6 unmodified lines7 - Fix a typo in an error message for the ``flask run --key`` option. :pr:`5344`8 - Session data is untagged without relying on the built-in ``json.loads``9 ``object_hook``. This allows other JSON providers that don't implement that.10 :issue:`5381`11+- Address more type findings when using mypy strict mode. :pr:`5383`12 13 14 Version 3.0.015 -------------1528 unmodified linesmodified:pyproject.toml+1 added-15 removed
80 unmodified lines81 python_version = "3.8"82 files = ["src/flask", "tests/typing"]83 show_error_codes = true84 pretty = true85-#strict = true86-allow_redefinition = true87-disallow_subclassing_any = true88-#disallow_untyped_calls = true89-#disallow_untyped_defs = true90-#disallow_incomplete_defs = true91-no_implicit_optional = true92-local_partial_types = true93-#no_implicit_reexport = true94-strict_equality = true95-warn_redundant_casts = true96-warn_unused_configs = true97-warn_unused_ignores = true98-#warn_return_any = true99-#warn_unreachable = true85+strict = true86 87 [[tool.mypy.overrides]]88 module = [89 "asgiref.*",26 unmodified lines