slowapi icon indicating copy to clipboard operation
slowapi copied to clipboard

mypy error: type of `_rate_limit_exceeded_handler` is incompatible with latest starlette

Open eggplants opened this issue 1 year ago • 1 comments

Describe the bug

Type annotation of Slowapi's _rate_limit_exceeded_handler is not matched with latest starlette annotations due to lack of consideration of Awaitable.

# _rate_limit_exceeded_handler
Callable[[Request, RateLimitExceeded], Response]

# Argument 2 to "add_exception_handler" of "Starlette"
Callable[[Request, Exception], Response | Awaitable[Response]] |
Callable[[WebSocket, Exception], Awaitable[None]]

After updating starlette to the latest it raises error.

https://results.pre-commit.ci/run/github/689781832/1707152173.Vq3hZuM6QlSEMvoYNuM7NQ

locloc/main.py:31: error: Argument 2 to "add_exception_handler" of "Starlette"
has incompatible type "Callable[[Request, RateLimitExceeded], Response]";
expected
"Union[Callable[[Request, Exception], Union[Response, Awaitable[Response]]], Callable[[WebSocket, Exception], Awaitable[None]]]"
 [arg-type]
    app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_hand...

To Reproduce

In 6547679:

from fastapi import FastAPI
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

app = FastAPI()
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
docker run --rm -it python:3.12 bash
pip install fastapi==0.109.2 mypy
pip install git+https://github.com/laurentS/slowapi.git@6547679
cat <<'A'>app.py
from fastapi import FastAPI
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

app = FastAPI()
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
A
mypy --strict app.py
root@bf2b20276907:/# mypy --strict app.py
app.py:6: error: Argument 2 to "add_exception_handler" of "Starlette" has incompatible type "Callable[[Request, RateLimitExceeded], Response]"; expected "Callable[[Request, Exception], Response | Awaitable[Response]] | Callable[[WebSocket, Exception], Awaitable[None]]"  [arg-type]

Expected behavior Mypy says Success: no issues found in 1 source file under strict mode.

Screenshots image

Your app (please complete the following information):

fastapi or starlette?

fastapi

Version?

https://github.com/eggplants/locloc/tree/f737fae958571180e61e5e62f076b53b1c6ff585

slowapi version (have you tried with the latest version)?

6547679

Additional context

Starlette has started to check typing in mypy strict mode since v0.31.0. See https://github.com/encode/starlette/pull/2180

eggplants avatar Feb 11 '24 15:02 eggplants

I'm running into this issue as well

lukecivantos avatar Mar 11 '24 18:03 lukecivantos