-
Beta Was this translation helpful? Give feedback.
Answered by
erictraut
May 2, 2024
Replies: 1 comment 1 reply
-
The Python static type system isn't rich enough to express the notion that "this object has an attribute called The from typing import Any, TypeGuard, TypeVar
T = TypeVar("T", bound=np.generic)
def is_correct_type(arr: npt.NDArray[Any], typ: type[T]) -> TypeGuard[npt.NDArray[T]]:
return arr.dtype == np.int_ or np.issubdtype(arr.dtype, np.int_)
if is_correct_type(arr, np.int_):
arr = func_2(arr) Or if you're using Python 3.12, you can use the new generics syntax: def is_correct_type[T: np.generic](arr: npt.NDArray[Any], typ: type[T]) -> TypeGuard[npt.NDArray[T]]:
return arr.dtype == np.int_ or np.issubdtype(arr.dtype, np.int_) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
gaufde
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Python static type system isn't rich enough to express the notion that "this object has an attribute called
dtype
that contains an immutable value that relates to the type of class". A static type checker therefore cannot narrow the type ofarr
in your example without additional information.The
TypeGuard
type (introduced in PEP 647) was designed to handle cases like this.Or if you're using Pytho…