'Type annotations: Using numpy and pure python types with generics

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?.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source