Fixes Pyright type errors

This commit is contained in:
bre-17387639 2024-08-06 16:46:15 -06:00
parent 8a6cdf1e2a
commit eeae10c142
8 changed files with 26 additions and 17 deletions

View file

@ -6,6 +6,8 @@ Version 3.1.0
- ``Flask.open_resource``/``open_instance_resource`` and - ``Flask.open_resource``/``open_instance_resource`` and
``Blueprint.open_resource`` take an ``encoding`` parameter to use when ``Blueprint.open_resource`` take an ``encoding`` parameter to use when
opening in text mode. It defaults to ``utf-8``. :issue:`5504` opening in text mode. It defaults to ``utf-8``. :issue:`5504`
- Fixes Pyright type errors. :issue:`5549`
Version 3.0.3 Version 3.0.3
------------- -------------

View file

@ -349,7 +349,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 +1163,10 @@ class Flask(App):
response object. response object.
""" """
status = headers = None status: int | None = None
headers: (
Headers | dict[t.Any, t.Any] | tuple[t.Any, ...] | list[t.Any] | None
) = None
# unpack tuple returns # unpack tuple returns
if isinstance(rv, tuple): if isinstance(rv, tuple):
@ -1171,11 +1174,11 @@ class Flask(App):
# a 3-tuple is unpacked directly # a 3-tuple is unpacked directly
if len_rv == 3: if len_rv == 3:
rv, status, headers = rv # type: ignore[misc] rv, status, headers = rv # type: ignore[assignment, misc]
# 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 # type: 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
@ -1203,7 +1206,7 @@ class Flask(App):
rv = self.response_class( rv = self.response_class(
rv, rv,
status=status, status=status,
headers=headers, # type: ignore[arg-type] headers=headers,
) )
status = headers = None status = headers = None
elif isinstance(rv, (dict, list)): elif isinstance(rv, (dict, list)):
@ -1243,7 +1246,7 @@ class Flask(App):
# extend existing headers with provided headers # extend existing headers with provided headers
if headers: if headers:
rv.headers.update(headers) # type: ignore[arg-type] rv.headers.update(headers)
return rv return rv

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[t.Any] = 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

@ -587,7 +587,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

@ -79,6 +79,10 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
path = url.path path = url.path
if url.query: if url.query:
# NOTE:
# If `path` in func args is `str`, then `url.query` will
# never be a `bytes` Should we adjust `path`? Should we
# adjust this statement here?
sep = b"?" if isinstance(url.query, bytes) else "?" sep = b"?" if isinstance(url.query, bytes) else "?"
path += sep + url.query path += sep + url.query

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 e_badreq:
if current_app and current_app.debug: if current_app and current_app.debug:
raise raise
raise BadRequest() from e raise BadRequest() from e_badreq
class Response(ResponseBase): class Response(ResponseBase):