这不是我的确切用例,但类似。假设我要定义两个键入注释:
Matrix = np.ndarray
Vector = np.ndarray
现在,当我将Matrix
传递给接受Vector
的函数时,我希望潜在的类型检查器抱怨:
def f(x: Vector):
...
m: Matrix = ...
f(m) # Bad!
如何将这些类型标记为不兼容?
答案 0 :(得分:1)
看来我可以使用typing.NewType
来创建不同的类型:
from typing import NewType
A = NewType('A', int)
B = NewType('B', int)
def f(a: A):
pass
b: B
f(b)
给予
a.py:11: error: Argument 1 to "f" has incompatible type "B"; expected "A"
不幸的是,它只有在np.ndarray
实现类型提示或numpy
支持NewType
的基本类型后才能与Any
一起使用。