类型注释:使用Numpy和Pure Python类型与仿制药

发布于 2025-01-23 09:51:25 字数 848 浏览 1 评论 0原文

我正在努力注释一个函数,该功能接受intfloats的函数,并使用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 dtypes 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文