Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pyright types fixes #5550

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Version 3.1.0
- ``Flask.open_resource``/``open_instance_resource`` and
``Blueprint.open_resource`` take an ``encoding`` parameter to use when
opening in text mode. It defaults to ``utf-8``. :issue:`5504`
- Fixes Pyright type errors. :issue:`5549`


Version 3.0.3
-------------
Expand Down
15 changes: 9 additions & 6 deletions src/flask/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def open_resource(
path = os.path.join(self.root_path, resource)

if mode == "rb":
return open(path, mode)
return open(path, mode) # pyright: ignore

return open(path, mode, encoding=encoding)

Expand Down Expand Up @@ -1163,19 +1163,22 @@ def make_response(self, rv: ft.ResponseReturnValue) -> Response:
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
if isinstance(rv, tuple):
len_rv = len(rv)

# a 3-tuple is unpacked directly
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
elif len_rv == 2:
if isinstance(rv[1], (Headers, dict, tuple, list)):
rv, headers = rv
rv, headers = rv # type: ignore
else:
rv, status = rv # type: ignore[assignment,misc]
# other sized tuples are not allowed
Expand Down Expand Up @@ -1203,7 +1206,7 @@ def make_response(self, rv: ft.ResponseReturnValue) -> Response:
rv = self.response_class(
rv,
status=status,
headers=headers, # type: ignore[arg-type]
headers=headers,
)
status = headers = None
elif isinstance(rv, (dict, list)):
Expand Down Expand Up @@ -1243,7 +1246,7 @@ def make_response(self, rv: ft.ResponseReturnValue) -> Response:

# extend existing headers with provided headers
if headers:
rv.headers.update(headers) # type: ignore[arg-type]
rv.headers.update(headers)

return rv

Expand Down
2 changes: 1 addition & 1 deletion src/flask/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,6 @@ def open_resource(
path = os.path.join(self.root_path, resource)

if mode == "rb":
return open(path, mode)
return open(path, mode) # pyright: ignore

return open(path, mode, encoding=encoding)
10 changes: 5 additions & 5 deletions src/flask/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,9 @@ def load_app(self) -> Flask:
"""
if self._loaded_app is not None:
return self._loaded_app

app: Flask | None = None
if self.create_app is not None:
app: Flask | None = self.create_app()
app = self.create_app()
else:
if self.app_import_path:
path, name = (
Expand Down Expand Up @@ -549,7 +549,7 @@ def __init__(
set_debug_flag: bool = True,
**extra: t.Any,
) -> 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
# callback. This allows users to make a custom group callback
# without losing the behavior. --env-file must come first so
Expand Down Expand Up @@ -587,7 +587,7 @@ def _load_plugin_commands(self) -> None:
# Use a backport on Python < 3.10. We technically have
# importlib.metadata on 3.8+, but the API changed in 3.10,
# 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"):
self.add_command(ep.load(), ep.name)
Expand Down Expand Up @@ -934,7 +934,7 @@ def run_command(
option.
"""
try:
app: WSGIApplication = info.load_app()
app: WSGIApplication = info.load_app() # pyright: ignore
except Exception as e:
if is_running_from_reloader():
# When reloading, print out the error immediately, but raise
Expand Down
2 changes: 1 addition & 1 deletion src/flask/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ def get_root_path(import_name: str) -> str:
return os.getcwd()

if hasattr(loader, "get_filename"):
filepath = loader.get_filename(import_name)
filepath = loader.get_filename(import_name) # pyright: ignore
else:
# Fall back to imports.
__import__(import_name)
Expand Down
4 changes: 4 additions & 0 deletions src/flask/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ def __init__(
path = url.path

if url.query:
# NOTE:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@davidism See note here

# 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 "?"
path += sep + url.query

Expand Down
4 changes: 2 additions & 2 deletions src/flask/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def dispatch_request(self, name):
#: decorator.
#:
#: .. 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
#: default. If a view subclass sets this to ``False``, the same
Expand Down Expand Up @@ -110,7 +110,7 @@ def view(**kwargs: t.Any) -> ft.ResponseReturnValue:
return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]

else:
self = cls(*class_args, **class_kwargs)
self = cls(*class_args, **class_kwargs) # pyright: ignore

def view(**kwargs: t.Any) -> ft.ResponseReturnValue:
return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]
Expand Down
4 changes: 2 additions & 2 deletions src/flask/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ def _load_form_data(self) -> None:
def on_json_loading_failed(self, e: ValueError | None) -> t.Any:
try:
return super().on_json_loading_failed(e)
except BadRequest as e:
except BadRequest as e_badreq:
if current_app and current_app.debug:
raise

raise BadRequest() from e
raise BadRequest() from e_badreq


class Response(ResponseBase):
Expand Down