相关疑难解决方法(0)

TypeVar('T', A, B) 和 TypeVar('T', bound=Union[A, B]) 的区别

我正在努力弄清楚以下两个TypeVars之间的区别

from typing import TypeVar, Union

class A: pass
class B: pass

T = TypeVar("T", A, B)
T = TypeVar("T", bound=Union[A, B])
Run Code Online (Sandbox Code Playgroud)

有人想启发我吗?

一个我不明白的例子......

T = TypeVar("T", bound=Union[A, B])

class AA(A):
    pass


class X(Generic[T]):
    pass


class XA(X[A]):
    pass


class XAA(X[AA]):
    pass
Run Code Online (Sandbox Code Playgroud)

通过类型检查,但T = TypeVar("T", A, B)失败了

错误:“X”的类型变量“T”的值不能是“AA”

相关:this question on the difference between Union[A, B]andTypeVar("T", A, B)

python generics type-hinting

16
推荐指数
2
解决办法
5440
查看次数

是否有更好的方法来使用 Python 的类型模块为复合类型创建类型别名?

我有一个带一个参数的函数,它应该以 anint或 aNone作为参数。有几种方法可以为这种复合类型创建类型别名:

# test.py
import typing

IntOrNone_1 = typing.TypeVar('IntOrNone_1', int, None)
IntOrNone_2 = typing.Union[int, None]


def my_func1(xyz: IntOrNone_1):
    return xyz

def my_func2(xyz: IntOrNone_2):
    return xyz


my_func1(12)
my_func1(None)
my_func1(13.7)
my_func1('str')

my_func2(12)
my_func2(None)
my_func2(13.7)
my_func2('str')
Run Code Online (Sandbox Code Playgroud)

两种方法都按照我的预期执行,但是,对应的mypy错误略有不同,但基本上具有相同的含义。

test.py:14: 错误:“my_func1”的类型变量“IntOrNone_1”的值不能是“float”

test.py:15: 错误:“my_func1”的类型变量“IntOrNone_1”的值不能是“str”

test.py:19: 错误:“my_func2”的参数 1 具有不兼容的类型“float”;预期“可选[int]”

test.py:20: 错误:“my_func2”的参数 1 具有不兼容的类型“str”;预期“可选[int]”

我倾向于使用第二种方法,因为它还会报告导致错误的参数。

我认为这两种方法确实等效,还是首选其中之一?

python typing typechecking

4
推荐指数
1
解决办法
1699
查看次数

标签 统计

python ×2

generics ×1

type-hinting ×1

typechecking ×1

typing ×1