mypy 使用 TypeVar 比 Union 更好地捕获错误

问题描述 投票:0回答:0

首次实施

from typing import Union

U = Union[int, str]

def max_1(var1: U, var2: U) -> U:
    return max(var1, var2)

print(max_1("foo", 1)) # mypy accept this, despite the fact that the type of var1 is str and the type of var2 is int
print(max_1(1, "foo"))
print(max_1(1, 2))
print(max_1("foo", "bar"))

二次实施

from typing import TypeVar

T = TypeVar("T", int, str)

def max_2(var1: T, var2: T) -> T:
    return max(var1, var2)

print(max_2("foo", 1)) # mypy shows an error here
print(max_2(1, "foo"))
print(max_2(1, 2))
print(max_2("foo", "bar"))`

我想知道mypy是如何检测到这个错误的,抛出的错误是什么意思:

Value of type variable "T" of "max_2" cannot be "object"  [type-var]mypy 

这个“对象”是什么意思?

在WEB中搜索解释,但找不到太多

python python-3.x mypy python-typing
© www.soinside.com 2019 - 2024. All rights reserved.