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

Improve typing of exception handlers #1456

Closed
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ ignore = W503, E203, B305
max-line-length = 88

[mypy]
python_version = 3.6
Copy link
Author

Choose a reason for hiding this comment

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

This makes sure mypy checks for compatibility with Python 3.6 and onwards, which seems to be the oldest version Starlette supports (?).

disallow_untyped_defs = True
ignore_missing_imports = True
no_implicit_optional = True
Expand Down
28 changes: 16 additions & 12 deletions starlette/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@
from starlette.routing import BaseRoute, Router
from starlette.types import ASGIApp, Receive, Scope, Send

_ExcKey = typing.TypeVar(
"_ExcKey",
bound=typing.Union[int, typing.Type[Exception]],
contravariant=True,
)
# Breaking out Exception to a bounded TypeVar here allows defining a narrower type in
# handlers, like HTTPException.
_HandledException = typing.TypeVar("_HandledException", bound=Exception)
_ExcHandler = typing.Callable[
[Request, _HandledException], typing.Union[Response, typing.Awaitable[Response]]
]


class Starlette:
"""
Expand Down Expand Up @@ -44,13 +56,7 @@ def __init__(
routes: typing.Optional[typing.Sequence[BaseRoute]] = None,
middleware: typing.Optional[typing.Sequence[Middleware]] = None,
exception_handlers: typing.Optional[
typing.Mapping[
typing.Any,
typing.Callable[
[Request, Exception],
typing.Union[Response, typing.Awaitable[Response]],
],
]
typing.Mapping[_ExcKey, _ExcHandler]
] = None,
on_startup: typing.Optional[typing.Sequence[typing.Callable]] = None,
on_shutdown: typing.Optional[typing.Sequence[typing.Callable]] = None,
Expand Down Expand Up @@ -78,9 +84,7 @@ def __init__(
def build_middleware_stack(self) -> ASGIApp:
debug = self.debug
error_handler = None
exception_handlers: typing.Dict[
typing.Any, typing.Callable[[Request, Exception], Response]
] = {}
exception_handlers = {}

for key, value in self.exception_handlers.items():
if key in (500, Exception):
Expand Down Expand Up @@ -170,8 +174,8 @@ def add_middleware(

def add_exception_handler(
self,
exc_class_or_status_code: typing.Union[int, typing.Type[Exception]],
handler: typing.Callable,
exc_class_or_status_code: _ExcKey,
handler: _ExcHandler,
) -> None: # pragma: no cover
self.exception_handlers[exc_class_or_status_code] = handler
self.middleware_stack = self.build_middleware_stack()
Expand Down
2 changes: 1 addition & 1 deletion tests/test_applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ async def websocket_endpoint(session):
Middleware(TrustedHostMiddleware, allowed_hosts=["testserver", "*.example.org"])
]

app = Starlette(
app = Starlette( # type: ignore[type-var]
routes=[
Route("/func", endpoint=func_homepage),
Route("/async", endpoint=async_homepage),
Expand Down