Постановка проблемы:
У меня есть сотни py-файлов, которые определяют pydantic-схему. Внезапно мне нужно рассматривать пустую строку как None. Я ожидаю минимальных изменений во всех файлах.
Примененный мной подход:
Я создал унаследованный класс, такой как
Код: Выделить всё
class ConstrainedStr(str):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v: str, field: Field) -> Optional[str]:
v = v.strip()
if v == "":
return None
return v
Код: Выделить всё
from package.module import ConstrainedStr as str
User file:
Код: Выделить всё
from package.module import ConstrainedStr as str
def validate(cls, value:str): //sample value 'asd'
if isinstance(value, str):
validation_rule()
Question
- How could I avoid major changes to achieve this? Is there a way?
- Why that isinstance check failed. Constrainedstr is also a str right? Is my understanding wrong?
Код: Выделить всё
type(ConstrainedStr)
Код: Выделить всё
typeКод: Выделить всё
`type('123')`
Код: Выделить всё
typeКод: Выделить всё
builtinsКод: Выделить всё
strКод: Выделить всё
strКод: Выделить всё
strКод: Выделить всё
ConstrainedStrКод: Выделить всё
classAnother example:
Код: Выделить всё
class A(int):
pass
isinstance(2, A)
# False
Источник: https://stackoverflow.com/questions/781 ... lass-cases