Код: Выделить всё
from typing import TypeVar, Generic
from dataclasses import dataclass
class ParentType: ...
class ChildType(ParentType): ...
T = TypeVar("T", bound=ParentType)
@dataclass
class MyClass(Generic[T]):
a: T
mc1 = MyClass(ParentType())
mc2 = MyClass(ChildType())
def my_func(cls: MyClass[T]) -> T:
return cls.a
for i in (mc1, mc2):
my_func(i)
# ^
# Argument of type "MyClass[ParentType] | MyClass[ChildType]" cannot be assigned to parameter "cls" of type "MyClass[T@my_func]" in function "my_func"
# Type "MyClass[ParentType] | MyClass[ChildType]" is not assignable to type "MyClass[ParentType]"
# "MyClass[ChildType]" is not assignable to "MyClass[ParentType]"
# Type parameter "T@MyClass" is invariant, but "ChildType" is not the same as "ParentType"PylancereportArgumentType
# (variable) i: MyClass[ParentType] | MyClass[ChildType]
Если у меня нет выбора сделать T ковариантным, как бы вы решили эту проблему? Является ли кастинг единственным вариантом? Должна ли сама программа проверки типов попытаться учесть этот сценарий?
Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-python