Pydantic: Restrict GenericModel to certain data types

Created on 25 Dec 2019  路  3Comments  路  Source: samuelcolvin/pydantic

Question

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)

question

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.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings