From 51c9aa8e35c8200ca8694fc62da1837cdc1cbbff Mon Sep 17 00:00:00 2001 From: BvB93 <43369155+BvB93@users.noreply.github.com> Date: Fri, 30 Sep 2022 16:38:19 +0200 Subject: TYP,ENH: Mark `numpy.typing` protocols as runtime checkable --- numpy/_typing/_array_like.py | 6 ++++-- numpy/_typing/_dtype_like.py | 2 ++ numpy/_typing/_nested_sequence.py | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) (limited to 'numpy/_typing') diff --git a/numpy/_typing/_array_like.py b/numpy/_typing/_array_like.py index 2e5684b0b..67d67ce19 100644 --- a/numpy/_typing/_array_like.py +++ b/numpy/_typing/_array_like.py @@ -3,7 +3,7 @@ from __future__ import annotations # NOTE: Import `Sequence` from `typing` as we it is needed for a type-alias, # not an annotation from collections.abc import Collection, Callable -from typing import Any, Sequence, Protocol, Union, TypeVar +from typing import Any, Sequence, Protocol, Union, TypeVar, runtime_checkable from numpy import ( ndarray, dtype, @@ -33,10 +33,12 @@ _DType_co = TypeVar("_DType_co", covariant=True, bound="dtype[Any]") # array. # Concrete implementations of the protocol are responsible for adding # any and all remaining overloads +@runtime_checkable class _SupportsArray(Protocol[_DType_co]): def __array__(self) -> ndarray[Any, _DType_co]: ... +@runtime_checkable class _SupportsArrayFunc(Protocol): """A protocol class representing `~class.__array_function__`.""" def __array_function__( @@ -146,7 +148,7 @@ _ArrayLikeInt = _DualArrayLike[ # Used as the first overload, should only match NDArray[Any], # not any actual types. # https://github.com/numpy/numpy/pull/22193 -class _UnknownType: +class _UnknownType: ... diff --git a/numpy/_typing/_dtype_like.py b/numpy/_typing/_dtype_like.py index b705d82fd..e92e17dd2 100644 --- a/numpy/_typing/_dtype_like.py +++ b/numpy/_typing/_dtype_like.py @@ -8,6 +8,7 @@ from typing import ( TypeVar, Protocol, TypedDict, + runtime_checkable, ) import numpy as np @@ -80,6 +81,7 @@ class _DTypeDict(_DTypeDictBase, total=False): # A protocol for anything with the dtype attribute +@runtime_checkable class _SupportsDType(Protocol[_DType_co]): @property def dtype(self) -> _DType_co: ... diff --git a/numpy/_typing/_nested_sequence.py b/numpy/_typing/_nested_sequence.py index 360c0f1b2..789bf3844 100644 --- a/numpy/_typing/_nested_sequence.py +++ b/numpy/_typing/_nested_sequence.py @@ -8,6 +8,7 @@ from typing import ( overload, TypeVar, Protocol, + runtime_checkable, ) __all__ = ["_NestedSequence"] @@ -15,6 +16,7 @@ __all__ = ["_NestedSequence"] _T_co = TypeVar("_T_co", covariant=True) +@runtime_checkable class _NestedSequence(Protocol[_T_co]): """A protocol for representing nested sequences. -- cgit v1.2.1