You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决mypy引用带包前缀的类型别名时的"Name未定义"错误?

问题:Mypy无法识别存根文件中全名引用的类型别名

场景背景

我正在为Python包装的原生库编写存根文件,以提供完善的类型注解,当前的包结构如下:

. geometry
|- typing
|  `- __init__.pyi
|- geometry.cpython-39-x86_64-linux-gnu.so
|- __init__.py
|- __init__.pyi
`- py.typed

各存根文件内容:

geometry/typing/__init__.pyi

import geometry
import typing

Point = tuple[int, int]
Primitive = geometry.Circle | geometry.Rect
Primitives = typing.Sequence[Primitive]

geometry/__init__.pyi

import geometry.typing


class Circle:
    center: geometry.typing.Point
    radius: int

    def __init__(self, center: geometry.typing.Point, radius: int): ...


class Rect:
    top_left: geometry.typing.Point
    width: int
    height: int

    def __init__(self, top_left: geometry.typing.Point, width: int, height: int): ...


def calculate_union_area(primitives: geometry.typing.Primitives) -> float: ... 

geometry/__init__.py

from .geometry import Circle, Rect, calculate_union_area

报错情况

执行python -m mypy.stubtest geometry时,mypy报错:

error: not checking stubs due to mypy build errors:
geometry/__init__.pyi:4: error: Name "geometry.typing.Point" is not defined  [name-defined]
geometry/__init__.pyi:7: error: Name "geometry.typing.Point" is not defined  [name-defined]
geometry/__init__.pyi:10: error: Name "geometry.typing.Point" is not defined  [name-defined]
geometry/__init__.pyi:14: error: Name "geometry.typing.Point" is not defined  [name-defined]
geometry/__init__.pyi:16: error: Name "geometry.typing.Primitives" is not defined  [name-defined]

在外部文件中使用geometry.typing的类型时,Pylance和Pyright的类型提示与自动补全正常工作,但执行python -m mypy --strict --follow_imports_for_stubs main.py时,geometry.typing.Primitives仍触发"Name未定义"错误,而Point可被正常解析并检测类型错误。

已知条件

  • mypy版本:0.991
  • Python版本:3.10.9
  • 已尝试将geometry.typing.__init__.pyi改为带typing.TYPE_CHECKING判断的.py文件,问题依旧
  • 由于实际场景存在命名冲突,无法使用from geometry.typing import Name或别名导入的方式

需求

如何让mypy接受使用全名引用的类型别名?

内容的提问来源于stack exchange,提问作者V. Levin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:05:19