Home > Software engineering >  Checking input data types in pydantic
Checking input data types in pydantic

Time:05-30

Is there a way to check the datatypes of the input variables natively in pydantic, like:

class ModelParameters(BaseModel):
    str_val: str
    int_val: int
    wrong_val: int


test = ModelParameters(**dict({
    "str_val":"test",
    "int_val":1,
    "wrong_val":1.2}))

Which should throw an error for wrong_val.

CodePudding user response:

Pydantic does a handful of implicit conversion, particularly on primitive types like int, str, or float. The reason behind this behaviour is discussed here.

So indeed, with a class like this:

class ModelParameters(BaseModel):
    str_val: str
    int_val: int
    wrong_val: int

You can absolutely instantiate an object like that:

test = ModelParameters(**dict({
    "str_val": 123,
    "int_val": "1",
    "wrong_val": 1.2}))

test
# ModelParameters(str_val='123', int_val=1, wrong_val=1)

But you do have the option to enforce type checking. What you need to do, is to use StrictStr, StrictFloat and StrictInt as a type-hint replacement for str, float and int. You'll find them in pydantic.types. In your case:

from pydantic.types import StrictStr, StrictInt

class ModelParameters(BaseModel):
    str_val: StrictStr
    int_val: StrictInt
    wrong_val: StrictInt

Now, if you try the same instantiation, you'll see validation errors all around the place, like you'd expect:

test = ModelParameters(**dict({
    "str_val": 123,
    "int_val": "1",
    "wrong_val": 1.2}))
pydantic.error_wrappers.ValidationError: 3 validation errors for ModelParameters
str_val
  str type expected (type=type_error.str)
int_val
  value is not a valid integer (type=type_error.integer)
wrong_val
  value is not a valid integer (type=type_error.integer)
  • Related