Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate_assignment does not work with root_validator #1971

Closed
caldwellshane opened this issue Oct 5, 2020 · 1 comment · Fixed by #1972
Closed

validate_assignment does not work with root_validator #1971

caldwellshane opened this issue Oct 5, 2020 · 1 comment · Fixed by #1972
Labels

Comments

@caldwellshane
Copy link

@caldwellshane caldwellshane commented Oct 5, 2020

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.5.1
            pydantic compiled: True
                 install path: /Users/shane/repos/domain-model-specification/Python/.venv/lib/python3.7/site-packages/pydantic
               python version: 3.7.7 (default, Jul 18 2020, 22:28:30)  [Clang 11.0.3 (clang-1103.0.32.62)]
                     platform: Darwin-19.6.0-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

Minimal Example

I'd like to enforce a condition on a whole model during arbitrary changes in its state:

from pydantic import BaseModel, root_validator

class Example(BaseModel):
    current_value: float
    max_value: float

    class Config:
        validate_assignment = True

    @root_validator
    def current_lessequal_max(cls, values):
        current_value = values.get("current_value")
        max_value = values.get("max_value")
        assert abs(current_value) <= max_value, f"current_value cannot be greater than max_value"
        return values

Based on my reading of the docs I'd expect this to fail validation if I set current_value above max_value, or set max_value below current_value, on an existing instance. Is that not the intended behavior?

Thanks for an excellent library!

PrettyWood added a commit to PrettyWood/pydantic that referenced this issue Oct 6, 2020
PrettyWood added a commit to PrettyWood/pydantic that referenced this issue Oct 6, 2020
@PrettyWood
Copy link
Collaborator

@PrettyWood PrettyWood commented Oct 6, 2020

Hello @caldwellshane

I agree with you the behaviour should be the same as a regular validator.
I opened a PR to fix this issue. We will see if it is accepted ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

2 participants