Afternoon,
Is it possible in python, given a function that takes a generic sequence of objects, to type it so that the list must be of only one type and not a union of multiple children?
for code like this...
from collections.abc import Sequence
from pydantic import BaseModel, ConfigDict
class ExampleModel(BaseModel):
id: int
name: str
model_config = ConfigDict(validate_default=True)
class NewModel(BaseModel):
id: int
name: str
def func[T: BaseModel](b: Sequence[T]) -> T:
return b[0]
l1 = [ExampleModel(id=1, name="Test1"), ExampleModel(id=2, name="Test2")]
l2 = [NewModel(id=3, name="NewTest1"), NewModel(id=4, name="NewTest2")]
l3 = [ExampleModel(id=5, name="Test3"), NewModel(id=6, name="NewTest3")]
print(func(l1))
print(func(l2))
print(func(l3))
Is there a way to type func so that b is a sequence of one and only one child of BaseModel i.e. l1 and l2 are valid but l3 will raise a pyright/mypy error (not necessarily a runtime error).
Note this must be generic to any child of BaseModel (or itself) so solutions like
def func(b: Sequence[ExampleModel] | Sequence[NewModel]) -> T:
return b[0]
Are inadequate.