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)
Thanks so much for reporting, amazingly it looks like this has been around for ages and no one noticed, should be fixed in #1174 which I'll release asap.
Most helpful comment
Thanks so much for reporting, amazingly it looks like this has been around for ages and no one noticed, should be fixed in #1174 which I'll release asap.