Pydantic Field constraint does not trigger with Optional type

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″).

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật