Mypy reports invalid type when a value is a parameterized generic
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 20.6k
- 派生
- 3.3k
- PR 合并指标
- PR 指标待抓取
描述
Bug Report
When I attempt to use a parameterized generic as a value to build a signature at runtime, mypy complains about the parameter as being invalid, when the parameter comes from a variable.
To Reproduce
from inspect import Parameter
def signature_parameter(name: str, item_type: type) -> Parameter:
return Parameter(name=name, kind=Parameter.KEYWORD_ONLY, annotation=list[item_type])
Expected Behavior
I would expect no error in this case (when the parameterized type is used as a value).
I know a variable cannot be used as a type parameter in a typing context (i.e. when used as a type annotation).
I understand that the following code would be wrong because variables cannot be used in type specifications:
var: type = int
lst: list[var] = [1, 2, 3] # this is wrong
But in my case above, list[item_type] is not used as a type specification, but as a value, that is passed to the runtime to build a signature. I do not think mypy should flag such use of values. It should simply consider the value to be of type types.GenericAlias.
Actual Behavior
typing-8.py:6: error: Variable "item_type" is not valid as a type [valid-type]
typing-8.py:6: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used:
mypy 1.12.0+dev.6a0657e5959ba1777c4d427f8f355d499035d145 (compiled: no) - Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files):
[tool.mypy]
enable_incomplete_feature = "NewGenericSyntax"
disable_bytearray_promotion = true
disable_memoryview_promotion = true
check_untyped_defs = true
warn_unreachable = true
warn_redundant_casts = true
warn_unused_ignores = true
- Python version used: 3.12
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 typing-8.py 复现程序开始,并在 Python 3.12 下运行 mypy,以确认针对 list[item_type] 的 [valid-type] 诊断。追踪负责该诊断的类型检查路径,并添加一个回归测试,证明这个运行时注解值会被接受;完成标准是测试在不抑制错误的情况下通过。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 45/100