Having to add type hint 2nd time on AnyStr when assigning as instance attribute
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 20.6k
- 派生
- 3.3k
- PR 合并指标
- PR 指标待抓取
描述
I am reporting a potential bug/improvement in mypy.
I assign a class's instance attribute to be an argument from the __init__ signature.
I noticed that when the argument is type hinted as a AnyStr, mypy raises an error unless the instance attribute receives a second type hint.
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'
# Observation: 'builtins.bytes*' doesn't seem to propagate
class B(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case B... Success
self.attr = arg # type: AnyStr
The desirable behavior is not to have to supply a second type hint.
What's going on here? Is there some way I can not supply a second type hint?
I am invoking mypy from the command line with no flags. Here are my versions:
python==3.6.5
mypy==0.770
Aside
I am coming here from Stack Overflow, where a community member thought it was a bug: Python mypy why does class instance attribute require type hint if expression already has type hint
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先使用 mypy 0.770,根据随附的 Python 代码片段重现该问题,比较 Case A 和 Case B 及其 revealed types。跟踪 Generic[AnyStr] 的实例属性推断,并确定在没有内联注解的情况下类型变量是否应当继续传播。完成的标准是 Case A 不再需要第二个类型提示,并且为所演示的行为添加回归覆盖。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100