Python 3.9 - 我有以下模块:
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)
Run Code Online (Sandbox Code Playgroud)
当我导入这个模块时,它会引发NameError: name 'Optional' is not defined. 我可以删除该if TYPE_CHECKING部分,但我知道这是最佳实践(例如,如果我使用自己的类型,则可以防止循环导入)。当我删除B.update_forward_refs()呼叫时,它会引发pydantic.errors.ConfigError: field "foo" not yet prepared so type is still a ForwardRef, you might need to call B.update_forward_refs(). …