Я сталкивался с этим случаем несколько раз:
- Аргумент
arg
в классе __init__
имеет подсказку типа, равную TypeVar
- An Атрибут экземпляра
self.attr
назначен на arg
- mypy вызывает ошибки, если я не указываю подсказку второго типа на
self.attr
Мой вопрос: почему Мне нужно указать подсказку второго типа?
Пример кода
from typing import AnyStr, Generic
class A(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case A... error: Need type annotation for 'attr'
self.attr = arg
reveal_type(arg)
# note: Revealed type is 'builtins.str*'
# note: Revealed type is 'builtins.bytes*'
reveal_type(self.attr)
# note: Revealed type is 'builtins.str'
# note: Revealed type is 'Any'
class B(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case B... Success
self.attr = arg # type: AnyStr
Для Case A
я думаю, что подсказка типа на arg
следует распространить на self.attr
, но это не так. Почему это так?
Версии:
python==3.6.5
mypy==0.770