Skip to content

Improve typing for add_exception_handler#3219

Open
Ragug wants to merge 8 commits into
Kludex:mainfrom
Ragug:improve-exception-handler-typing
Open

Improve typing for add_exception_handler#3219
Ragug wants to merge 8 commits into
Kludex:mainfrom
Ragug:improve-exception-handler-typing

Conversation

@Ragug

@Ragug Ragug commented Apr 4, 2026

Copy link
Copy Markdown

Summary

This improves type inference for add_exception_handler by allowing handlers
to accept specific Exception subclasses instead of only Exception.

For example, the following now type-checks correctly:

class MyException(Exception):
    ...

def handler(request: Request, exc: MyException) -> Response:
    ...

app.add_exception_handler(MyException, handler)

This is achieved using overloads while preserving the existing runtime behavior.

No runtime changes are introduced.

Note: This PR intentionally does not attempt to improve typing for the
exception_handlers mapping, as its key-dependent typing cannot be fully
expressed in Python's type system.

Related discussion: #2403

Checklist

  • I understand that this PR may be closed in case there was no previous discussion.
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.

Ragug added 6 commits April 4, 2026 03:55
Allow handlers to accept specific Exception subclasses using overloads.
This improves type inference without changing runtime behavior.
- Use @overload to differentiate between Exception types and status code integers.
- Synchronize parameter names to fix mypy [misc] implementation errors.
- Broaden implementation handler signature to support generic Exception types.
@Ragug

Ragug commented Apr 5, 2026

Copy link
Copy Markdown
Author

Hi @Kludex, I’d appreciate it if you could review this and let me know if any changes are needed. Looking forward to your feedback.

@nullwiz nullwiz mentioned this pull request Apr 17, 2026
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants