-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
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 ourterms of serviceand privacy statement.We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pydantic v2, dataclasses, UUID, and__annotations__
#10007
Comments
Maybe using an id of type str can solve the problem... class Item: |
It looks like forward references are resolved from namespaces built from the previous 2 frames |
You could use Pydantic's dataclass extension. It doesn't just give you the same data validation features but also fix your issue. from__future__importannotations
fromtypingimportList,Union
importuuid
frompydantic.dataclassesimportdataclass,Field
@dataclass
classItem:
id:uuid.UUID
name:str
price:float
tags:List[str]=Field(default_factory=list)
description:Union[str,None]=None
tax:Union[float,None]=None
item=Item(
id=uuid.uuid4(),
name="John",
price=666.66,
)
print(item)
# Item(id=UUID('c399d5c9-c2bf-4e5f-94f9-21a7a5f78610'), name='John', price=666.66, tags=[], description=None, tax=None) |
This would need to be handled on the Pydantic side (or at least require some input/changes from them).pydantic/pydantic#7111 As@harunyasarmentions, there's a simple workaround, to use Pydantic's flavor of frompydantic.dataclassesimportdataclass I understand this is one of the things that begs for PEP 649 (Deferred Evaluation Of Annotations Using Descriptors) that will hopefully come to Python 3.13 🎉 |
I'm not sure if this is related, but I'm hitting:
I've installed the lastest fastapi and pydantic, so I suspect this is a new issue! I think probably the only way to fix this now is to fall back to a much older pydantic. Also@tiangoloyour use of emojis in commits is pure 🔥 I love looking at your code! 🙌 |
I actually can't find a pairing that works! I'm going to look in an older container (where it did work) and cross my fingers I can reproduce that! 🤞 |
Yeah this is strange - when I go to previously working versions I still get:
|
When I tried to update from:
A route that uses a stdlib
fromother.pathimportMyDataclass
@router.post("/route/")
defroute()->MyDataclass:
... In my case, it appears that if any of the nested The reason we are using There are also weird things that can happen with manually stringified type annotations: |
You can use create your own data model like below: from__future__importannotations
importuuid
fromdataclassesimportdataclass,field
fromtypingimportList,Union
fromfastapiimportFastAPI
frompydanticimportBaseModel
classItem(BaseModel):
id:uuid.UUID
name:str
price:float
tags:List[str]=field(default_factory=list)
description:Union[str,None]=None
tax:Union[float,None]=None
app=FastAPI()
@app.get("/items/next",response_model=Item)
asyncdefread_next_item():
return{
"name":"Island In The Moon",
"price":12.99,
"description":"A place to be be playin' and havin' fun",
"tags":["breater"],
} |
Hi~have you found a solution? |
I think a bump should solve the issue - either FastAPI or Pydantic. |
Right. I have solved this issue by "pip install pydantic==1.9.0" |
I said bump, not downgrade. 😅 |
This might also be related. Python 3.11x plus latest FastApi and Pydantic V2. Replaced
|
I'm just chiming into this conversation to share an issue I had with this recently and what I did to solve it in case it helps with someone else chasing this down. I have separated my models, controllers and routers into separate modules - I was trying to create a dependable to extract a provided auth token, pull the appropriate user from my db and then return it as a pydantic User object. This meant that I wanted to reference the dependable in my router module as a method of the controller class held as an instance variable. So something like this:
This resulted in an error as below: Error log
So I figured there was an issue with how the type forward refs were being resolved and I quoted the User references. This led to a very similar error but with So, lastly I tried removing the
This now seems to work fine. I presume the issue is something to do with when Annotated gets resolved as opposed to defining it as a standard default value. Certainly did have me floundering for a while, I would loved to have seen this mentioned somewhere in the otherwise flawless FastAPI docs (please point me to it if it's already there). |
I think my problem is related to this issue, all code comes from document but I can not resolve it. |
Hello 👋🏻 Had a similar issue which was caused by having fromfutureimport__annotations__ together with FastAPI dependency injection. It would result in a weird error
where FastAPI would error on all injected dependencies. Removing the import from Thanks. |
Privileged issue
Issue Content
The combination of using:
from future import __annotations__
seems to break in a strange way.
This was original reported in this discussion by@sanzoghenzo:#9709 (comment)
In particular the comment by@raddevonwith the minimal example by@fantix:
Starting FastAPI with that breaks with an error of:
log
I still don't know if it's about which of these multiple interacting parts, I'm creating this issue to keep track of it.
The text was updated successfully, but these errors were encountered: