Pydantic: Forbid floats on integer fields?

Created on 4 Oct 2019  路  4Comments  路  Source: samuelcolvin/pydantic

Question, Suggestion

Now if you pass float to int field, it will be converted to int without any error or warning. That could cause some unexpected behavior.

import pydantic

class MyModel(pydantic.BaseModel):
    a: int

m = MyModel(a=3.4)
print(m.a)  # 3

What I would expect to happen is:

m = MyModel(a=3.4)

Traceback (most recent call last):
    ...
pydantic.error_wrappers.ValidationError: 1 validation error
a
  value is not a valid integer (type=type_error.integer)
question

All 4 comments

There is a note addressing this in the new docs:

Data Conversion

pydantic may cast input data to force it to conform model field types. This may result in data being lost, take the following example:

from pydantic import BaseModel

class Model(BaseModel):
    a: int
    b: float
    c: str

print(Model(a=3.1415, b=' 2.72 ', c=123).dict())
#> {'a': 3, 'b': 2.72, 'c': '123'}

(This script is complete, it should run "as is")

This is a deliberate decision of pydantic, and in general it's the most useful approach, see here for a longer discussion of the subject.

Also, there is a StrictInt type in pydantic.types (at least that's what it's called in v1, not sure if/where it exists in 0.32.2) that can be used to prevent floats if that's what you want.

Thanks for quick reply and solution! Checked for StrictInt earlier without luck, will look for it in current versions.

It may not exist in 0.32.2 at all -- but you can probably copy the code as a workaround until v1 is released!

Was this page helpful?
0 / 5 - 0 ratings