Skip to content

cls is None in validator when validate_assignment is True #1172

@espdev

Description

@espdev

Bug

When we set config value validate_assignment to True and define custom validator for a field, and try to set value for the field, we get None in cls argument in the validator method instead of expected model class object. In my case I want to store some data in model class object that I want to use for validation and I cannot get it via cls because cls is None. Of course I can use model class object directly, but this behavior is ambiguous and looks like a bug anyway.

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

         pydantic version: 1.3
        pydantic compiled: False
             install path: C:\Users\espdev\AppData\Local\pypoetry\Cache\virtualenvs\ms3eI9mF-py3.8\Lib\site-packages\pydantic
           python version: 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)]
                 platform: Windows-10-10.0.18362-SP0
 optional deps. installed: []

A minimal example:

from pydantic import BaseModel, StrictStr, validator

class Model(BaseModel):
    name: StrictStr

    class Config:
        validate_assignment = True

    @validator('name')
    def _validate_foo(cls, value):
        if cls is None:
            raise ValueError('cls is None')
        return value

if __name__ == '__main__':
    m = Model(name='hello')  # OK
    m.name = 'goodbye'       # <-- ValidationError "cls is None"
pydantic.error_wrappers.ValidationError: 1 validation error for Model
name
  cls is None (type=value_error)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions