【发布时间】:2021-08-07 19:28:36
【问题描述】:
尽管在typing documentation、mypy documentation 和PEP 483 上花费了大量时间,但我仍在努力理解何时使用TypeVar 以及何时使用Union。
问题的简单版本:Numeric = TypeVar('Numeric', int, float) 和 Numeric = Union[int, float] 有什么区别?
这是我遇到的更详细的示例:
"""example1.py
Use of Union to define "Numeric" type.
"""
from typing import Union, Sequence
Numeric = Union[int, float]
Vector = Sequence[Numeric]
Matrix = Sequence[Vector]
检查 mypy:
$ mypy --strict example1.py
Success: no issues found in 1 source file
改用TypeVar:
"""example2.py
Use of TypeVar to define "Numeric" type.
"""
from typing import TypeVar, Sequence
Numeric = TypeVar('Numeric', int, float)
Vector = Sequence[Numeric]
Matrix = Sequence[Vector]
检查 mypy:
$ mypy --strict example2.py
example2.py:11: error: Missing type parameters for generic type "Vector"
Found 1 error in 1 file (checked 1 source file)
上面的mypy错误是指Matrix的定义。为什么mypy 对example1.py 满意,但对example2.py 不满意?
我可以通过将最后一行更改为Matrix = Sequence[Vector[Numeric]] 来消除example2.py 中的错误。
版本信息:
$ python --version
Python 3.8.4
$ mypy --version
mypy 0.782
【问题讨论】:
-
我不确定错误本身。通常,
TypeVar是int或float中的一个的占位符,但在您实际提供基于它的值之前,该选择不会固定。也就是说,Matrix可以包含所有int值,或所有float值,但不能同时包含每个值。使用Union,单个Matrix的每个元素都可以是int或float,与其他元素的类型无关。
标签: python python-3.x type-hinting mypy python-typing