'Use the original value when validating an assignment to a pydantic object
Is it possible to have pydantic look at the original value of an attribute when validating an assignment? I want to create a schema where a field can start off None, and can be set to a string, but can then never be modified again. Something like
class M(pydantic.BaseModel):
maybe_str: Optional[str] = None
@non_existent_validate_on_assignment_decorator("maybe_str")
def permit_assignment_unless_maybe_str_is_already_set(self, v):
assert self.maybe_str is None
return v
In my dream, m = M(); m.maybe_str = "x" would be ok but m = M(maybe_str="y"); m.maybe_str = "x" would raise an AssertionError.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
