Код: Выделить всё
from typing import Any, Generic, TypeVar
from pydantic import BaseModel
X = TypeVar("X")
class TestModel(BaseModel, Generic[X]):
a: X
T = TypeVar("T")
class GetValue(Generic[T]):
@classmethod
def get_value(cls, x: Any) -> TestModel[T]:
return TestModel[T](a=x)
class GetInt:
@classmethod
def get_value(cls, x: Any) -> TestModel[int]:
return TestModel[int](a=x)
res = GetValue[int].get_value("1")
assert type(res.a) == str
res_2 = GetInt.get_value("1")
assert type(res_2.a) == int
assert res.a != res_2.a # I want these two to be equal, not sure why they are different.
x: Any = "1"
res_3 = TestModel[int](a=x)
assert type(res_3.a) == int
Версия Python: Python 3.12.5
pydantic версия: 2.10. 0
Подробнее здесь: https://stackoverflow.com/questions/792 ... onstructor