类型注释:使用Numpy和Pure Python类型与仿制药
我正在努力注释一个函数,该功能接受int
或floats
的函数,并使用dtype
s np.integer产生numpy数组
或np.floing
:
from __future__ import annotations
from typing import Tuple, Union, TypeVar
import numpy as np
T = TypeVar('T', np.integer, np.floating)
def bounds2loc(bounds: Tuple[T, T, T, T]) -> np.ndarray[Tuple[int], np.dtype[T]]:
left, top, right, bottom = bounds
loc = np.asarray([left, top])
return loc
def do_check_int() -> np.ndarray[Tuple[int], np.dtype[np.integer]]:
bounds = (1, 2, 10, 5)
bounds2loc(bounds)
mypy检查合理失败,因为纯Python的int
无法将其施加到np.integer
:参数1到“ bounds2loc”具有不兼容的类型“元组[int,int,int,int]”;预期的“元组[Integer [any],Integer [any],Integer [Any],Integer [Any]]”
。
有没有办法做出适当的注释,以允许这样做?
I'm struggling to annotate a function which accepts tuples of int
or floats
and produces a numpy array with dtype
s np.integer
or np.floating
:
from __future__ import annotations
from typing import Tuple, Union, TypeVar
import numpy as np
T = TypeVar('T', np.integer, np.floating)
def bounds2loc(bounds: Tuple[T, T, T, T]) -> np.ndarray[Tuple[int], np.dtype[T]]:
left, top, right, bottom = bounds
loc = np.asarray([left, top])
return loc
def do_check_int() -> np.ndarray[Tuple[int], np.dtype[np.integer]]:
bounds = (1, 2, 10, 5)
bounds2loc(bounds)
Mypy check reasonably fails, as pure python's int
cannot be casted to np.integer
: Argument 1 to "bounds2loc" has incompatible type "Tuple[int, int, int, int]"; expected "Tuple[integer[Any], integer[Any], integer[Any], integer[Any]]"
.
Is there a way to make a proper annotation which would allow that?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论