python / python/mypy

Mypy gives confusing/misleading error message

未关闭
#17,531 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug
主要语言
Python
星标
20.6k
派生
3.3k
PR 合并指标
PR 指标待抓取

描述

Bug Report

Mypy reports error: Name "..." is not defined [name-defined] when using an instance attribute that was annotated.

To Reproduce

from inspect import Parameter


class ListElementDescriptor[T]:
    name: str
    item_type: type[T]

    @property
    def signature_parameter(self) -> Parameter:
        return Parameter(name=self.name, kind=Parameter.KEYWORD_ONLY, annotation=list[self.item_type])

Expected Behavior

Definitely not an error that self.item_type is not defined. I suspect mypy tries to to convey a different error, maybe related to using variables for type parameters in generics, though I disagree with that as well since list[] is not used here in a typing context to specify a type, but is used as a value.

Actual Behavior

typing-7.py:11: error: Name "self.item_type" is not defined  [name-defined]
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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先,使用 mypy 1.12.0+dev.6a0657e5959ba1777c4d427f8f355d499035d145 和所示的 Python 3.12 配置运行提供的 ListElementDescriptor 示例。跟踪对 list[self.item_type] 的诊断并更新它,使报告的问题准确,而不是声称 self.item_type 未定义;重新运行复现步骤,以确认误导性的 name-defined 错误已消失。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
compilers
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
48/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。