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
show_error_codes = True
Expand Down
39 changes: 23 additions & 16 deletions starlette/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@
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]]
]
_ExcDict = typing.Dict[_ExcKey, _ExcHandler]
antonagestam marked this conversation as resolved.
Show resolved Hide resolved
_C = typing.TypeVar("_C", bound=typing.Callable)


class Starlette:
"""
Expand Down Expand Up @@ -43,12 +57,7 @@ def __init__(
debug: bool = False,
routes: typing.Sequence[BaseRoute] = None,
middleware: typing.Sequence[Middleware] = None,
exception_handlers: typing.Mapping[
typing.Any,
typing.Callable[
[Request, Exception], typing.Union[Response, typing.Awaitable[Response]]
],
] = None,
exception_handlers: typing.Mapping[_ExcKey, _ExcHandler] = None,
on_startup: typing.Sequence[typing.Callable] = None,
on_shutdown: typing.Sequence[typing.Callable] = None,
lifespan: typing.Callable[["Starlette"], typing.AsyncContextManager] = None,
Expand All @@ -64,7 +73,7 @@ def __init__(
self.router = Router(
routes, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan
)
self.exception_handlers = (
self.exception_handlers: _ExcDict = (
{} if exception_handlers is None else dict(exception_handlers)
)
self.user_middleware = [] if middleware is None else list(middleware)
Expand All @@ -73,9 +82,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: _ExcDict = {}
antonagestam marked this conversation as resolved.
Show resolved Hide resolved

for key, value in self.exception_handlers.items():
if key in (500, Exception):
Expand Down Expand Up @@ -111,7 +118,7 @@ def debug(self, value: bool) -> None:
self._debug = value
self.middleware_stack = self.build_middleware_stack()

def url_path_for(self, name: str, **path_params: typing.Any) -> URLPath:
def url_path_for(self, name: str, **path_params: str) -> URLPath:
return self.router.url_path_for(name, **path_params)

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
Expand All @@ -135,8 +142,8 @@ def add_middleware(self, middleware_class: type, **options: typing.Any) -> None:

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:
self.exception_handlers[exc_class_or_status_code] = handler
self.middleware_stack = self.build_middleware_stack()
Expand All @@ -162,9 +169,9 @@ def add_websocket_route(
self.router.add_websocket_route(path, route, name=name)

def exception_handler(
self, exc_class_or_status_code: typing.Union[int, typing.Type[Exception]]
) -> typing.Callable:
def decorator(func: typing.Callable) -> typing.Callable:
self, exc_class_or_status_code: _ExcKey
) -> typing.Callable[[_C], _C]:
def decorator(func: _C) -> _C:
adriangb marked this conversation as resolved.
Show resolved Hide resolved
self.add_exception_handler(exc_class_or_status_code, func)
return func

Expand Down