fix pyright type errors

This commit is contained in:
bre-17387639 2024-08-06 16:46:15 -06:00 committed by David Lord
parent 5e8cb74018
commit 9e831e915f
No known key found for this signature in database
GPG key ID: 43368A7AA8CC5926
10 changed files with 22 additions and 19 deletions

View file

@ -95,7 +95,7 @@ ignore_missing_imports = true
[tool.pyright] [tool.pyright]
pythonVersion = "3.8" pythonVersion = "3.8"
include = ["src/flask", "tests"] include = ["src/flask", "tests/typing"]
typeCheckingMode = "basic" typeCheckingMode = "basic"
[tool.ruff] [tool.ruff]

View file

@ -59,6 +59,7 @@ if t.TYPE_CHECKING: # pragma: no cover
from .testing import FlaskClient from .testing import FlaskClient
from .testing import FlaskCliRunner from .testing import FlaskCliRunner
from .typing import HeadersValue
T_shell_context_processor = t.TypeVar( T_shell_context_processor = t.TypeVar(
"T_shell_context_processor", bound=ft.ShellContextProcessorCallable "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
@ -349,7 +350,7 @@ class Flask(App):
path = os.path.join(self.root_path, resource) path = os.path.join(self.root_path, resource)
if mode == "rb": if mode == "rb":
return open(path, mode) return open(path, mode) # pyright: ignore
return open(path, mode, encoding=encoding) return open(path, mode, encoding=encoding)
@ -1163,7 +1164,8 @@ class Flask(App):
response object. response object.
""" """
status = headers = None status: int | None = None
headers: HeadersValue | None = None
# unpack tuple returns # unpack tuple returns
if isinstance(rv, tuple): if isinstance(rv, tuple):
@ -1175,7 +1177,7 @@ class Flask(App):
# decide if a 2-tuple has status or headers # decide if a 2-tuple has status or headers
elif len_rv == 2: elif len_rv == 2:
if isinstance(rv[1], (Headers, dict, tuple, list)): if isinstance(rv[1], (Headers, dict, tuple, list)):
rv, headers = rv rv, headers = rv # pyright: ignore
else: else:
rv, status = rv # type: ignore[assignment,misc] rv, status = rv # type: ignore[assignment,misc]
# other sized tuples are not allowed # other sized tuples are not allowed

View file

@ -123,6 +123,6 @@ class Blueprint(SansioBlueprint):
path = os.path.join(self.root_path, resource) path = os.path.join(self.root_path, resource)
if mode == "rb": if mode == "rb":
return open(path, mode) return open(path, mode) # pyright: ignore
return open(path, mode, encoding=encoding) return open(path, mode, encoding=encoding)

View file

@ -323,9 +323,9 @@ class ScriptInfo:
""" """
if self._loaded_app is not None: if self._loaded_app is not None:
return self._loaded_app return self._loaded_app
app: Flask | None = None
if self.create_app is not None: if self.create_app is not None:
app: Flask | None = self.create_app() app = self.create_app()
else: else:
if self.app_import_path: if self.app_import_path:
path, name = ( path, name = (
@ -549,7 +549,7 @@ class FlaskGroup(AppGroup):
set_debug_flag: bool = True, set_debug_flag: bool = True,
**extra: t.Any, **extra: t.Any,
) -> None: ) -> None:
params = list(extra.pop("params", None) or ()) params: list[click.Parameter] = list(extra.pop("params", None) or ())
# Processing is done with option callbacks instead of a group # Processing is done with option callbacks instead of a group
# callback. This allows users to make a custom group callback # callback. This allows users to make a custom group callback
# without losing the behavior. --env-file must come first so # without losing the behavior. --env-file must come first so
@ -587,7 +587,7 @@ class FlaskGroup(AppGroup):
# Use a backport on Python < 3.10. We technically have # Use a backport on Python < 3.10. We technically have
# importlib.metadata on 3.8+, but the API changed in 3.10, # importlib.metadata on 3.8+, but the API changed in 3.10,
# so use the backport for consistency. # so use the backport for consistency.
import importlib_metadata as metadata import importlib_metadata as metadata # pyright: ignore
for ep in metadata.entry_points(group="flask.commands"): for ep in metadata.entry_points(group="flask.commands"):
self.add_command(ep.load(), ep.name) self.add_command(ep.load(), ep.name)
@ -934,7 +934,7 @@ def run_command(
option. option.
""" """
try: try:
app: WSGIApplication = info.load_app() app: WSGIApplication = info.load_app() # pyright: ignore
except Exception as e: except Exception as e:
if is_running_from_reloader(): if is_running_from_reloader():
# When reloading, print out the error immediately, but raise # When reloading, print out the error immediately, but raise

View file

@ -599,7 +599,7 @@ def get_root_path(import_name: str) -> str:
return os.getcwd() return os.getcwd()
if hasattr(loader, "get_filename"): if hasattr(loader, "get_filename"):
filepath = loader.get_filename(import_name) filepath = loader.get_filename(import_name) # pyright: ignore
else: else:
# Fall back to imports. # Fall back to imports.
__import__(import_name) __import__(import_name)

View file

@ -628,7 +628,7 @@ class App(Scaffold):
methods = {item.upper() for item in methods} methods = {item.upper() for item in methods}
# Methods that should always be added # Methods that should always be added
required_methods = set(getattr(view_func, "required_methods", ())) required_methods: set[str] = set(getattr(view_func, "required_methods", ()))
# starting with Flask 0.8 the view_func object can disable and # starting with Flask 0.8 the view_func object can disable and
# force-enable the automatic options handling. # force-enable the automatic options handling.

View file

@ -79,8 +79,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
path = url.path path = url.path
if url.query: if url.query:
sep = b"?" if isinstance(url.query, bytes) else "?" path = f"{path}?{url.query}"
path += sep + url.query
self.app = app self.app = app
super().__init__(path, base_url, *args, **kwargs) super().__init__(path, base_url, *args, **kwargs)

View file

@ -61,7 +61,7 @@ class View:
#: decorator. #: decorator.
#: #:
#: .. versionadded:: 0.8 #: .. versionadded:: 0.8
decorators: t.ClassVar[list[t.Callable[[F], F]]] = [] decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = []
#: Create a new instance of this view class for every request by #: Create a new instance of this view class for every request by
#: default. If a view subclass sets this to ``False``, the same #: default. If a view subclass sets this to ``False``, the same
@ -110,7 +110,7 @@ class View:
return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return] return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]
else: else:
self = cls(*class_args, **class_kwargs) self = cls(*class_args, **class_kwargs) # pyright: ignore
def view(**kwargs: t.Any) -> ft.ResponseReturnValue: def view(**kwargs: t.Any) -> ft.ResponseReturnValue:
return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return] return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]

View file

@ -129,11 +129,11 @@ class Request(RequestBase):
def on_json_loading_failed(self, e: ValueError | None) -> t.Any: def on_json_loading_failed(self, e: ValueError | None) -> t.Any:
try: try:
return super().on_json_loading_failed(e) return super().on_json_loading_failed(e)
except BadRequest as e: except BadRequest as ebr:
if current_app and current_app.debug: if current_app and current_app.debug:
raise raise
raise BadRequest() from e raise BadRequest() from ebr
class Response(ResponseBase): class Response(ResponseBase):

View file

@ -28,7 +28,9 @@ commands = pre-commit run --all-files
[testenv:typing] [testenv:typing]
deps = -r requirements/typing.txt deps = -r requirements/typing.txt
commands = mypy commands =
mypy
pyright
[testenv:docs] [testenv:docs]
deps = -r requirements/docs.txt deps = -r requirements/docs.txt