I was wondering what's the best way to restrict a GenericModel to only accept being parameterized by certain data types.
For example (using the Response class from the docs), I would like to allow Response[int] and Response[float] and forbid all else (or the other way around forbid Response[int] and Response[float] and allow all else)
You can restrict a TypeVar to specific types: TypeVar('T', int, float). I am fairly certain the opposite is not possible.
hmm it seems that the constraint is not actually enforced
from typing import Generic
from typing import TypeVar
from pydantic.generics import GenericModel
NumberT = TypeVar("T", int, float)
class Foo(GenericModel, Generic[NumberT]):
bar: NumberT
Foo[int](bar=2) # works fine as it should
Foo[str](bar="asdf") # also works fine, but it shouldn't :(
This will be fixed in https://github.com/samuelcolvin/pydantic/pull/1104; sorry I just haven't had time to get around to finishing it, it should be done soon.
Most helpful comment
This will be fixed in https://github.com/samuelcolvin/pydantic/pull/1104; sorry I just haven't had time to get around to finishing it, it should be done soon.