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

Python中使用NewType定义可调用类型的mypy报错解决方法咨询

解决NewType定义可调用类型的mypy错误方案

错误原因分析

  • 第一个错误:NewType的第一个字符串参数必须与变量名完全一致,这是mypy的强制规则,用于保证类型名称的一致性。
  • 第二个错误:SquareCalculator是通过NewType创建的名义类型,它和原生的Callable[[Square], int]属于不同类型范畴,直接返回原生可调用对象无法匹配该名义类型。

修正后的代码

from typing import NewType, Callable

Shape = NewType('Shape', tuple[int, int])
Square = NewType('Square', Shape)

def square_area(sh: Square) -> int:
    a, b = sh
    return a * b

def shape_area(sh: Shape) -> int:
    a, b = sh
    return a * b

# 修正NewType第一个参数与变量名一致
SquareCalculator = NewType('SquareCalculator', Callable[[Square], int])

def get_calc() -> SquareCalculator:
    # 用SquareCalculator包装函数,完成名义类型转换
    return SquareCalculator(square_area)

类型差异保留验证

修改后仍能保留Shape和Square的类型检查能力:

  • 无法将Shape类型变量传入square_area函数(mypy会报错)
  • 无法将shape_area包装为SquareCalculator返回(shape_area接受Shape参数,与SquareCalculator要求的Square参数类型不兼容,mypy会捕获该错误)

内容的提问来源于stack exchange,提问作者Zee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:35:00