Search code examples
pythonpython-3.xpydantictyping

How to enforce Pydantic error raising for wrong generic types


Below you can see my code

from pydantic import BaseModel
from typing import TypeVar, Generic

T = TypeVar('T')

class GenericItem(BaseModel, Generic[T]):
    item: T

# Examples of using GenericItem
string_item = GenericItem[str](item="example")
int_item = GenericItem[int](item=42)

# This will raise a validation error because 'item' is expected to be of type 'int'
try:
    invalid_item = GenericItem[int](item="invalid")
except Exception as e:
    print(f"Validation error: {e}")

I want to use a generic value T and I have a field item of that value.

When I create GenericItem[int](item="invalid") it should throw an error, because the input should be int, but it is an str. Yet, no error shows up.

How can I make that possible, such that in this case it would just accept input of the specified type T?


Solution

  • I think it was the intended feature in v1.10.x.

    As I commented, after V2, that works fine. But in v1.10x, you need to use GenericModel

    from pydantic.generics import GenericModel  # Import `GenericModel` instead of `BaseModel`
    from typing import TypeVar, Generic
    
    T = TypeVar('T')
    
    class GenericItem(GenericModel, Generic[T]):  # use `GenericModel`
        item: T
    
    # Examples of using GenericItem
    string_item = GenericItem[str](item="example")
    int_item = GenericItem[int](item=42)
    
    # This will raise a validation error because 'item' is expected to be of type 'int'
    try:
        invalid_item = GenericItem[int](item="invalid")
    except Exception as e:
        print(f"Validation error: {e}")
    

    Run it; you might have got

    Validation error: 1 validation error for GenericItem[int]
    item
      value is not a valid integer (type=type_error.integer)
    

    Ref: https://docs.pydantic.dev/1.10/usage/models/#generic-models