-
First Check
Commit to Help
Example Codefrom __future__ import annotations
from typing import Annotated
from fastapi import Depends, FastAPI, Request
app = FastAPI()
# Function-based dependency (works fine)
def fetch_ip(request: Request) -> str:
return request.client.host
IP = Annotated[str, Depends(fetch_ip)]
# Class-based dependency (does not work)
class IPFetcher:
def __call__(self, request: Request) -> str:
return request.client.host
IP = Annotated[str, Depends(IPFetcher())] # This raises an error
@app.get("/ip")
async def ask_ip(ip: IP):
return {"your IP address is": ip}
if __name__ == "__main__":
from fastapi.testclient import TestClient
with TestClient(app) as client:
response = client.get("/ip")
response.raise_for_status()
print(response.json())DescriptionObservationWhen using Expected behaviourBoth function-based and class-based dependencies should work consistently, regardless of WorkaroundRemoving Operating SystemLinux Operating System DetailsNo response FastAPI Version0.115.8 Pydantic Version2.10.6 Python VersionPython 3.11.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
When using As Workaround, You could also add a class attribute |
Beta Was this translation helpful? Give feedback.
You're right, adding class variable
__globals__ = globals()may resolve this issue:This workaround works fine regradless of the line
from __future__ import annotations.