Skip to content

False positive on Starlette middleware registration #1635

@Asaf31214

Description

@Asaf31214

Summary

Register any FastAPI middleware, custom or built-in:

app = FastAPI()
app.add_middleware(NoStoreAuthMiddleware) # custom, subclass of BaseHTTPMiddleware
app.add_middleware(RateLimitMiddleware) # custom, subclass of BaseHTTPMiddleware
app.add_middleware( 
    CORSMiddleware, # built-in middleware, from fastapi.middleware.cors
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
) 

run:
ty check, without any specified rules at pyproject.toml

No issue until [email protected] (expected result)
But for versions [email protected] and [email protected] (current latest):

error[invalid-argument-type]: Argument to bound method `add_middleware` is incorrect
  --> main.py:31:20
   |
30 | app = FastAPI(default_response_class=ORJSONResponse, lifespan=lifespan)
31 | app.add_middleware(NoStoreAuthMiddleware)
   |                    ^^^^^^^^^^^^^^^^^^^^^ Expected `_MiddlewareFactory[Unknown]`, found `<class 'NoStoreAuthMiddleware'>`
32 | app.add_middleware(RateLimitMiddleware)
33 | app.add_middleware(ExceptionHandlerMiddleware)
   |
info: Method defined here
   --> .venv/lib/python3.14/site-packages/starlette/applications.py:118:9
    |
116 |         self.router.host(host, app=app, name=name)  # pragma: no cover
117 |
118 |     def add_middleware(
    |         ^^^^^^^^^^^^^^
119 |         self,
120 |         middleware_class: _MiddlewareFactory[P],
    |         --------------------------------------- Parameter declared here
121 |         *args: P.args,
122 |         **kwargs: P.kwargs,
    |
info: rule `invalid-argument-type` is enabled by default

same error for all 3 middlewares registered here.

this is also mentioned at issue #1564 by @dmytro-GL here

Version

ty 0.0.1-alpha.27

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions