python / python/mypy

False positive for Union[type, ...] and inspect.isclass()

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

还没有人认领这个 Issue。

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

描述

Bug Report

When a variable's type is declared as a union that includes type (or typing.Type[...]), mypy does not take into account whether usage of that variable occurs inside of an if inspect.isclass(...) conditional block, leading to false positives.

To Reproduce

gist
playground

Python code
from inspect import isclass

registry: dict[str, type] = {}

def decorator_factory(arg: str | type):
    if isclass(arg):
        registry[arg.__name__.lower()] = arg
        return arg
    else:
        def decorator(cls: type):
            registry[arg] = cls
            return cls
        return decorator
        
@decorator_factory
class Foo:
    pass
        
@decorator_factory("alt")
class Bar:
    pass

Expected Behavior**

mypy reports no errors

Actual Behavior

main.py:11: error: Invalid index type "str | type" for "dict[str, type]"; expected type "str"  [index]
Found 1 error in 1 file (checked 1 source file)

Workaround

Using typing.cast to narrow the union explicitly.

gist
playground

Python code
from inspect import isclass
from typing import cast, TYPE_CHECKING

registry: dict[str, type] = {}

def decorator_factory(arg: str | type):
    if isclass(arg):
        registry[arg.__name__.lower()] = arg
        return arg
    else:
        if TYPE_CHECKING:
            arg = cast(str, arg)
        
        def decorator(cls: type):
            registry[arg] = cls
            return cls
        return decorator
        
@decorator_factory
class Foo:
    pass
        
@decorator_factory("alt")
class Bar:
    pass

Your Environment

  • Mypy version used: 1.7.1
  • Mypy command-line flags: (mypy-play defaults)
  • Mypy configuration options from mypy.ini (and other config files): (mypy-play defaults)
  • Python version used: 3.12

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先使用 mypy 运行链接的 reproducer,并将报告的错误与 inspect.isclass() 和 Union[type, ...] 周围的预期行为进行比较。跟踪 inspect.isclass 的类型收窄路径,然后为 reproducer 添加回归覆盖。验证在不使用 cast 绕过方案的情况下,mypy 不会报告任何错误。

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

评估

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

把新 issue 发到你的邮箱

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