Created
January 17, 2020 12:43
-
-
Save espdev/b2cf786a84dcc31762f4288ad3a92111 to your computer and use it in GitHub Desktop.
cls is None
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
from pydantic import BaseModel, validator | |
class MyModel(BaseModel): | |
name: Optional[str] | |
class Config: | |
validate_assignment = True | |
@validator('name', always=True) | |
def _validate_name(cls, value): | |
if value is None: | |
return 'hello' | |
if cls is None: | |
raise ValueError('cls is None') | |
return value | |
if __name__ == '__main__': | |
m = MyModel() | |
assert m.name == 'hello' | |
m.name = 'goodbye' # <-- error "cls is None" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Traceback (most recent call last): | |
File "C:/Users/espdev/.PyCharm2019.3/config/scratches/scratch_17.py", line 24, in <module> | |
m.name = 'goodbye' | |
File "C:\Users\espdev\AppData\Local\pypoetry\Cache\virtualenvs\lol-ms3eI9mF-py3.8\lib\site-packages\pydantic\main.py", line 289, in __setattr__ | |
raise ValidationError([error_], type(self)) | |
pydantic.error_wrappers.ValidationError: 1 validation error for MyModel | |
name | |
cls is None (type=value_error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment