Код: Выделить всё
from typing import Generic
from typing import TypeVar
from typing import reveal_type
T = TypeVar('T')
class Field(Generic[T]):
"""A field definition with a default value."""
def __init__(self, default_value: T):
self.default_value = default_value
class FieldDataCollection:
"""A collection of field values."""
def __init__(self, value_per_field: dict[Field[T], T]) -> None:
self._value_per_field = value_per_field
def get_field_value(self, field: Field[T]) -> T:
"""Return the field value if in the collection or the field default value."""
return self._value_per_field.get(field, field.default_value)
if __name__ == '__main__':
foo = Field(1)
value = FieldDataCollection({foo: 2}).get_field_value(foo)
reveal_type(value)
Код: Выделить всё
error: Incompatible return value type (got "T@__init__", expected "T@get_field_value") [return-value]
error: Argument 1 to "get" of "dict" has incompatible type "Field[T@get_field_value]"; expected "Field[T@__init__]" [arg-type]
error: Argument 2 to "get" of "dict" has incompatible type "T@get_field_value"; expected "T@__init__" [arg-type]
note: Revealed type is "builtins.int"
Я пытался использовать переменную другого типа для get_field_value:
Код: Выделить всё
T = TypeVar("T")
Tfield = TypeVar("Tfield")
...
class FieldDataCollection:
...
def get_field_value(self, field: Field[Tfield]) -> Tfield:
...
Код: Выделить всё
error: Incompatible return value type (got "T", expected "Tfield") [return-value]
error: Argument 1 to "get" of "dict" has incompatible type "Field[Tfield]"; expected "Field[T]" [arg-type]
error: Argument 2 to "get" of "dict" has incompatible type "Tfield"; expected "T" [arg-type]
note: Revealed type is "builtins.int"
Считаете ли вы, что это регресс на стороне mypy?
В противном случае, есть ли у вас какие-либо идеи о том, как правильно аннотировать класс FieldDataCollection?
Подробнее здесь: https://stackoverflow.com/questions/787 ... ss-methods