9

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?

1 Answer 1

17

Use validate_assignment on Config.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you see any reason why validate_assignment is not True by default?
It has a performance impact and I would argue that the majority of cases wouldn't expect it to be on by default.
curious- does this cause root validators to be re-triggered?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.