小编Whi*_*osh的帖子

Mypy - 为什么 TypeVar 在没有指定界限的情况下不起作用

我试图理解类型注释,我有以下代码:

from typing import TypeVar

T = TypeVar('T')

class MyClass():
    x: int = 10

def foo(obj: T) -> None:
    print(obj.x)

foo(MyClass())
Run Code Online (Sandbox Code Playgroud)

当我运行 mypy 时,出现以下错误:

main.py:9: error: "T" has no attribute "x"
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

但是当我添加bound='MyClass'到时TypeVar,它没有显示任何错误。

这种行为的原因是什么?我尝试阅读文档,但没有找到任何关于bound设置为默认值时到底发生了什么的答案。

python mypy

3
推荐指数
1
解决办法
3751
查看次数

标签 统计

mypy ×1

python ×1