I have a class with some attributes I want to constrain to a range.
I did this with pydantics’ Field constraint (e.g. ge=0), and expected the constraint to be enforced.
However, validation does not trigger as expected, and an invalid value is set. Here is a small working example:
from typing import Annotated, Optional, List
from pydantic import Field, BaseModel, ValidationError
import pytest
class MyClass(BaseModel):
# My implementation that fails. The Field constraint does not work as expected.
f1: Optional[Annotated[float | List[float], Field(ge=0)]] = None
# Modified to work.
f2: Annotated[float | List[float], Field(ge=0)] = None
# To demonstrate that the inner type is not the root cause of failing check.
f3: Optional[Annotated[float,Field(ge=0)]] = None
def test_valid_input():
# Valid input, passes as expected.
myclass = MyClass(f1=1, f2=1)
assert myclass.f1 == myclass.f2 == 1
### THIS PASSES ###
def test_invalid_input_successful_validation():
# Valid f1, invalid f2 --> raises ValidationError as expected.
with pytest.raises(ValidationError):
myclass = MyClass(f1=1,f2=-1)
### THIS PASSES ###
def test_invalid_input_failing_validation():
# Valid f2, invalid f1 --> Expect to raise ValidationError, but it lets the invalid value through.
with pytest.raises(ValidationError):
myclass = MyClass(f1=-1,f2=1)
### THIS FAILS ###
### myclass.f1 == -1 ###
Expected a ValidationError to be thrown at the invalid f1=-1, but instead, the value was accepted.
The tests above demonstrate this and also that Optional
might be the culprit.
What version of Python are you using? With Python 3.13rc1, your code seems to work as written. First, all the tests pass:
$ pytest -v test_models.py
========================================================================== test session starts ===========================================================================
platform linux -- Python 3.12.5, pytest-8.3.3, pluggy-1.5.0 -- /home/lars/tmp/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/lars/tmp/python
collected 3 items
models.py::test_valid_input PASSED [ 33%]
models.py::test_invalid_input_successful_validation PASSED [ 66%]
models.py::test_invalid_input_failing_validation PASSED [100%]
=========================================================================== 3 passed in 0.07s ============================================================================
And we can manually demonstrate the expected behavior:
$ python -i test_models.py
>>> x = MyClass(f1=-1,f2=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/main.py", line 212, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for MyClass
f1
Input should be greater than or equal to 0 [type=greater_than_equal, input_value=-1, input_type=int]
For further information visit https://errors.pydantic.dev/2.9/v/greater_than_equal
>>> x = MyClass(f1=1,f2=-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/main.py", line 212, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for MyClass
f2
Input should be greater than or equal to 0 [type=greater_than_equal, input_value=-1, input_type=int]
For further information visit https://errors.pydantic.dev/2.9/v/greater_than_equal
There is however a problem with your code; you can’t apply the ge=0
validation to List[float]
; that gets you:
>>> x = MyClass(f1=[1])
Traceback (most recent call last):
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/_internal/_validators.py", line 265, in validator
if not predicate(x, constraint_value):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/_internal/_validators.py", line 278, in <lambda>
'ge': create_constraint_validator('ge', lambda x, ge: x >= ge, 'greater_than_equal'),
^^^^^^^
TypeError: '>=' not supported between instances of 'list' and 'int'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/main.py", line 212, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/_internal/_validators.py", line 270, in validator
raise TypeError(f"Unable to apply constraint '{constraint_id}' to supplied value {x}")
TypeError: Unable to apply constraint 'ge' to supplied value [1.0]
If you want to support both lists and single values, consider this instead:
from typing import Annotated
from pydantic import BaseModel, Field
positiveFloat = Annotated[float, Field(ge=0)]
class OtherClass(BaseModel):
f1: positiveFloat | list[positiveFloat] | None = None
f2: positiveFloat | list[positiveFloat] | None = None
f3: positiveFloat | None = Field(None, ge=0)
Here we’re creating an Annotated
floating point type so that our fields can either be a single positiveFloat
value or a list of postiveFloat
values; that gets us what we want:
>>> OtherClass(f1=[-1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lars/tmp/python/.venv/lib/python3.12/site-packages/pydantic/main.py", line 212, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 2 validation errors for OtherClass
f1.constrained-float
Input should be a valid number [type=float_type, input_value=[-1], input_type=list]
For further information visit https://errors.pydantic.dev/2.9/v/float_type
f1.list[constrained-float].0
Input should be greater than or equal to 0 [type=greater_than_equal, input_value=-1, input_type=int]
For further information visit https://errors.pydantic.dev/2.9/v/greater_than_equal
>>>
>>> OtherClass(f1=[1])
OtherClass(f1=[1.0], f2=None, f3=None)
Note also that I’m saving some clutter here by using native types (list
, etc) rather than imports from typing
(List
, Optional
). This should work with any reasonably modern Python (which I think in this case means “anything >=
3.9″).