我想实例化两个直接派生的类的类型。Union
pydantic.BaseModel
但是我得到一个TypeError: Cannot instantiate typing.Union
.
我见过的所有示例都声明Union
为类的属性(例如此处)。
下面是我想使用的最小示例。
from pydantic import BaseModel
from typing import Union
class A(BaseModel):
a: int
class B(A):
b: int
class C(A):
c: str
MyUnion = Union[B, C, A]
mu = MyUnion(a=666, c='foo') # This command throws the TypeError
有没有办法做到这一点?
这是我得到的错误
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-8163e3490185> in <module>
----> 1 MyUnion()
c:\program files\python37\lib\typing.py in __call__(self, *args, **kwargs)
668 raise TypeError(f"Type {self._name} cannot be instantiated; "
669 f"use {self._name.lower()}() instead")
--> 670 result = self.__origin__(*args, **kwargs)
671 try:
672 result.__orig_class__ = self
c:\program files\python37\lib\typing.py in __call__(self, *args, **kwds)
327
328 def __call__(self, *args, **kwds):
--> 329 raise TypeError(f"Cannot instantiate {self!r}")
330
331 def __instancecheck__(self, obj):
TypeError: Cannot instantiate typing.Union