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

为什么mypy会对Number入参、NewType派生类型的参数报错?

我查阅了Mypy和Python的官方文档,但仍然没搞懂下述代码的报错原因:

from typing import NewType
from numbers import Number


def foo(num: Number):
    print(num)

foo(5)

A = NewType("A", str)
B = NewType("B", A)

test_var_1 = A("test")
test_var_2 = B(A("test"))
test_var_3 = B("test")

运行mypy得到如下报错:

mypytest.py:8: error: Argument 1 to "foo" has incompatible type "int"; expected "Number"
mypytest.py:15: error: Argument 1 to "B" has incompatible type "str"; expected "A"

按照相关问题的答复,mypy不应该对foo函数的调用报错,numbers.Number、collections.abc.Sequence这类抽象基类的作用不就是用来做类型提示,表明函数可以接收任意其子类作为参数吗?(同时也支持用户自定义的子类)

另外关于NewType的「派生」用法,Python官方文档就给出了对应的示例:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

我使用的Mypy版本为0.910,Python版本为3.9.7。

补充:
Mypy官方文档提到NewType等价于创建一个空的子类,仅运行时开销更低,但上述逻辑如果改用普通类实现则完全没有报错:

class A(str):
    pass

class B(A):
    pass


test_var_1 = A("test")
test_var_2 = B(A("test"))
test_var_3 = B("test")

mypy检查结果:

Success: no issues found in 1 source file

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:45:02