I would like to instantiate a typing Union
of two classes derived from pydantic.BaseModel
directly. However I get a TypeError: Cannot instantiate typing.Union
.
All examples I have seen declare Union
as an attribute of a class (for example here).
Below is the minimum example I would like to use.
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
Is there a way to achieve this?
Here is the error I obtain
---------------------------------------------------------------------------
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