update_forward_refs()对于动态创建的模型失败



当我通过create_model()动态创建一个pydantic模型时,在某些情况下update_forward_refs()找不到相关的定义。

如此:

from typing import List, Union
from pydantic import BaseModel
class Foo(BaseModel):
foo: List["Bar"]
Bar = Union[Foo, int]
Foo.update_forward_refs()

但以下,我相信这应该是等价的,失败NameError:

from typing import List, Union
from pydantic import create_model, BaseModel
Foo = create_model("Foo", foo=(List["Bar"], ...))
Bar = Union[Foo, int]
Foo.update_forward_refs()

导致:

Traceback (most recent call last):
File "test_forward_ref.py", line 11, in <module>
Foo.update_forward_refs()
File "pydanticmain.py", line 832, in pydantic.main.BaseModel.update_forward_refs
File "pydantictyping.py", line 382, in pydantic.typing.update_field_forward_refs
or class checks.
File "pydantictyping.py", line 62, in pydantic.typing.evaluate_forwardref
'MutableSet',
File "C:UsersIan.condaenvstsolibtyping.py", line 518, in _evaluate
eval(self.__forward_code__, globalns, localns),
File "<string>", line 1, in <module>
NameError: name 'Bar' is not defined

重要的是"Bar"在字段foo的注释中的List中引用。如果字段foo的注释直接为"bar";那就没问题了。

有人能帮我解决这个问题吗?我还需要做什么?

Python 3.8和pydantic 1.8.2

update_forward_refs()允许**localns: Any参数。似乎在这种情况下,你可以传递Bar=Barupdate_forward_refs(),它将工作:

from typing import List, Union
from pydantic import create_model
Foo = create_model("Foo", foo=(List["Bar"], ...))
Bar = Union[Foo, int]
Foo.update_forward_refs(Bar=Bar)
print(Foo(foo=[1, Foo(foo=[2])]))

输出:

foo=[1, Foo(foo=[2])]

最新更新