输入参数的正确方法,可以是序列或 numpy 数组

Proper way of typing argument which can be either sequence or numpy array

我想实现一种在 3D space 中进行一些距离计算的方法,具体取决于 position 参数,该参数分别由 x、y 和 z 坐标的 3 个整数值组成。

现在,如果该方法接受此 position 参数作为

就好了

我想知道记录这种灵活参数类型的当前最佳实践是什么。使用 python 相对较新的打字模块,我想到的是:

import numpy as np
from typing import Union, Sequence

def get_distances(self, 
                  position: Union[Sequence[int, int, int], np.ndarray((3,), dtype=int)]):
    ...
    return distances

那是怎么做到的?或者它是在顶部,像这样的东西通过文档字符串更好地记录还是一起避免?

对于你的类型注释,你正在实例化一个 numpy 数组(如果你 运行 它会引发异常)此外, Sequence 只接受一个参数,类型它包含。

Sequence 错误将引发:

TypeError: Too many parameters for typing.Sequence; actual 3, expected 1

np.ndarray((3,)...) 错误将引发:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

你只需要输入类型标识符,并且只指定一次int:

import numpy as np
from typing import Union, Sequence

def get_distances(self, 
                  position: Union[Sequence[int], np.ndarray]):
    ...
    return distances

typing 文档页有很多关于如何使用注释的有用信息。