Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Pydantic field while setting value

A Pydantic class that has confloat field cannot be initialised if the value provided for it is outside specified range. But when setting this field at later stage (my_object.constrained_field = <big_value>) the new value is not validated.

from pydantic import BaseModel, confloat

class testClass(BaseModel):
    a: confloat(gt=0.0, lt=10.0)

x = testClass(a=2.0) # OK

# x = testClass(a=20.0) # ERROR: outside limits

x.a = 40.0 # OK despite outside limits

print(x.a) # prints '40.0'

Is this possible to validate new value when setting member, so that calling x.a = 40.0 in the example above will raise an exception?

If not -is there any workaround like getting validator method out of the class field?

like image 558
MaciekS Avatar asked May 13 '26 13:05

MaciekS


1 Answers

Use validate_assignment on Config.

like image 85
SColvin Avatar answered May 17 '26 18:05

SColvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!