I'm trying to have a field in one Pydantic model accept any of a set of BaseModel-derived classes or subclasses that I define separately. Reading the docs here, I naively did the below, which failed; I then realised that I'd misread the docs and that in this scenario "a field may only accept classes (not instances)", and also that Foo and Bar in that example don't derive from BaseModel themselves (is that important?).
I'm guessing that I'm just misconceiving this from the start, so my question: is there a correct way to do what I'm trying to do without using a Union on the subclasses, or some other way entirely that's better?
Bonus question: what's a common usecase for only being able to accept classes and not instances?
MRE:
from pydantic import BaseModel
from typing import Type, Union
class Foo(BaseModel):
pass
class Bar(Foo):
pass
class Baz(Foo):
pass
class Container(BaseModel):
some_foo: Type[Foo] # this fails
# this will run successfully --> some_foo: Union[Bar, Baz]
b = Baz()
c = Container(some_foo = b)
# Traceback (most recent call last):
# File "mre.py", line 20, in <module>
# c = Container(some_foo = b)
# File "pydantic/main.py", line 400, in pydantic.main.BaseModel.__init__
# pydantic.error_wrappers.ValidationError: 1 validation error for Container
# some_foo
# subclass of Foo expected (type=type_error.subclass; expected_class=Foo)