Python 3.9 - I have the following module:
from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic import BaseModel
if TYPE_CHECKING:
from typing import Optional
class A(BaseModel):
id: int
class Config:
orm_mode = True
class B(A):
foo: C
class C(A):
bar: Optional[str]
C.update_forward_refs()
c = C(id=1, bar='bar')
b = B(id=2, foo=c)
When I import this module it raises NameError: name 'Optional' is not defined
. I can remove the if TYPE_CHECKING
part, but I understand that this is the best practice (to prevent circular imports if I use my own types for example).
When I remove the B.update_forward_refs()
call it raises pydantic.errors.ConfigError: field "foo" not yet prepared so type is still a ForwardRef, you might need to call B.update_forward_refs().
Any idea how to overcome this?