Как я могу обрабатывать случаи суперкласса и подклассаPython

Программы на Python
Гость
Как я могу обрабатывать случаи суперкласса и подкласса

Сообщение Гость »


Постановка проблемы:
У меня есть сотни 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
Then, in all the py files I just added an import statement

Код: Выделить всё

from package.module import ConstrainedStr as str
Luckily, It worked at the first sight. But I ended up with an issue where I have a function
User file:

Код: Выделить всё

from package.module import ConstrainedStr as str

def validate(cls, value:str): //sample value 'asd'
if isinstance(value, str):
validation_rule()
Here, this conditional statement failed.
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?
When I digged into this further, just to understand the behaviour for the question #2, I found the below.

Код: Выделить всё

type(ConstrainedStr)
return .

Код: Выделить всё

`type('123')`
returns But when I check the

Код: Выделить всё

builtins
package, is also a class. But type function returns the type for as but for

Код: Выделить всё

ConstrainedStr
as . Hence, My question #2 popped up.
Another example:

Код: Выделить всё

class A(int):
pass

isinstance(2, A)
# False
This is my #2 question.


Источник: https://stackoverflow.com/questions/781 ... lass-cases

Вернуться в «Python»