summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
Diffstat (limited to 'numpy')
-rw-r--r--numpy/core/_add_newdocs.py6
-rw-r--r--numpy/core/defchararray.py1
-rw-r--r--numpy/core/records.py1
-rw-r--r--numpy/distutils/fcompiler/nv.py2
-rw-r--r--numpy/f2py/cfuncs.py153
-rwxr-xr-xnumpy/f2py/crackfortran.py1
-rwxr-xr-xnumpy/f2py/rules.py6
-rw-r--r--numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c2
-rw-r--r--numpy/f2py/tests/test_return_character.py4
-rw-r--r--numpy/f2py/tests/test_string.py146
-rw-r--r--numpy/lib/npyio.py1
-rw-r--r--numpy/ma/core.py1
-rw-r--r--numpy/ma/extras.py1
-rw-r--r--numpy/typing/__init__.py21
-rw-r--r--numpy/typing/_array_like.py16
-rw-r--r--numpy/typing/_callable.py154
-rw-r--r--numpy/typing/_char_codes.py114
-rw-r--r--numpy/typing/_dtype_like.py77
-rw-r--r--numpy/typing/_generic_alias.py1
-rw-r--r--numpy/typing/_shape.py9
-rw-r--r--numpy/typing/_ufunc.pyi70
-rw-r--r--numpy/typing/mypy_plugin.py4
22 files changed, 488 insertions, 303 deletions
diff --git a/numpy/core/_add_newdocs.py b/numpy/core/_add_newdocs.py
index b8f0ee907..448f6a0c0 100644
--- a/numpy/core/_add_newdocs.py
+++ b/numpy/core/_add_newdocs.py
@@ -924,7 +924,7 @@ add_newdoc('numpy.core.multiarray', 'asarray',
'F' column-major (Fortran-style) memory representation.
'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
- Defaults to 'C'.
+ Defaults to 'K'.
${ARRAY_FUNCTION_LIKE}
.. versionadded:: 1.20.0
@@ -1536,6 +1536,10 @@ add_newdoc('numpy.core.multiarray', 'frombuffer',
.. versionadded:: 1.20.0
+ Returns
+ -------
+ out : ndarray
+
Notes
-----
If the buffer has data that is not in machine byte-order, this should
diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py
index ab1166ad2..e264fa210 100644
--- a/numpy/core/defchararray.py
+++ b/numpy/core/defchararray.py
@@ -16,7 +16,6 @@ The preferred alias for `defchararray` is `numpy.char`.
"""
import functools
-import sys
from .numerictypes import (
string_, unicode_, integer, int_, object_, bool_, character)
from .numeric import ndarray, compare_chararrays
diff --git a/numpy/core/records.py b/numpy/core/records.py
index 5bd13a698..b3474ad01 100644
--- a/numpy/core/records.py
+++ b/numpy/core/records.py
@@ -33,7 +33,6 @@ Record arrays allow us to access fields as properties::
array([2., 2.])
"""
-import os
import warnings
from collections import Counter
from contextlib import nullcontext
diff --git a/numpy/distutils/fcompiler/nv.py b/numpy/distutils/fcompiler/nv.py
index 8e9f16835..212f34806 100644
--- a/numpy/distutils/fcompiler/nv.py
+++ b/numpy/distutils/fcompiler/nv.py
@@ -1,5 +1,3 @@
-import sys
-
from numpy.distutils.fcompiler import FCompiler
compilers = ['NVHPCFCompiler']
diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py
index f403a66b5..60685be8a 100644
--- a/numpy/f2py/cfuncs.py
+++ b/numpy/f2py/cfuncs.py
@@ -469,7 +469,7 @@ cppmacros['MEMCOPY'] = """\
"""
cppmacros['STRINGMALLOC'] = """\
#define STRINGMALLOC(str,len)\\
- if ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\\
+ if ((str = (string)malloc(len+1)) == NULL) {\\
PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\
goto capi_fail;\\
} else {\\
@@ -481,18 +481,18 @@ cppmacros['STRINGFREE'] = """\
"""
needs['STRINGCOPYN'] = ['string.h', 'FAILNULL']
cppmacros['STRINGCOPYN'] = """\
-#define STRINGCOPYN(to,from,buf_size) \\
+/*
+STRINGCOPYN copies N bytes.
+
+`to` and `from` buffers must have sizes of at least N bytes.
+*/
+#define STRINGCOPYN(to,from,N) \\
do { \\
- int _m = (buf_size); \\
+ int _m = (N); \\
char *_to = (to); \\
char *_from = (from); \\
FAILNULL(_to); FAILNULL(_from); \\
- (void)strncpy(_to, _from, sizeof(char)*_m); \\
- _to[_m-1] = '\\0'; \\
- /* Padding with spaces instead of nulls */ \\
- for (_m -= 2; _m >= 0 && _to[_m] == '\\0'; _m--) { \\
- _to[_m] = ' '; \\
- } \\
+ (void)strncpy(_to, _from, _m); \\
} while (0)
"""
needs['STRINGCOPY'] = ['string.h', 'FAILNULL']
@@ -623,71 +623,121 @@ static int *nextforcomb(void) {
}"""
needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string']
cfuncs['try_pyarr_from_string'] = """\
-static int try_pyarr_from_string(PyObject *obj,const string str) {
- PyArrayObject *arr = NULL;
- if (PyArray_Check(obj) && (!((arr = (PyArrayObject *)obj) == NULL)))
- { STRINGCOPYN(PyArray_DATA(arr),str,PyArray_NBYTES(arr)); }
- return 1;
+/*
+ try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`.
+
+ If obj is an `ndarray`, it is assumed to be contiguous.
+
+ If the specified len==-1, str must be null-terminated.
+*/
+static int try_pyarr_from_string(PyObject *obj,
+ const string str, const int len) {
+#ifdef DEBUGCFUNCS
+fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n",
+ (char*)str,len, obj);
+#endif
+ if (PyArray_Check(obj)) {
+ PyArrayObject *arr = (PyArrayObject *)obj;
+ assert(ISCONTIGUOUS(arr));
+ string buf = PyArray_DATA(arr);
+ npy_intp n = len;
+ if (n == -1) {
+ /* Assuming null-terminated str. */
+ n = strlen(str);
+ }
+ if (n > PyArray_NBYTES(arr)) {
+ n = PyArray_NBYTES(arr);
+ }
+ STRINGCOPYN(buf, str, n);
+ return 1;
+ }
capi_fail:
PRINTPYOBJERR(obj);
- PyErr_SetString(#modulename#_error,\"try_pyarr_from_string failed\");
+ PyErr_SetString(#modulename#_error, \"try_pyarr_from_string failed\");
return 0;
}
"""
needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN']
cfuncs['string_from_pyobj'] = """\
+/*
+ Create a new string buffer `str` of at most length `len` from a
+ Python string-like object `obj`.
+
+ The string buffer has given size (len) or the size of inistr when len==-1.
+
+ The string buffer is null-terminated.
+ */
static int
-string_from_pyobj(string *str,int *len,const string inistr,PyObject *obj,const char *errmess)
+string_from_pyobj(string *str, int *len, const string inistr, PyObject *obj,
+ const char *errmess)
{
- PyArrayObject *arr = NULL;
PyObject *tmp = NULL;
+ string buf = NULL;
+ npy_intp n = -1;
#ifdef DEBUGCFUNCS
-fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",(char*)str,*len,(char *)inistr,obj);
+fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",
+ (char*)str, *len, (char *)inistr, obj);
#endif
if (obj == Py_None) {
- if (*len == -1)
- *len = strlen(inistr); /* Will this cause problems? */
- STRINGMALLOC(*str,*len);
- STRINGCOPYN(*str,inistr,*len+1);
- return 1;
+ n = strlen(inistr);
+ buf = inistr;
}
- if (PyArray_Check(obj)) {
- if ((arr = (PyArrayObject *)obj) == NULL)
- goto capi_fail;
+ else if (PyArray_Check(obj)) {
+ PyArrayObject *arr = (PyArrayObject *)obj;
if (!ISCONTIGUOUS(arr)) {
- PyErr_SetString(PyExc_ValueError,\"array object is non-contiguous.\");
+ PyErr_SetString(PyExc_ValueError,
+ \"array object is non-contiguous.\");
goto capi_fail;
}
- if (*len == -1)
- *len = (PyArray_ITEMSIZE(arr))*PyArray_SIZE(arr);
- STRINGMALLOC(*str,*len);
- STRINGCOPYN(*str,PyArray_DATA(arr),*len+1);
- return 1;
- }
- if (PyBytes_Check(obj)) {
- tmp = obj;
- Py_INCREF(tmp);
- }
- else if (PyUnicode_Check(obj)) {
- tmp = PyUnicode_AsASCIIString(obj);
+ n = PyArray_NBYTES(arr);
+ buf = PyArray_DATA(arr);
}
else {
- PyObject *tmp2;
- tmp2 = PyObject_Str(obj);
- if (tmp2) {
- tmp = PyUnicode_AsASCIIString(tmp2);
- Py_DECREF(tmp2);
+ if (PyBytes_Check(obj)) {
+ tmp = obj;
+ Py_INCREF(tmp);
+ }
+ else if (PyUnicode_Check(obj)) {
+ tmp = PyUnicode_AsASCIIString(obj);
}
else {
- tmp = NULL;
+ PyObject *tmp2;
+ tmp2 = PyObject_Str(obj);
+ if (tmp2) {
+ tmp = PyUnicode_AsASCIIString(tmp2);
+ Py_DECREF(tmp2);
+ }
+ else {
+ tmp = NULL;
+ }
}
+ if (tmp == NULL) goto capi_fail;
+ n = PyBytes_GET_SIZE(tmp);
+ buf = PyBytes_AS_STRING(tmp);
}
- if (tmp == NULL) goto capi_fail;
- if (*len == -1)
- *len = PyBytes_GET_SIZE(tmp);
- STRINGMALLOC(*str,*len);
- STRINGCOPYN(*str,PyBytes_AS_STRING(tmp),*len+1);
- Py_DECREF(tmp);
+ if (*len == -1) {
+ /* TODO: change the type of `len` so that we can remove this */
+ if (n > NPY_MAX_INT) {
+ PyErr_SetString(PyExc_OverflowError,
+ "object too large for a 32-bit int");
+ goto capi_fail;
+ }
+ *len = n;
+ }
+ else if (*len < n) {
+ /* discard the last (len-n) bytes of input buf */
+ n = *len;
+ }
+ if (n < 0 || *len < 0 || buf == NULL) {
+ goto capi_fail;
+ }
+ STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1)
+ if (n < *len) {
+ /* Pad fixed-width string with nulls */
+ memset(*str + n, '\\0', *len - n);
+ }
+ STRINGCOPYN(*str, buf, n);
+ Py_XDECREF(tmp);
return 1;
capi_fail:
Py_XDECREF(tmp);
@@ -702,7 +752,6 @@ capi_fail:
}
"""
-
needs['char_from_pyobj'] = ['int_from_pyobj']
cfuncs['char_from_pyobj'] = """\
static int
diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py
index 6453bbecb..984bd642b 100755
--- a/numpy/f2py/crackfortran.py
+++ b/numpy/f2py/crackfortran.py
@@ -139,7 +139,6 @@ TODO:
The above may be solved by creating appropriate preprocessor program, for example.
"""
-import io
import sys
import string
import fileinput
diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py
index 63e47baa2..f01b2bcfa 100755
--- a/numpy/f2py/rules.py
+++ b/numpy/f2py/rules.py
@@ -561,7 +561,8 @@ rout_rules = [
'\tint #name#_return_value_len = 0;'],
'callfortran':'#name#_return_value,#name#_return_value_len,',
'callfortranroutine':['\t#name#_return_value_len = #rlength#;',
- '\tif ((#name#_return_value = (string)malloc(sizeof(char)*(#name#_return_value_len+1))) == NULL) {',
+ '\tif ((#name#_return_value = (string)malloc('
+ '#name#_return_value_len+1) == NULL) {',
'\t\tPyErr_SetString(PyExc_MemoryError, \"out of memory\");',
'\t\tf2py_success = 0;',
'\t} else {',
@@ -963,7 +964,8 @@ if (#varname#_cb.capi==Py_None) {
'args_capi': {isrequired: ',&#varname#_capi'},
'keys_capi': {isoptional: ',&#varname#_capi'},
'pyobjfrom': {isintent_inout: '''\
-\tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,#varname#);
+\tf2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#,
+\t slen(#varname#));
\tif (f2py_success) {'''},
'closepyobjfrom': {isintent_inout: '\t} /*if (f2py_success) of #varname# pyobjfrom*/'},
'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
diff --git a/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c b/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c
index 0411b62e0..fe21d4b9b 100644
--- a/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c
+++ b/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c
@@ -93,7 +93,7 @@ static PyObject *f2py_rout_wrap_attrs(PyObject *capi_self,
PyObject *strides = NULL;
char s[100];
int i;
- memset(s,0,100*sizeof(char));
+ memset(s,0,100);
if (!PyArg_ParseTuple(capi_args,"O!|:wrap.attrs",
&PyArray_Type,&arr_capi))
return NULL;
diff --git a/numpy/f2py/tests/test_return_character.py b/numpy/f2py/tests/test_return_character.py
index 429e69bb4..dc524e60c 100644
--- a/numpy/f2py/tests/test_return_character.py
+++ b/numpy/f2py/tests/test_return_character.py
@@ -24,8 +24,8 @@ class TestReturnCharacter(util.F2PyTest):
assert_(t(23) == b'23 ', repr(t(23)))
assert_(t('123456789abcdef') == b'123456789a')
elif tname in ['t5', 's5']:
- assert_(t(23) == b'23 ', repr(t(23)))
- assert_(t('ab') == b'ab ', repr(t('ab')))
+ assert_(t(23) == b'23', repr(t(23)))
+ assert_(t('ab') == b'ab', repr(t('ab')))
assert_(t('123456789abcdef') == b'12345')
else:
raise NotImplementedError
diff --git a/numpy/f2py/tests/test_string.py b/numpy/f2py/tests/test_string.py
index e3ec96af9..1530c58f6 100644
--- a/numpy/f2py/tests/test_string.py
+++ b/numpy/f2py/tests/test_string.py
@@ -1,6 +1,6 @@
import os
import pytest
-
+import textwrap
from numpy.testing import assert_array_equal
import numpy as np
from . import util
@@ -9,14 +9,156 @@ from . import util
def _path(*a):
return os.path.join(*((os.path.dirname(__file__),) + a))
+
class TestString(util.F2PyTest):
sources = [_path('src', 'string', 'char.f90')]
@pytest.mark.slow
def test_char(self):
strings = np.array(['ab', 'cd', 'ef'], dtype='c').T
- inp, out = self.module.char_test.change_strings(strings, strings.shape[1])
+ inp, out = self.module.char_test.change_strings(strings,
+ strings.shape[1])
assert_array_equal(inp, strings)
expected = strings.copy()
expected[1, :] = 'AAA'
assert_array_equal(out, expected)
+
+
+class TestDocStringArguments(util.F2PyTest):
+ suffix = '.f'
+
+ code = """
+C FILE: STRING.F
+ SUBROUTINE FOO(A,B,C,D)
+ CHARACTER*5 A, B
+ CHARACTER*(*) C,D
+Cf2py intent(in) a,c
+Cf2py intent(inout) b,d
+ PRINT*, "A=",A
+ PRINT*, "B=",B
+ PRINT*, "C=",C
+ PRINT*, "D=",D
+ PRINT*, "CHANGE A,B,C,D"
+ A(1:1) = 'A'
+ B(1:1) = 'B'
+ C(1:1) = 'C'
+ D(1:1) = 'D'
+ PRINT*, "A=",A
+ PRINT*, "B=",B
+ PRINT*, "C=",C
+ PRINT*, "D=",D
+ END
+C END OF FILE STRING.F
+ """
+
+ def test_example(self):
+ a = np.array(b'123\0\0')
+ b = np.array(b'123\0\0')
+ c = np.array(b'123')
+ d = np.array(b'123')
+
+ self.module.foo(a, b, c, d)
+
+ assert a.tobytes() == b'123\0\0'
+ assert b.tobytes() == b'B23\0\0', (b.tobytes(),)
+ assert c.tobytes() == b'123'
+ assert d.tobytes() == b'D23'
+
+
+class TestFixedString(util.F2PyTest):
+ suffix = '.f90'
+
+ code = textwrap.dedent("""
+ function sint(s) result(i)
+ implicit none
+ character(len=*) :: s
+ integer :: j, i
+ i = 0
+ do j=1, len(s)
+ i = i + ichar(s(j:j)) * 10 ** (j - 1)
+ end do
+ return
+ end function sint
+
+ function test_in_bytes4(a) result (i)
+ implicit none
+ integer :: sint
+ character(len=4) :: a
+ integer :: i
+ i = sint(a)
+ a(1:1) = 'A'
+ return
+ end function test_in_bytes4
+
+ function test_inout_bytes4(a) result (i)
+ implicit none
+ integer :: sint
+ character(len=4), intent(inout) :: a
+ integer :: i
+ if (ichar(a(1:1)).ne.0) then
+ a(1:1) = 'E'
+ endif
+ i = sint(a)
+ return
+ end function test_inout_bytes4
+ """)
+
+ @staticmethod
+ def _sint(s, start=0, end=None):
+ """Return the content of a string buffer as integer value.
+
+ For example:
+ _sint('1234') -> 4321
+ _sint('123A') -> 17321
+ """
+ if isinstance(s, np.ndarray):
+ s = s.tobytes()
+ elif isinstance(s, str):
+ s = s.encode()
+ assert isinstance(s, bytes)
+ if end is None:
+ end = len(s)
+ i = 0
+ for j in range(start, min(end, len(s))):
+ i += s[j] * 10 ** j
+ return i
+
+ def _get_input(self, intent='in'):
+ if intent in ['in']:
+ yield ''
+ yield '1'
+ yield '1234'
+ yield '12345'
+ yield b''
+ yield b'\0'
+ yield b'1'
+ yield b'\01'
+ yield b'1\0'
+ yield b'1234'
+ yield b'12345'
+ yield np.ndarray((), np.bytes_, buffer=b'') # array(b'', dtype='|S0')
+ yield np.array(b'') # array(b'', dtype='|S1')
+ yield np.array(b'\0')
+ yield np.array(b'1')
+ yield np.array(b'1\0')
+ yield np.array(b'\01')
+ yield np.array(b'1234')
+ yield np.array(b'123\0')
+ yield np.array(b'12345')
+
+ def test_intent_in(self):
+ for s in self._get_input():
+ r = self.module.test_in_bytes4(s)
+ # also checks that s is not changed inplace
+ expected = self._sint(s, end=4)
+ assert r == expected, (s)
+
+ def test_intent_inout(self):
+ for s in self._get_input(intent='inout'):
+ rest = self._sint(s, start=4)
+ r = self.module.test_inout_bytes4(s)
+ expected = self._sint(s, end=4)
+ assert r == expected
+
+ # check that the rest of input string is preserved
+ assert rest == self._sint(s, start=4)
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
index 5780a05bb..c4d625bd3 100644
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -1,4 +1,3 @@
-import sys
import os
import re
import functools
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index 63d42ecca..4c204cac2 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -40,7 +40,6 @@ from numpy.compat import (
from numpy import expand_dims
from numpy.core.numeric import normalize_axis_tuple
from numpy.core._internal import recursive
-from numpy.compat import pickle
__all__ = [
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
index bd5fc2ca3..c139f4640 100644
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -33,7 +33,6 @@ from .core import (
import numpy as np
from numpy import ndarray, array as nxarray
-import numpy.core.umath as umath
from numpy.core.multiarray import normalize_axis_index
from numpy.core.numeric import normalize_axis_tuple
from numpy.lib.function_base import _ureduce
diff --git a/numpy/typing/__init__.py b/numpy/typing/__init__.py
index 1bfdf07ae..04d34f0c7 100644
--- a/numpy/typing/__init__.py
+++ b/numpy/typing/__init__.py
@@ -164,11 +164,19 @@ API
from typing import TYPE_CHECKING, List
if TYPE_CHECKING:
- import sys
- if sys.version_info >= (3, 8):
- from typing import final
+ # typing_extensions is always available when type-checking
+ from typing_extensions import Literal as L
+ _HAS_TYPING_EXTENSIONS: L[True]
+else:
+ try:
+ import typing_extensions
+ except ImportError:
+ _HAS_TYPING_EXTENSIONS = False
else:
- from typing_extensions import final
+ _HAS_TYPING_EXTENSIONS = True
+
+if TYPE_CHECKING:
+ from typing_extensions import final
else:
def final(f): return f
@@ -204,14 +212,14 @@ class NBitBase:
.. code-block:: python
>>> from __future__ import annotations
- >>> from typing import TypeVar, Union, TYPE_CHECKING
+ >>> from typing import TypeVar, TYPE_CHECKING
>>> import numpy as np
>>> import numpy.typing as npt
>>> T1 = TypeVar("T1", bound=npt.NBitBase)
>>> T2 = TypeVar("T2", bound=npt.NBitBase)
- >>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[Union[T1, T2]]:
+ >>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]:
... return a + b
>>> a = np.float16()
@@ -352,6 +360,7 @@ from ._array_like import (
)
from ._generic_alias import (
NDArray as NDArray,
+ _DType,
_GenericAlias,
)
diff --git a/numpy/typing/_array_like.py b/numpy/typing/_array_like.py
index 9f57b2295..2b823ecc0 100644
--- a/numpy/typing/_array_like.py
+++ b/numpy/typing/_array_like.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import sys
-from typing import Any, overload, Sequence, TYPE_CHECKING, Union, TypeVar
+from typing import Any, Sequence, TYPE_CHECKING, Union, TypeVar
from numpy import (
ndarray,
@@ -20,25 +20,21 @@ from numpy import (
str_,
bytes_,
)
+
+from . import _HAS_TYPING_EXTENSIONS
from ._dtype_like import DTypeLike
if sys.version_info >= (3, 8):
from typing import Protocol
- HAVE_PROTOCOL = True
-else:
- try:
- from typing_extensions import Protocol
- except ImportError:
- HAVE_PROTOCOL = False
- else:
- HAVE_PROTOCOL = True
+elif _HAS_TYPING_EXTENSIONS:
+ from typing_extensions import Protocol
_T = TypeVar("_T")
_ScalarType = TypeVar("_ScalarType", bound=generic)
_DType = TypeVar("_DType", bound="dtype[Any]")
_DType_co = TypeVar("_DType_co", covariant=True, bound="dtype[Any]")
-if TYPE_CHECKING or HAVE_PROTOCOL:
+if TYPE_CHECKING or _HAS_TYPING_EXTENSIONS:
# The `_SupportsArray` protocol only cares about the default dtype
# (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
# array.
diff --git a/numpy/typing/_callable.py b/numpy/typing/_callable.py
index d9cb0f157..54f9b1425 100644
--- a/numpy/typing/_callable.py
+++ b/numpy/typing/_callable.py
@@ -43,25 +43,17 @@ from ._scalars import (
_BoolLike_co,
_IntLike_co,
_FloatLike_co,
- _ComplexLike_co,
_NumberLike_co,
)
-from . import NBitBase
-from ._array_like import ArrayLike
+from . import NBitBase, _HAS_TYPING_EXTENSIONS
from ._generic_alias import NDArray
if sys.version_info >= (3, 8):
from typing import Protocol
- HAVE_PROTOCOL = True
-else:
- try:
- from typing_extensions import Protocol
- except ImportError:
- HAVE_PROTOCOL = False
- else:
- HAVE_PROTOCOL = True
-
-if TYPE_CHECKING or HAVE_PROTOCOL:
+elif _HAS_TYPING_EXTENSIONS:
+ from typing_extensions import Protocol
+
+if TYPE_CHECKING or _HAS_TYPING_EXTENSIONS:
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
_2Tuple = Tuple[_T1, _T1]
@@ -110,7 +102,7 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
class _BoolTrueDiv(Protocol):
@overload
- def __call__(self, __other: Union[float, _IntLike_co]) -> float64: ...
+ def __call__(self, __other: float | _IntLike_co) -> float64: ...
@overload
def __call__(self, __other: complex) -> complex128: ...
@overload
@@ -134,7 +126,7 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
@overload # platform dependent
def __call__(self, __other: int) -> _2Tuple[int_]: ...
@overload
- def __call__(self, __other: float) -> _2Tuple[floating[Union[_NBit1, _NBitDouble]]]: ...
+ def __call__(self, __other: float) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(self, __other: _IntType) -> _2Tuple[_IntType]: ...
@overload
@@ -152,15 +144,15 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
@overload
def __call__(self, __other: bool) -> floating[_NBit1]: ...
@overload
- def __call__(self, __other: int) -> floating[Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> floating[_NBit1 | _NBitInt]: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: complex
- ) -> complexfloating[Union[_NBit1, _NBitDouble], Union[_NBit1, _NBitDouble]]: ...
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
- def __call__(self, __other: integer[_NBit2]) -> floating[Union[_NBit1, _NBit2]]: ...
+ def __call__(self, __other: integer[_NBit2]) -> floating[_NBit1 | _NBit2]: ...
class _UnsignedIntOp(Protocol[_NBit1]):
# NOTE: `uint64 + signedinteger -> float64`
@@ -168,18 +160,18 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
def __call__(self, __other: bool) -> unsignedinteger[_NBit1]: ...
@overload
def __call__(
- self, __other: Union[int, signedinteger[Any]]
+ self, __other: int | signedinteger[Any]
) -> Any: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: complex
- ) -> complexfloating[Union[_NBit1, _NBitDouble], Union[_NBit1, _NBitDouble]]: ...
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: unsignedinteger[_NBit2]
- ) -> unsignedinteger[Union[_NBit1, _NBit2]]: ...
+ ) -> unsignedinteger[_NBit1 | _NBit2]: ...
class _UnsignedIntBitOp(Protocol[_NBit1]):
@overload
@@ -191,135 +183,135 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
@overload
def __call__(
self, __other: unsignedinteger[_NBit2]
- ) -> unsignedinteger[Union[_NBit1, _NBit2]]: ...
+ ) -> unsignedinteger[_NBit1 | _NBit2]: ...
class _UnsignedIntMod(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> unsignedinteger[_NBit1]: ...
@overload
def __call__(
- self, __other: Union[int, signedinteger[Any]]
+ self, __other: int | signedinteger[Any]
) -> Any: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: unsignedinteger[_NBit2]
- ) -> unsignedinteger[Union[_NBit1, _NBit2]]: ...
+ ) -> unsignedinteger[_NBit1 | _NBit2]: ...
class _UnsignedIntDivMod(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> _2Tuple[signedinteger[_NBit1]]: ...
@overload
def __call__(
- self, __other: Union[int, signedinteger[Any]]
+ self, __other: int | signedinteger[Any]
) -> _2Tuple[Any]: ...
@overload
- def __call__(self, __other: float) -> _2Tuple[floating[Union[_NBit1, _NBitDouble]]]: ...
+ def __call__(self, __other: float) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(
self, __other: unsignedinteger[_NBit2]
- ) -> _2Tuple[unsignedinteger[Union[_NBit1, _NBit2]]]: ...
+ ) -> _2Tuple[unsignedinteger[_NBit1 | _NBit2]]: ...
class _SignedIntOp(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> signedinteger[_NBit1]: ...
@overload
- def __call__(self, __other: int) -> signedinteger[Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> signedinteger[_NBit1 | _NBitInt]: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: complex
- ) -> complexfloating[Union[_NBit1, _NBitDouble], Union[_NBit1, _NBitDouble]]: ...
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: signedinteger[_NBit2]
- ) -> signedinteger[Union[_NBit1, _NBit2]]: ...
+ ) -> signedinteger[_NBit1 | _NBit2]: ...
class _SignedIntBitOp(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> signedinteger[_NBit1]: ...
@overload
- def __call__(self, __other: int) -> signedinteger[Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> signedinteger[_NBit1 | _NBitInt]: ...
@overload
def __call__(
self, __other: signedinteger[_NBit2]
- ) -> signedinteger[Union[_NBit1, _NBit2]]: ...
+ ) -> signedinteger[_NBit1 | _NBit2]: ...
class _SignedIntMod(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> signedinteger[_NBit1]: ...
@overload
- def __call__(self, __other: int) -> signedinteger[Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> signedinteger[_NBit1 | _NBitInt]: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: signedinteger[_NBit2]
- ) -> signedinteger[Union[_NBit1, _NBit2]]: ...
+ ) -> signedinteger[_NBit1 | _NBit2]: ...
class _SignedIntDivMod(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> _2Tuple[signedinteger[_NBit1]]: ...
@overload
- def __call__(self, __other: int) -> _2Tuple[signedinteger[Union[_NBit1, _NBitInt]]]: ...
+ def __call__(self, __other: int) -> _2Tuple[signedinteger[_NBit1 | _NBitInt]]: ...
@overload
- def __call__(self, __other: float) -> _2Tuple[floating[Union[_NBit1, _NBitDouble]]]: ...
+ def __call__(self, __other: float) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(
self, __other: signedinteger[_NBit2]
- ) -> _2Tuple[signedinteger[Union[_NBit1, _NBit2]]]: ...
+ ) -> _2Tuple[signedinteger[_NBit1 | _NBit2]]: ...
class _FloatOp(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> floating[_NBit1]: ...
@overload
- def __call__(self, __other: int) -> floating[Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> floating[_NBit1 | _NBitInt]: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, __other: complex
- ) -> complexfloating[Union[_NBit1, _NBitDouble], Union[_NBit1, _NBitDouble]]: ...
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
- self, __other: Union[integer[_NBit2], floating[_NBit2]]
- ) -> floating[Union[_NBit1, _NBit2]]: ...
+ self, __other: integer[_NBit2] | floating[_NBit2]
+ ) -> floating[_NBit1 | _NBit2]: ...
class _FloatMod(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> floating[_NBit1]: ...
@overload
- def __call__(self, __other: int) -> floating[Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> floating[_NBit1 | _NBitInt]: ...
@overload
- def __call__(self, __other: float) -> floating[Union[_NBit1, _NBitDouble]]: ...
+ def __call__(self, __other: float) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
- self, __other: Union[integer[_NBit2], floating[_NBit2]]
- ) -> floating[Union[_NBit1, _NBit2]]: ...
+ self, __other: integer[_NBit2] | floating[_NBit2]
+ ) -> floating[_NBit1 | _NBit2]: ...
class _FloatDivMod(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> _2Tuple[floating[_NBit1]]: ...
@overload
- def __call__(self, __other: int) -> _2Tuple[floating[Union[_NBit1, _NBitInt]]]: ...
+ def __call__(self, __other: int) -> _2Tuple[floating[_NBit1 | _NBitInt]]: ...
@overload
- def __call__(self, __other: float) -> _2Tuple[floating[Union[_NBit1, _NBitDouble]]]: ...
+ def __call__(self, __other: float) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(
- self, __other: Union[integer[_NBit2], floating[_NBit2]]
- ) -> _2Tuple[floating[Union[_NBit1, _NBit2]]]: ...
+ self, __other: integer[_NBit2] | floating[_NBit2]
+ ) -> _2Tuple[floating[_NBit1 | _NBit2]]: ...
class _ComplexOp(Protocol[_NBit1]):
@overload
def __call__(self, __other: bool) -> complexfloating[_NBit1, _NBit1]: ...
@overload
- def __call__(self, __other: int) -> complexfloating[Union[_NBit1, _NBitInt], Union[_NBit1, _NBitInt]]: ...
+ def __call__(self, __other: int) -> complexfloating[_NBit1 | _NBitInt, _NBit1 | _NBitInt]: ...
@overload
def __call__(
- self, __other: Union[float, complex]
- ) -> complexfloating[Union[_NBit1, _NBitDouble], Union[_NBit1, _NBitDouble]]: ...
+ self, __other: complex
+ ) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self,
@@ -328,7 +320,7 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
floating[_NBit2],
complexfloating[_NBit2, _NBit2],
]
- ) -> complexfloating[Union[_NBit1, _NBit2], Union[_NBit1, _NBit2]]: ...
+ ) -> complexfloating[_NBit1 | _NBit2, _NBit1 | _NBit2]: ...
class _NumberOp(Protocol):
def __call__(self, __other: _NumberLike_co) -> Any: ...
@@ -340,25 +332,25 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
def __call__(self, __other: _T2) -> NDArray[bool_]: ...
else:
- _BoolOp = Any
- _BoolBitOp = Any
- _BoolSub = Any
- _BoolTrueDiv = Any
- _BoolMod = Any
- _BoolDivMod = Any
- _TD64Div = Any
- _IntTrueDiv = Any
- _UnsignedIntOp = Any
- _UnsignedIntBitOp = Any
- _UnsignedIntMod = Any
- _UnsignedIntDivMod = Any
- _SignedIntOp = Any
- _SignedIntBitOp = Any
- _SignedIntMod = Any
- _SignedIntDivMod = Any
- _FloatOp = Any
- _FloatMod = Any
- _FloatDivMod = Any
- _ComplexOp = Any
- _NumberOp = Any
- _ComparisonOp = Any
+ _BoolOp = NotImplemented
+ _BoolBitOp = NotImplemented
+ _BoolSub = NotImplemented
+ _BoolTrueDiv = NotImplemented
+ _BoolMod = NotImplemented
+ _BoolDivMod = NotImplemented
+ _TD64Div = NotImplemented
+ _IntTrueDiv = NotImplemented
+ _UnsignedIntOp = NotImplemented
+ _UnsignedIntBitOp = NotImplemented
+ _UnsignedIntMod = NotImplemented
+ _UnsignedIntDivMod = NotImplemented
+ _SignedIntOp = NotImplemented
+ _SignedIntBitOp = NotImplemented
+ _SignedIntMod = NotImplemented
+ _SignedIntDivMod = NotImplemented
+ _FloatOp = NotImplemented
+ _FloatMod = NotImplemented
+ _FloatDivMod = NotImplemented
+ _ComplexOp = NotImplemented
+ _NumberOp = NotImplemented
+ _ComparisonOp = NotImplemented
diff --git a/numpy/typing/_char_codes.py b/numpy/typing/_char_codes.py
index 6b6f7ae88..6b33f995d 100644
--- a/numpy/typing/_char_codes.py
+++ b/numpy/typing/_char_codes.py
@@ -1,18 +1,14 @@
import sys
from typing import Any, TYPE_CHECKING
+from . import _HAS_TYPING_EXTENSIONS
+
if sys.version_info >= (3, 8):
from typing import Literal
- HAVE_LITERAL = True
-else:
- try:
- from typing_extensions import Literal
- except ImportError:
- HAVE_LITERAL = False
- else:
- HAVE_LITERAL = True
-
-if TYPE_CHECKING or HAVE_LITERAL:
+elif _HAS_TYPING_EXTENSIONS:
+ from typing_extensions import Literal
+
+if TYPE_CHECKING or _HAS_TYPING_EXTENSIONS:
_BoolCodes = Literal["?", "=?", "<?", ">?", "bool", "bool_", "bool8"]
_UInt8Codes = Literal["uint8", "u1", "=u1", "<u1", ">u1"]
@@ -124,52 +120,52 @@ if TYPE_CHECKING or HAVE_LITERAL:
]
else:
- _BoolCodes = Any
-
- _UInt8Codes = Any
- _UInt16Codes = Any
- _UInt32Codes = Any
- _UInt64Codes = Any
-
- _Int8Codes = Any
- _Int16Codes = Any
- _Int32Codes = Any
- _Int64Codes = Any
-
- _Float16Codes = Any
- _Float32Codes = Any
- _Float64Codes = Any
-
- _Complex64Codes = Any
- _Complex128Codes = Any
-
- _ByteCodes = Any
- _ShortCodes = Any
- _IntCCodes = Any
- _IntPCodes = Any
- _IntCodes = Any
- _LongLongCodes = Any
-
- _UByteCodes = Any
- _UShortCodes = Any
- _UIntCCodes = Any
- _UIntPCodes = Any
- _UIntCodes = Any
- _ULongLongCodes = Any
-
- _HalfCodes = Any
- _SingleCodes = Any
- _DoubleCodes = Any
- _LongDoubleCodes = Any
-
- _CSingleCodes = Any
- _CDoubleCodes = Any
- _CLongDoubleCodes = Any
-
- _StrCodes = Any
- _BytesCodes = Any
- _VoidCodes = Any
- _ObjectCodes = Any
-
- _DT64Codes = Any
- _TD64Codes = Any
+ _BoolCodes = NotImplemented
+
+ _UInt8Codes = NotImplemented
+ _UInt16Codes = NotImplemented
+ _UInt32Codes = NotImplemented
+ _UInt64Codes = NotImplemented
+
+ _Int8Codes = NotImplemented
+ _Int16Codes = NotImplemented
+ _Int32Codes = NotImplemented
+ _Int64Codes = NotImplemented
+
+ _Float16Codes = NotImplemented
+ _Float32Codes = NotImplemented
+ _Float64Codes = NotImplemented
+
+ _Complex64Codes = NotImplemented
+ _Complex128Codes = NotImplemented
+
+ _ByteCodes = NotImplemented
+ _ShortCodes = NotImplemented
+ _IntCCodes = NotImplemented
+ _IntPCodes = NotImplemented
+ _IntCodes = NotImplemented
+ _LongLongCodes = NotImplemented
+
+ _UByteCodes = NotImplemented
+ _UShortCodes = NotImplemented
+ _UIntCCodes = NotImplemented
+ _UIntPCodes = NotImplemented
+ _UIntCodes = NotImplemented
+ _ULongLongCodes = NotImplemented
+
+ _HalfCodes = NotImplemented
+ _SingleCodes = NotImplemented
+ _DoubleCodes = NotImplemented
+ _LongDoubleCodes = NotImplemented
+
+ _CSingleCodes = NotImplemented
+ _CDoubleCodes = NotImplemented
+ _CLongDoubleCodes = NotImplemented
+
+ _StrCodes = NotImplemented
+ _BytesCodes = NotImplemented
+ _VoidCodes = NotImplemented
+ _ObjectCodes = NotImplemented
+
+ _DT64Codes = NotImplemented
+ _TD64Codes = NotImplemented
diff --git a/numpy/typing/_dtype_like.py b/numpy/typing/_dtype_like.py
index a41e2f358..405cc4a3c 100644
--- a/numpy/typing/_dtype_like.py
+++ b/numpy/typing/_dtype_like.py
@@ -2,18 +2,20 @@ import sys
from typing import Any, List, Sequence, Tuple, Union, Type, TypeVar, TYPE_CHECKING
import numpy as np
+
+from . import _HAS_TYPING_EXTENSIONS
from ._shape import _ShapeLike
+from ._generic_alias import _DType as DType
if sys.version_info >= (3, 8):
from typing import Protocol, TypedDict
- HAVE_PROTOCOL = True
+elif _HAS_TYPING_EXTENSIONS:
+ from typing_extensions import Protocol, TypedDict
+
+if sys.version_info >= (3, 9):
+ from types import GenericAlias
else:
- try:
- from typing_extensions import Protocol, TypedDict
- except ImportError:
- HAVE_PROTOCOL = False
- else:
- HAVE_PROTOCOL = True
+ from ._generic_alias import _GenericAlias as GenericAlias
from ._char_codes import (
_BoolCodes,
@@ -58,8 +60,9 @@ from ._char_codes import (
)
_DTypeLikeNested = Any # TODO: wait for support for recursive types
+_DType_co = TypeVar("_DType_co", covariant=True, bound=DType[Any])
-if TYPE_CHECKING or HAVE_PROTOCOL:
+if TYPE_CHECKING or _HAS_TYPING_EXTENSIONS:
# Mandatory keys
class _DTypeDictBase(TypedDict):
names: Sequence[str]
@@ -72,16 +75,16 @@ if TYPE_CHECKING or HAVE_PROTOCOL:
itemsize: int
aligned: bool
- _DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype)
-
# A protocol for anything with the dtype attribute
class _SupportsDType(Protocol[_DType_co]):
@property
def dtype(self) -> _DType_co: ...
else:
- _DTypeDict = Any
- _SupportsDType = Any
+ _DTypeDict = NotImplemented
+
+ class _SupportsDType: ...
+ _SupportsDType = GenericAlias(_SupportsDType, _DType_co)
# Would create a dtype[np.void]
@@ -106,13 +109,13 @@ _VoidDTypeLike = Union[
# Anything that can be coerced into numpy.dtype.
# Reference: https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
DTypeLike = Union[
- np.dtype,
+ DType[Any],
# default data type (float64)
None,
# array-scalar types and generic types
- type, # TODO: enumerate these when we add type hints for numpy scalars
+ Type[Any], # TODO: enumerate these when we add type hints for numpy scalars
# anything with a dtype attribute
- "_SupportsDType[np.dtype[Any]]",
+ _SupportsDType[DType[Any]],
# character codes, type strings or comma-separated fields, e.g., 'float64'
str,
_VoidDTypeLike,
@@ -130,14 +133,14 @@ DTypeLike = Union[
_DTypeLikeBool = Union[
Type[bool],
Type[np.bool_],
- "np.dtype[np.bool_]",
- "_SupportsDType[np.dtype[np.bool_]]",
+ DType[np.bool_],
+ _SupportsDType[DType[np.bool_]],
_BoolCodes,
]
_DTypeLikeUInt = Union[
Type[np.unsignedinteger],
- "np.dtype[np.unsignedinteger]",
- "_SupportsDType[np.dtype[np.unsignedinteger]]",
+ DType[np.unsignedinteger],
+ _SupportsDType[DType[np.unsignedinteger]],
_UInt8Codes,
_UInt16Codes,
_UInt32Codes,
@@ -152,8 +155,8 @@ _DTypeLikeUInt = Union[
_DTypeLikeInt = Union[
Type[int],
Type[np.signedinteger],
- "np.dtype[np.signedinteger]",
- "_SupportsDType[np.dtype[np.signedinteger]]",
+ DType[np.signedinteger],
+ _SupportsDType[DType[np.signedinteger]],
_Int8Codes,
_Int16Codes,
_Int32Codes,
@@ -168,8 +171,8 @@ _DTypeLikeInt = Union[
_DTypeLikeFloat = Union[
Type[float],
Type[np.floating],
- "np.dtype[np.floating]",
- "_SupportsDType[np.dtype[np.floating]]",
+ DType[np.floating],
+ _SupportsDType[DType[np.floating]],
_Float16Codes,
_Float32Codes,
_Float64Codes,
@@ -181,8 +184,8 @@ _DTypeLikeFloat = Union[
_DTypeLikeComplex = Union[
Type[complex],
Type[np.complexfloating],
- "np.dtype[np.complexfloating]",
- "_SupportsDType[np.dtype[np.complexfloating]]",
+ DType[np.complexfloating],
+ _SupportsDType[DType[np.complexfloating]],
_Complex64Codes,
_Complex128Codes,
_CSingleCodes,
@@ -191,41 +194,41 @@ _DTypeLikeComplex = Union[
]
_DTypeLikeDT64 = Union[
Type[np.timedelta64],
- "np.dtype[np.timedelta64]",
- "_SupportsDType[np.dtype[np.timedelta64]]",
+ DType[np.timedelta64],
+ _SupportsDType[DType[np.timedelta64]],
_TD64Codes,
]
_DTypeLikeTD64 = Union[
Type[np.datetime64],
- "np.dtype[np.datetime64]",
- "_SupportsDType[np.dtype[np.datetime64]]",
+ DType[np.datetime64],
+ _SupportsDType[DType[np.datetime64]],
_DT64Codes,
]
_DTypeLikeStr = Union[
Type[str],
Type[np.str_],
- "np.dtype[np.str_]",
- "_SupportsDType[np.dtype[np.str_]]",
+ DType[np.str_],
+ _SupportsDType[DType[np.str_]],
_StrCodes,
]
_DTypeLikeBytes = Union[
Type[bytes],
Type[np.bytes_],
- "np.dtype[np.bytes_]",
- "_SupportsDType[np.dtype[np.bytes_]]",
+ DType[np.bytes_],
+ _SupportsDType[DType[np.bytes_]],
_BytesCodes,
]
_DTypeLikeVoid = Union[
Type[np.void],
- "np.dtype[np.void]",
- "_SupportsDType[np.dtype[np.void]]",
+ DType[np.void],
+ _SupportsDType[DType[np.void]],
_VoidCodes,
_VoidDTypeLike,
]
_DTypeLikeObject = Union[
type,
- "np.dtype[np.object_]",
- "_SupportsDType[np.dtype[np.object_]]",
+ DType[np.object_],
+ _SupportsDType[DType[np.object_]],
_ObjectCodes,
]
diff --git a/numpy/typing/_generic_alias.py b/numpy/typing/_generic_alias.py
index 68523827a..0d30f54ca 100644
--- a/numpy/typing/_generic_alias.py
+++ b/numpy/typing/_generic_alias.py
@@ -199,6 +199,7 @@ else:
ScalarType = TypeVar("ScalarType", bound=np.generic, covariant=True)
if TYPE_CHECKING:
+ _DType = np.dtype[ScalarType]
NDArray = np.ndarray[Any, np.dtype[ScalarType]]
elif sys.version_info >= (3, 9):
_DType = types.GenericAlias(np.dtype, (ScalarType,))
diff --git a/numpy/typing/_shape.py b/numpy/typing/_shape.py
index b720c3ffc..0742be8a9 100644
--- a/numpy/typing/_shape.py
+++ b/numpy/typing/_shape.py
@@ -1,13 +1,14 @@
import sys
from typing import Sequence, Tuple, Union
+from . import _HAS_TYPING_EXTENSIONS
+
if sys.version_info >= (3, 8):
from typing import SupportsIndex
+elif _HAS_TYPING_EXTENSIONS:
+ from typing_extensions import SupportsIndex
else:
- try:
- from typing_extensions import SupportsIndex
- except ImportError:
- SupportsIndex = NotImplemented
+ SupportsIndex = NotImplemented
_Shape = Tuple[int, ...]
diff --git a/numpy/typing/_ufunc.pyi b/numpy/typing/_ufunc.pyi
index b3b9fa95e..f4fead504 100644
--- a/numpy/typing/_ufunc.pyi
+++ b/numpy/typing/_ufunc.pyi
@@ -11,11 +11,9 @@ from typing import (
Any,
Generic,
List,
- Optional,
overload,
Tuple,
TypeVar,
- Union,
)
from numpy import ufunc, _Casting, _OrderKACF
@@ -82,26 +80,26 @@ class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
__x1: _ScalarLike_co,
out: None = ...,
*,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _2Tuple[Optional[str]]] = ...,
+ signature: str | _2Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> Any: ...
@overload
def __call__(
self,
__x1: ArrayLike,
- out: Union[None, NDArray[Any], Tuple[NDArray[Any]]] = ...,
+ out: None | NDArray[Any] | Tuple[NDArray[Any]] = ...,
*,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _2Tuple[Optional[str]]] = ...,
+ signature: str | _2Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> NDArray[Any]: ...
@@ -134,12 +132,12 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
__x2: _ScalarLike_co,
out: None = ...,
*,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> Any: ...
@overload
@@ -147,14 +145,14 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
self,
__x1: ArrayLike,
__x2: ArrayLike,
- out: Union[None, NDArray[Any], Tuple[NDArray[Any]]] = ...,
+ out: None | NDArray[Any] | Tuple[NDArray[Any]] = ...,
*,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> NDArray[Any]: ...
@@ -168,9 +166,9 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
def reduce(
self,
array: ArrayLike,
- axis: Optional[_ShapeLike] = ...,
+ axis: None | _ShapeLike = ...,
dtype: DTypeLike = ...,
- out: Optional[NDArray[Any]] = ...,
+ out: None | NDArray[Any] = ...,
keepdims: bool = ...,
initial: Any = ...,
where: _ArrayLikeBool_co = ...,
@@ -181,7 +179,7 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
array: ArrayLike,
axis: SupportsIndex = ...,
dtype: DTypeLike = ...,
- out: Optional[NDArray[Any]] = ...,
+ out: None | NDArray[Any] = ...,
) -> NDArray[Any]: ...
def reduceat(
@@ -190,7 +188,7 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
indices: _ArrayLikeInt_co,
axis: SupportsIndex = ...,
dtype: DTypeLike = ...,
- out: Optional[NDArray[Any]] = ...,
+ out: None | NDArray[Any] = ...,
) -> NDArray[Any]: ...
# Expand `**kwargs` into explicit keyword-only arguments
@@ -201,12 +199,12 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
__B: _ScalarLike_co,
*,
out: None = ...,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> Any: ...
@overload
@@ -215,13 +213,13 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
__A: ArrayLike,
__B: ArrayLike,
*,
- out: Union[None, NDArray[Any], Tuple[NDArray[Any]]] = ...,
- where: Optional[_ArrayLikeBool_co] = ...,
+ out: None | NDArray[Any] | Tuple[NDArray[Any]] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> NDArray[Any]: ...
@@ -258,28 +256,28 @@ class _UFunc_Nin1_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):
__out1: None = ...,
__out2: None = ...,
*,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> _2Tuple[Any]: ...
@overload
def __call__(
self,
__x1: ArrayLike,
- __out1: Optional[NDArray[Any]] = ...,
- __out2: Optional[NDArray[Any]] = ...,
+ __out1: None | NDArray[Any] = ...,
+ __out2: None | NDArray[Any] = ...,
*,
out: _2Tuple[NDArray[Any]] = ...,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> _2Tuple[NDArray[Any]]: ...
@@ -317,12 +315,12 @@ class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):
__out1: None = ...,
__out2: None = ...,
*,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _4Tuple[Optional[str]]] = ...,
+ signature: str | _4Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> _2Tuple[Any]: ...
@overload
@@ -330,16 +328,16 @@ class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):
self,
__x1: ArrayLike,
__x2: ArrayLike,
- __out1: Optional[NDArray[Any]] = ...,
- __out2: Optional[NDArray[Any]] = ...,
+ __out1: None | NDArray[Any] = ...,
+ __out2: None | NDArray[Any] = ...,
*,
out: _2Tuple[NDArray[Any]] = ...,
- where: Optional[_ArrayLikeBool_co] = ...,
+ where: None | _ArrayLikeBool_co = ...,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _4Tuple[Optional[str]]] = ...,
+ signature: str | _4Tuple[None | str] = ...,
extobj: List[Any] = ...,
) -> _2Tuple[NDArray[Any]]: ...
@@ -384,7 +382,7 @@ class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
axes: List[_2Tuple[SupportsIndex]] = ...,
) -> Any: ...
@@ -393,13 +391,13 @@ class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
self,
__x1: ArrayLike,
__x2: ArrayLike,
- out: Union[NDArray[Any], Tuple[NDArray[Any]]],
+ out: NDArray[Any] | Tuple[NDArray[Any]],
*,
casting: _Casting = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
- signature: Union[str, _3Tuple[Optional[str]]] = ...,
+ signature: str | _3Tuple[None | str] = ...,
extobj: List[Any] = ...,
axes: List[_2Tuple[SupportsIndex]] = ...,
) -> NDArray[Any]: ...
diff --git a/numpy/typing/mypy_plugin.py b/numpy/typing/mypy_plugin.py
index 901bf4fb1..100e0d957 100644
--- a/numpy/typing/mypy_plugin.py
+++ b/numpy/typing/mypy_plugin.py
@@ -14,7 +14,7 @@ try:
from mypy.build import PRI_MED
_HookFunc = t.Callable[[AnalyzeTypeContext], Type]
- MYPY_EX: t.Optional[ModuleNotFoundError] = None
+ MYPY_EX: None | ModuleNotFoundError = None
except ModuleNotFoundError as ex:
MYPY_EX = ex
@@ -90,7 +90,7 @@ if t.TYPE_CHECKING or MYPY_EX is None:
class _NumpyPlugin(Plugin):
"""A plugin for assigning platform-specific `numpy.number` precisions."""
- def get_type_analyze_hook(self, fullname: str) -> t.Optional[_HookFunc]:
+ def get_type_analyze_hook(self, fullname: str) -> None | _HookFunc:
"""Set the precision of platform-specific `numpy.number` subclasses.
For example: `numpy.int_`, `numpy.longlong` and `numpy.longdouble`.