5

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?

MaciekS
  • 401
  • 8
  • 18

1 Answers1

12

Use validate_assignment on Config.

SColvin
  • 11,584
  • 6
  • 57
  • 71