diff options
author | Charles Harris <charlesr.harris@gmail.com> | 2020-09-07 11:04:05 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-07 11:04:05 -0600 |
commit | 16821b94e973196a5d335ad2c2a059c48d953a1e (patch) | |
tree | 023f466c2c5e1e1992f45b968b246d9ab3181113 | |
parent | 1cb5f15109f0f8eb03afd662bc7c85dd6d10313a (diff) | |
parent | d15254d487fa432b3f14aa32c9e9552835f76248 (diff) | |
download | numpy-16821b94e973196a5d335ad2c2a059c48d953a1e.tar.gz |
Merge branch 'master' into ndarray-methods
28 files changed, 937 insertions, 137 deletions
diff --git a/doc/source/dev/index.rst b/doc/source/dev/index.rst index aeb277a87..c4f35b68f 100644 --- a/doc/source/dev/index.rst +++ b/doc/source/dev/index.rst @@ -4,6 +4,22 @@ Contributing to NumPy ##################### +.. TODO: this is hidden because there's a bug in the pydata theme that won't render TOC items under headers + +.. toctree:: + :hidden: + + conduct/code_of_conduct + Git Basics <gitwash/index> + development_environment + development_workflow + ../benchmarking + style_guide + releasing + governance/index + howto-docs + + Not a coder? Not a problem! NumPy is multi-faceted, and we can use a lot of help. These are all activities we'd like to get help with (they're all important, so we list them in alphabetical order): diff --git a/doc/source/glossary.rst b/doc/source/glossary.rst index fb4e0137a..d37534960 100644 --- a/doc/source/glossary.rst +++ b/doc/source/glossary.rst @@ -54,14 +54,6 @@ Glossary Any sequence that can be interpreted as an ndarray. This includes nested lists, tuples, scalars and existing arrays. - attribute - A property of an object that can be accessed using ``obj.attribute``, - e.g., ``shape`` is an attribute of an array:: - - >>> x = np.array([1, 2, 3]) - >>> x.shape - (3,) - big-endian When storing a multi-byte value in memory as a sequence of bytes, the sequence addresses/sends/stores the most significant byte first (lowest @@ -179,19 +171,6 @@ Glossary An object that cannot be modified after execution is called immutable. Two common examples are strings and tuples. - instance - A class definition gives the blueprint for constructing an object:: - - >>> class House: - ... wall_colour = 'white' - - Yet, we have to *build* a house before it exists:: - - >>> h = House() # build a house - - Now, ``h`` is called a ``House`` instance. An instance is therefore - a specific realisation of a class. - iterable A sequence that allows "walking" (iterating) over items, typically using a loop such as:: @@ -297,14 +276,6 @@ Glossary matrix([[ 7, 10], [15, 22]]) - method - A function associated with an object. For example, each ndarray has a - method called ``repeat``:: - - >>> x = np.array([1, 2, 3]) - >>> x.repeat(2) - array([1, 1, 2, 2, 3, 3]) - ndarray See *array*. @@ -332,21 +303,6 @@ Glossary Row-major order is also known as the C order, as the C programming language uses it. New NumPy arrays are by default in row-major order. - self - Often seen in method signatures, ``self`` refers to the instance - of the associated class. For example: - - >>> class Paintbrush: - ... color = 'blue' - ... - ... def paint(self): - ... print("Painting the city %s!" % self.color) - ... - >>> p = Paintbrush() - >>> p.color = 'red' - >>> p.paint() # self refers to 'p' - Painting the city red! - slice Used to select only certain elements from a sequence: @@ -374,9 +330,6 @@ Glossary >>> x[:, 1] array([2, 4]) - structure - See :term:`structured data type` - structured data type A data type composed of other datatypes @@ -394,41 +347,6 @@ Glossary associated :ref:`title <titles>` which is an alias to the name and is commonly used for plotting. - tuple - A sequence that may contain a variable number of types of any - kind. A tuple is immutable, i.e., once constructed it cannot be - changed. Similar to a list, it can be indexed and sliced:: - - >>> x = (1, 'one', [1, 2]) - >>> x - (1, 'one', [1, 2]) - - >>> x[0] - 1 - - >>> x[:2] - (1, 'one') - - A useful concept is "tuple unpacking", which allows variables to - be assigned to the contents of a tuple:: - - >>> x, y = (1, 2) - >>> x, y = 1, 2 - - This is often used when a function returns multiple values: - - >>> def return_many(): - ... return 1, 'alpha', None - - >>> a, b, c = return_many() - >>> a, b, c - (1, 'alpha', None) - - >>> a - 1 - >>> b - 'alpha' - ufunc Universal function. A fast element-wise, :term:`vectorized <vectorization>` array operation. Examples include ``add``, ``sin`` and diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 02862d1cd..666e5fc16 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -35,9 +35,41 @@ from typing import ( ) if sys.version_info >= (3, 8): - from typing import Literal, Protocol + from typing import Literal, Protocol, SupportsIndex else: from typing_extensions import Literal, Protocol + class SupportsIndex(Protocol): + def __index__(self) -> int: ... + +# Ensures that the stubs are picked up +from . import ( + char, + compat, + core, + ctypeslib, + emath, + fft, + lib, + linalg, + ma, + matrixlib, + polynomial, + random, + rec, + testing, + version, +) + +from numpy.core.function_base import ( + linspace, + logspace, + geomspace, +) + +# Add an object to `__all__` if their stubs are defined in an external file; +# their stubs will not be recognized otherwise. +# NOTE: This is redundant for objects defined within this file. +__all__ = ["linspace", "logspace", "geomspace"] # TODO: remove when the full numpy namespace is defined def __getattr__(name: str) -> Any: ... @@ -425,37 +457,56 @@ class ndarray(_ArrayOrScalarCommon, Iterable, Sized, Container): # See https://github.com/numpy/numpy-stubs/pull/80 for more details. +_CharLike = Union[str, bytes] + class generic(_ArrayOrScalarCommon): @abstractmethod def __init__(self, *args: Any, **kwargs: Any) -> None: ... @property def base(self) -> None: ... -class _real_generic(generic): # type: ignore +class number(generic): # type: ignore @property def real(self: _ArraySelf) -> _ArraySelf: ... @property def imag(self: _ArraySelf) -> _ArraySelf: ... -class number(generic): ... # type: ignore - -class bool_(_real_generic): +class bool_(generic): def __init__(self, __value: object = ...) -> None: ... + @property + def real(self: _ArraySelf) -> _ArraySelf: ... + @property + def imag(self: _ArraySelf) -> _ArraySelf: ... class object_(generic): def __init__(self, __value: object = ...) -> None: ... + @property + def real(self: _ArraySelf) -> _ArraySelf: ... + @property + def imag(self: _ArraySelf) -> _ArraySelf: ... -class datetime64: +class datetime64(generic): @overload def __init__( self, - __value: Union[None, datetime64, str, dt.datetime] = ..., - __format: str = ... + __value: Union[None, datetime64, _CharLike, dt.datetime] = ..., + __format: Union[_CharLike, Tuple[_CharLike, _IntLike]] = ..., ) -> None: ... @overload - def __init__(self, __value: int, __format: str) -> None: ... + def __init__(self, __value: int, __format: Union[_CharLike, Tuple[_CharLike, _IntLike]]) -> None: ... def __add__(self, other: Union[timedelta64, int]) -> datetime64: ... def __sub__(self, other: Union[timedelta64, datetime64, int]) -> timedelta64: ... + def __rsub__(self, other: Union[datetime64, int]) -> timedelta64: ... + +# Support for `__index__` was added in python 3.8 (bpo-20092) +if sys.version_info >= (3, 8): + _IntValue = Union[SupportsInt, _CharLike, SupportsIndex] + _FloatValue = Union[None, _CharLike, SupportsFloat, SupportsIndex] + _ComplexValue = Union[None, _CharLike, SupportsFloat, SupportsComplex, SupportsIndex] +else: + _IntValue = Union[SupportsInt, _CharLike] + _FloatValue = Union[None, _CharLike, SupportsFloat] + _ComplexValue = Union[None, _CharLike, SupportsFloat, SupportsComplex] class integer(number, _real_generic): # type: ignore # NOTE: `__index__` is technically defined in the bottom-most @@ -465,19 +516,23 @@ class integer(number, _real_generic): # type: ignore class signedinteger(integer): ... # type: ignore class int8(signedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class int16(signedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class int32(signedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class int64(signedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class timedelta64(signedinteger): - def __init__(self, __value: Any = ..., __format: str = ...) -> None: ... + def __init__( + self, + __value: Union[None, int, _CharLike, dt.timedelta, timedelta64] = ..., + __format: Union[_CharLike, Tuple[_CharLike, _IntLike]] = ..., + ) -> None: ... @overload def __add__(self, other: Union[timedelta64, int]) -> timedelta64: ... @overload @@ -492,71 +547,69 @@ class timedelta64(signedinteger): class unsignedinteger(integer): ... # type: ignore class uint8(unsignedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class uint16(unsignedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class uint32(unsignedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class uint64(unsignedinteger): - def __init__(self, __value: SupportsInt = ...) -> None: ... + def __init__(self, __value: _IntValue = ...) -> None: ... class inexact(number): ... # type: ignore -class floating(inexact, _real_generic): ... # type: ignore +class floating(inexact): ... # type: ignore _FloatType = TypeVar('_FloatType', bound=floating) class float16(floating): - def __init__(self, __value: Optional[SupportsFloat] = ...) -> None: ... + def __init__(self, __value: _FloatValue = ...) -> None: ... class float32(floating): - def __init__(self, __value: Optional[SupportsFloat] = ...) -> None: ... + def __init__(self, __value: _FloatValue = ...) -> None: ... -class float64(floating): - def __init__(self, __value: Optional[SupportsFloat] = ...) -> None: ... +class float64(floating, float): + def __init__(self, __value: _FloatValue = ...) -> None: ... class complexfloating(inexact, Generic[_FloatType]): # type: ignore @property - def real(self) -> _FloatType: ... + def real(self) -> _FloatType: ... # type: ignore[override] @property - def imag(self) -> _FloatType: ... + def imag(self) -> _FloatType: ... # type: ignore[override] def __abs__(self) -> _FloatType: ... # type: ignore[override] class complex64(complexfloating[float32]): - def __init__( - self, - __value: Union[None, SupportsInt, SupportsFloat, SupportsComplex] = ... - ) -> None: ... + def __init__(self, __value: _ComplexValue = ...) -> None: ... -class complex128(complexfloating[float64]): - def __init__( - self, - __value: Union[None, SupportsInt, SupportsFloat, SupportsComplex] = ... - ) -> None: ... +class complex128(complexfloating[float64], complex): + def __init__(self, __value: _ComplexValue = ...) -> None: ... -class flexible(_real_generic): ... # type: ignore +class flexible(generic): ... # type: ignore class void(flexible): - def __init__(self, __value: Union[int, integer, bool_, bytes, bytes_]): ... + def __init__(self, __value: Union[int, integer, bool_, bytes]): ... + @property + def real(self: _ArraySelf) -> _ArraySelf: ... + @property + def imag(self: _ArraySelf) -> _ArraySelf: ... -class character(_real_generic): ... # type: ignore +class character(flexible): ... # type: ignore -class bytes_(character): +class bytes_(character, bytes): @overload def __init__(self, __value: object = ...) -> None: ... @overload def __init__( - self, __value: Union[str, str_], encoding: str = ..., errors: str = ... + self, __value: str, encoding: str = ..., errors: str = ... ) -> None: ... -class str_(character): +class str_(character, str): @overload def __init__(self, __value: object = ...) -> None: ... @overload def __init__( - self, __value: Union[bytes, bytes_], encoding: str = ..., errors: str = ... + self, __value: bytes, encoding: str = ..., errors: str = ... ) -> None: ... # TODO(alan): Platform dependent types @@ -971,9 +1024,9 @@ _Number = TypeVar('_Number', bound=number) _NumberLike = Union[int, float, complex, number, bool_] # An array-like object consisting of integers -_Int = Union[int, integer] -_Bool = Union[bool, bool_] -_IntOrBool = Union[_Int, _Bool] +_IntLike = Union[int, integer] +_BoolLike = Union[bool, bool_] +_IntOrBool = Union[_IntLike, _BoolLike] _ArrayLikeIntNested = ArrayLike # TODO: wait for support for recursive types _ArrayLikeBoolNested = ArrayLike # TODO: wait for support for recursive types @@ -986,8 +1039,8 @@ _ArrayLikeIntOrBool = Union[ Sequence[_ArrayLikeBoolNested], ] _ArrayLikeBool = Union[ - _Bool, - Sequence[_Bool], + _BoolLike, + Sequence[_BoolLike], ndarray ] diff --git a/numpy/char.pyi b/numpy/char.pyi new file mode 100644 index 000000000..0e7342c0b --- /dev/null +++ b/numpy/char.pyi @@ -0,0 +1,53 @@ +from typing import Any + +equal: Any +not_equal: Any +greater_equal: Any +less_equal: Any +greater: Any +less: Any +str_len: Any +add: Any +multiply: Any +mod: Any +capitalize: Any +center: Any +count: Any +decode: Any +encode: Any +endswith: Any +expandtabs: Any +find: Any +index: Any +isalnum: Any +isalpha: Any +isdigit: Any +islower: Any +isspace: Any +istitle: Any +isupper: Any +join: Any +ljust: Any +lower: Any +lstrip: Any +partition: Any +replace: Any +rfind: Any +rindex: Any +rjust: Any +rpartition: Any +rsplit: Any +rstrip: Any +split: Any +splitlines: Any +startswith: Any +strip: Any +swapcase: Any +title: Any +translate: Any +upper: Any +zfill: Any +isnumeric: Any +isdecimal: Any +array: Any +asarray: Any diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index b2f17cfeb..8a1fee99b 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -165,7 +165,7 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, if axis != 0: y = _nx.moveaxis(y, 0, axis) - + if _nx.issubdtype(dtype, _nx.integer): _nx.floor(y, out=y) @@ -207,7 +207,7 @@ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, endpoint : boolean, optional If true, `stop` is the last sample. Otherwise, it is not included. Default is True. - base : float, optional + base : array_like, optional The base of the log space. The step size between the elements in ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform. Default is 10.0. diff --git a/numpy/core/function_base.pyi b/numpy/core/function_base.pyi new file mode 100644 index 000000000..c6ebbd5f5 --- /dev/null +++ b/numpy/core/function_base.pyi @@ -0,0 +1,56 @@ +import sys +from typing import overload, Tuple, Union, Sequence, Any + +from numpy import ndarray, inexact, _NumberLike +from numpy.typing import ArrayLike, DtypeLike, _SupportsArray + +if sys.version_info >= (3, 8): + from typing import SupportsIndex, Literal +else: + from typing_extensions import Literal, Protocol + + class SupportsIndex(Protocol): + def __index__(self) -> int: ... + +# TODO: wait for support for recursive types +_ArrayLikeNested = Sequence[Sequence[Any]] +_ArrayLikeNumber = Union[ + _NumberLike, Sequence[_NumberLike], ndarray, _SupportsArray, _ArrayLikeNested +] +@overload +def linspace( + start: _ArrayLikeNumber, + stop: _ArrayLikeNumber, + num: SupportsIndex = ..., + endpoint: bool = ..., + retstep: Literal[False] = ..., + dtype: DtypeLike = ..., + axis: SupportsIndex = ..., +) -> ndarray: ... +@overload +def linspace( + start: _ArrayLikeNumber, + stop: _ArrayLikeNumber, + num: SupportsIndex = ..., + endpoint: bool = ..., + retstep: Literal[True] = ..., + dtype: DtypeLike = ..., + axis: SupportsIndex = ..., +) -> Tuple[ndarray, inexact]: ... +def logspace( + start: _ArrayLikeNumber, + stop: _ArrayLikeNumber, + num: SupportsIndex = ..., + endpoint: bool = ..., + base: _ArrayLikeNumber = ..., + dtype: DtypeLike = ..., + axis: SupportsIndex = ..., +) -> ndarray: ... +def geomspace( + start: _ArrayLikeNumber, + stop: _ArrayLikeNumber, + num: SupportsIndex = ..., + endpoint: bool = ..., + dtype: DtypeLike = ..., + axis: SupportsIndex = ..., +) -> ndarray: ... diff --git a/numpy/ctypeslib.pyi b/numpy/ctypeslib.pyi new file mode 100644 index 000000000..cacc97d68 --- /dev/null +++ b/numpy/ctypeslib.pyi @@ -0,0 +1,7 @@ +from typing import Any + +load_library: Any +ndpointer: Any +c_intp: Any +as_ctypes: Any +as_array: Any diff --git a/numpy/distutils/__init__.pyi b/numpy/distutils/__init__.pyi new file mode 100644 index 000000000..3938d68de --- /dev/null +++ b/numpy/distutils/__init__.pyi @@ -0,0 +1,4 @@ +from typing import Any + +# TODO: remove when the full numpy namespace is defined +def __getattr__(name: str) -> Any: ... diff --git a/numpy/emath.pyi b/numpy/emath.pyi new file mode 100644 index 000000000..032ec9505 --- /dev/null +++ b/numpy/emath.pyi @@ -0,0 +1,11 @@ +from typing import Any + +sqrt: Any +log: Any +log2: Any +logn: Any +log10: Any +power: Any +arccos: Any +arcsin: Any +arctanh: Any diff --git a/numpy/f2py/__init__.pyi b/numpy/f2py/__init__.pyi new file mode 100644 index 000000000..602517957 --- /dev/null +++ b/numpy/f2py/__init__.pyi @@ -0,0 +1,5 @@ +from typing import Any + +run_main: Any +compile: Any +f2py_testing: Any diff --git a/numpy/fft/__init__.pyi b/numpy/fft/__init__.pyi new file mode 100644 index 000000000..45190517f --- /dev/null +++ b/numpy/fft/__init__.pyi @@ -0,0 +1,20 @@ +from typing import Any + +fft: Any +ifft: Any +rfft: Any +irfft: Any +hfft: Any +ihfft: Any +rfftn: Any +irfftn: Any +rfft2: Any +irfft2: Any +fft2: Any +ifft2: Any +fftn: Any +ifftn: Any +fftshift: Any +ifftshift: Any +fftfreq: Any +rfftfreq: Any diff --git a/numpy/lib/__init__.pyi b/numpy/lib/__init__.pyi new file mode 100644 index 000000000..413e2ae1b --- /dev/null +++ b/numpy/lib/__init__.pyi @@ -0,0 +1,177 @@ +from typing import Any + +emath: Any +math: Any +tracemalloc_domain: Any +Arrayterator: Any +iscomplexobj: Any +isrealobj: Any +imag: Any +iscomplex: Any +isreal: Any +nan_to_num: Any +real: Any +real_if_close: Any +typename: Any +asfarray: Any +mintypecode: Any +asscalar: Any +common_type: Any +ravel_multi_index: Any +unravel_index: Any +mgrid: Any +ogrid: Any +r_: Any +c_: Any +s_: Any +index_exp: Any +ix_: Any +ndenumerate: Any +ndindex: Any +fill_diagonal: Any +diag_indices: Any +diag_indices_from: Any +select: Any +piecewise: Any +trim_zeros: Any +copy: Any +iterable: Any +percentile: Any +diff: Any +gradient: Any +angle: Any +unwrap: Any +sort_complex: Any +disp: Any +flip: Any +rot90: Any +extract: Any +place: Any +vectorize: Any +asarray_chkfinite: Any +average: Any +bincount: Any +digitize: Any +cov: Any +corrcoef: Any +msort: Any +median: Any +sinc: Any +hamming: Any +hanning: Any +bartlett: Any +blackman: Any +kaiser: Any +trapz: Any +i0: Any +add_newdoc: Any +add_docstring: Any +meshgrid: Any +delete: Any +insert: Any +append: Any +interp: Any +add_newdoc_ufunc: Any +quantile: Any +column_stack: Any +row_stack: Any +dstack: Any +array_split: Any +split: Any +hsplit: Any +vsplit: Any +dsplit: Any +apply_over_axes: Any +expand_dims: Any +apply_along_axis: Any +kron: Any +tile: Any +get_array_wrap: Any +take_along_axis: Any +put_along_axis: Any +broadcast_to: Any +broadcast_arrays: Any +diag: Any +diagflat: Any +eye: Any +fliplr: Any +flipud: Any +tri: Any +triu: Any +tril: Any +vander: Any +histogram2d: Any +mask_indices: Any +tril_indices: Any +tril_indices_from: Any +triu_indices: Any +triu_indices_from: Any +fix: Any +isneginf: Any +isposinf: Any +pad: Any +poly: Any +roots: Any +polyint: Any +polyder: Any +polyadd: Any +polysub: Any +polymul: Any +polydiv: Any +polyval: Any +poly1d: Any +polyfit: Any +RankWarning: Any +issubclass_: Any +issubsctype: Any +issubdtype: Any +deprecate: Any +deprecate_with_doc: Any +get_include: Any +info: Any +source: Any +who: Any +lookfor: Any +byte_bounds: Any +safe_eval: Any +ediff1d: Any +intersect1d: Any +setxor1d: Any +union1d: Any +setdiff1d: Any +unique: Any +in1d: Any +isin: Any +savetxt: Any +loadtxt: Any +genfromtxt: Any +ndfromtxt: Any +mafromtxt: Any +recfromtxt: Any +recfromcsv: Any +load: Any +loads: Any +save: Any +savez: Any +savez_compressed: Any +packbits: Any +unpackbits: Any +fromregex: Any +DataSource: Any +nansum: Any +nanmax: Any +nanmin: Any +nanargmax: Any +nanargmin: Any +nanmean: Any +nanmedian: Any +nanpercentile: Any +nanvar: Any +nanstd: Any +nanprod: Any +nancumsum: Any +nancumprod: Any +nanquantile: Any +histogram: Any +histogramdd: Any +histogram_bin_edges: Any diff --git a/numpy/linalg/__init__.pyi b/numpy/linalg/__init__.pyi new file mode 100644 index 000000000..ffb05bb81 --- /dev/null +++ b/numpy/linalg/__init__.pyi @@ -0,0 +1,23 @@ +from typing import Any + +matrix_power: Any +solve: Any +tensorsolve: Any +tensorinv: Any +inv: Any +cholesky: Any +eigvals: Any +eigvalsh: Any +pinv: Any +slogdet: Any +det: Any +svd: Any +eig: Any +eigh: Any +lstsq: Any +norm: Any +qr: Any +cond: Any +matrix_rank: Any +LinAlgError: Any +multi_dot: Any diff --git a/numpy/ma/__init__.pyi b/numpy/ma/__init__.pyi new file mode 100644 index 000000000..d1259abcc --- /dev/null +++ b/numpy/ma/__init__.pyi @@ -0,0 +1,225 @@ +from typing import Any + +core: Any +extras: Any +MAError: Any +MaskError: Any +MaskType: Any +MaskedArray: Any +abs: Any +absolute: Any +add: Any +all: Any +allclose: Any +allequal: Any +alltrue: Any +amax: Any +amin: Any +angle: Any +anom: Any +anomalies: Any +any: Any +append: Any +arange: Any +arccos: Any +arccosh: Any +arcsin: Any +arcsinh: Any +arctan: Any +arctan2: Any +arctanh: Any +argmax: Any +argmin: Any +argsort: Any +around: Any +array: Any +asanyarray: Any +asarray: Any +bitwise_and: Any +bitwise_or: Any +bitwise_xor: Any +bool_: Any +ceil: Any +choose: Any +clip: Any +common_fill_value: Any +compress: Any +compressed: Any +concatenate: Any +conjugate: Any +convolve: Any +copy: Any +correlate: Any +cos: Any +cosh: Any +count: Any +cumprod: Any +cumsum: Any +default_fill_value: Any +diag: Any +diagonal: Any +diff: Any +divide: Any +empty: Any +empty_like: Any +equal: Any +exp: Any +expand_dims: Any +fabs: Any +filled: Any +fix_invalid: Any +flatten_mask: Any +flatten_structured_array: Any +floor: Any +floor_divide: Any +fmod: Any +frombuffer: Any +fromflex: Any +fromfunction: Any +getdata: Any +getmask: Any +getmaskarray: Any +greater: Any +greater_equal: Any +harden_mask: Any +hypot: Any +identity: Any +ids: Any +indices: Any +inner: Any +innerproduct: Any +isMA: Any +isMaskedArray: Any +is_mask: Any +is_masked: Any +isarray: Any +left_shift: Any +less: Any +less_equal: Any +log: Any +log10: Any +log2: Any +logical_and: Any +logical_not: Any +logical_or: Any +logical_xor: Any +make_mask: Any +make_mask_descr: Any +make_mask_none: Any +mask_or: Any +masked: Any +masked_array: Any +masked_equal: Any +masked_greater: Any +masked_greater_equal: Any +masked_inside: Any +masked_invalid: Any +masked_less: Any +masked_less_equal: Any +masked_not_equal: Any +masked_object: Any +masked_outside: Any +masked_print_option: Any +masked_singleton: Any +masked_values: Any +masked_where: Any +max: Any +maximum: Any +maximum_fill_value: Any +mean: Any +min: Any +minimum: Any +minimum_fill_value: Any +mod: Any +multiply: Any +mvoid: Any +ndim: Any +negative: Any +nomask: Any +nonzero: Any +not_equal: Any +ones: Any +outer: Any +outerproduct: Any +power: Any +prod: Any +product: Any +ptp: Any +put: Any +putmask: Any +ravel: Any +remainder: Any +repeat: Any +reshape: Any +resize: Any +right_shift: Any +round: Any +round_: Any +set_fill_value: Any +shape: Any +sin: Any +sinh: Any +size: Any +soften_mask: Any +sometrue: Any +sort: Any +sqrt: Any +squeeze: Any +std: Any +subtract: Any +sum: Any +swapaxes: Any +take: Any +tan: Any +tanh: Any +trace: Any +transpose: Any +true_divide: Any +var: Any +where: Any +zeros: Any +apply_along_axis: Any +apply_over_axes: Any +atleast_1d: Any +atleast_2d: Any +atleast_3d: Any +average: Any +clump_masked: Any +clump_unmasked: Any +column_stack: Any +compress_cols: Any +compress_nd: Any +compress_rowcols: Any +compress_rows: Any +count_masked: Any +corrcoef: Any +cov: Any +diagflat: Any +dot: Any +dstack: Any +ediff1d: Any +flatnotmasked_contiguous: Any +flatnotmasked_edges: Any +hsplit: Any +hstack: Any +isin: Any +in1d: Any +intersect1d: Any +mask_cols: Any +mask_rowcols: Any +mask_rows: Any +masked_all: Any +masked_all_like: Any +median: Any +mr_: Any +notmasked_contiguous: Any +notmasked_edges: Any +polyfit: Any +row_stack: Any +setdiff1d: Any +setxor1d: Any +stack: Any +unique: Any +union1d: Any +vander: Any +vstack: Any diff --git a/numpy/matrixlib/__init__.pyi b/numpy/matrixlib/__init__.pyi new file mode 100644 index 000000000..b240bb327 --- /dev/null +++ b/numpy/matrixlib/__init__.pyi @@ -0,0 +1,6 @@ +from typing import Any + +matrix: Any +bmat: Any +mat: Any +asmatrix: Any diff --git a/numpy/polynomial/__init__.pyi b/numpy/polynomial/__init__.pyi new file mode 100644 index 000000000..817ba22ac --- /dev/null +++ b/numpy/polynomial/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Any + +Polynomial: Any +Chebyshev: Any +Legendre: Any +Hermite: Any +HermiteE: Any +Laguerre: Any +set_default_printstyle: Any diff --git a/numpy/random/__init__.pyi b/numpy/random/__init__.pyi new file mode 100644 index 000000000..f7c3cfafe --- /dev/null +++ b/numpy/random/__init__.pyi @@ -0,0 +1,61 @@ +from typing import Any + +beta: Any +binomial: Any +bytes: Any +chisquare: Any +choice: Any +dirichlet: Any +exponential: Any +f: Any +gamma: Any +geometric: Any +get_state: Any +gumbel: Any +hypergeometric: Any +laplace: Any +logistic: Any +lognormal: Any +logseries: Any +multinomial: Any +multivariate_normal: Any +negative_binomial: Any +noncentral_chisquare: Any +noncentral_f: Any +normal: Any +pareto: Any +permutation: Any +poisson: Any +power: Any +rand: Any +randint: Any +randn: Any +random: Any +random_integers: Any +random_sample: Any +ranf: Any +rayleigh: Any +sample: Any +seed: Any +set_state: Any +shuffle: Any +standard_cauchy: Any +standard_exponential: Any +standard_gamma: Any +standard_normal: Any +standard_t: Any +triangular: Any +uniform: Any +vonmises: Any +wald: Any +weibull: Any +zipf: Any +Generator: Any +RandomState: Any +SeedSequence: Any +MT19937: Any +Philox: Any +PCG64: Any +SFC64: Any +default_rng: Any +BitGenerator: Any diff --git a/numpy/rec.pyi b/numpy/rec.pyi new file mode 100644 index 000000000..c70ee5374 --- /dev/null +++ b/numpy/rec.pyi @@ -0,0 +1,5 @@ +from typing import Any + +record: Any +recarray: Any +format_parser: Any diff --git a/numpy/testing/__init__.pyi b/numpy/testing/__init__.pyi new file mode 100644 index 000000000..c394a387d --- /dev/null +++ b/numpy/testing/__init__.pyi @@ -0,0 +1,44 @@ +from typing import Any + +assert_equal: Any +assert_almost_equal: Any +assert_approx_equal: Any +assert_array_equal: Any +assert_array_less: Any +assert_string_equal: Any +assert_array_almost_equal: Any +assert_raises: Any +build_err_msg: Any +decorate_methods: Any +jiffies: Any +memusage: Any +print_assert_equal: Any +raises: Any +rundocs: Any +runstring: Any +verbose: Any +measure: Any +assert_: Any +assert_array_almost_equal_nulp: Any +assert_raises_regex: Any +assert_array_max_ulp: Any +assert_warns: Any +assert_no_warnings: Any +assert_allclose: Any +IgnoreException: Any +clear_and_catch_warnings: Any +SkipTest: Any +KnownFailureException: Any +temppath: Any +tempdir: Any +IS_PYPY: Any +HAS_REFCOUNT: Any +suppress_warnings: Any +assert_array_compare: Any +_assert_valid_refcount: Any +_gen_alignment_data: Any +assert_no_gc_cycles: Any +break_cycles: Any +HAS_LAPACK64: Any +TestCase: Any +run_module_suite: Any diff --git a/numpy/tests/test_typing.py b/numpy/tests/test_typing.py index 04ea3c64d..32342d321 100644 --- a/numpy/tests/test_typing.py +++ b/numpy/tests/test_typing.py @@ -89,7 +89,7 @@ def test_fail(path): for i, line in enumerate(lines): lineno = i + 1 - if " E:" not in line and lineno not in errors: + if line.startswith('#') or (" E:" not in line and lineno not in errors): continue target_line = lines[lineno - 1] diff --git a/numpy/tests/typing/fail/linspace.py b/numpy/tests/typing/fail/linspace.py new file mode 100644 index 000000000..a9769c5d6 --- /dev/null +++ b/numpy/tests/typing/fail/linspace.py @@ -0,0 +1,13 @@ +import numpy as np + +np.linspace(None, 'bob') # E: No overload variant +np.linspace(0, 2, num=10.0) # E: No overload variant +np.linspace(0, 2, endpoint='True') # E: No overload variant +np.linspace(0, 2, retstep=b'False') # E: No overload variant +np.linspace(0, 2, dtype=0) # E: No overload variant +np.linspace(0, 2, axis=None) # E: No overload variant + +np.logspace(None, 'bob') # E: Argument 1 +np.logspace(0, 2, base=None) # E: Argument "base" + +np.geomspace(None, 'bob') # E: Argument 1 diff --git a/numpy/tests/typing/fail/modules.py b/numpy/tests/typing/fail/modules.py new file mode 100644 index 000000000..e7ffe8920 --- /dev/null +++ b/numpy/tests/typing/fail/modules.py @@ -0,0 +1,3 @@ +import numpy as np + +np.testing.bob # E: Module has no attribute diff --git a/numpy/tests/typing/fail/scalars.py b/numpy/tests/typing/fail/scalars.py index 5d7221895..47c031163 100644 --- a/numpy/tests/typing/fail/scalars.py +++ b/numpy/tests/typing/fail/scalars.py @@ -32,11 +32,16 @@ dt_64 = np.datetime64(0, "D") td_64 = np.timedelta64(1, "h") dt_64 + dt_64 # E: Unsupported operand types - td_64 - dt_64 # E: Unsupported operand types -td_64 / dt_64 # E: No overload td_64 % 1 # E: Unsupported operand types -td_64 % dt_64 # E: Unsupported operand types + +# NOTE: The 2 tests below currently don't work due to the broad +# (i.e. untyped) signature of `generic.__truediv__()` and `.__mod__()`. +# TODO: Revisit this once annotations are added to the +# `_ArrayOrScalarCommon` magic methods. + +# td_64 / dt_64 # E: No overload +# td_64 % dt_64 # E: Unsupported operand types class A: diff --git a/numpy/tests/typing/pass/linspace.py b/numpy/tests/typing/pass/linspace.py new file mode 100644 index 000000000..8c6d0d56b --- /dev/null +++ b/numpy/tests/typing/pass/linspace.py @@ -0,0 +1,22 @@ +import numpy as np + +class Index: + def __index__(self) -> int: + return 0 + +np.linspace(0, 2) +np.linspace(0.5, [0, 1, 2]) +np.linspace([0, 1, 2], 3) +np.linspace(0j, 2) +np.linspace(0, 2, num=10) +np.linspace(0, 2, endpoint=True) +np.linspace(0, 2, retstep=True) +np.linspace(0j, 2j, retstep=True) +np.linspace(0, 2, dtype=bool) +np.linspace([0, 1], [2, 3], axis=Index()) + +np.logspace(0, 2, base=2) +np.logspace(0, 2, base=2) +np.logspace(0, 2, base=[1j, 2j], num=2) + +np.geomspace(1, 2) diff --git a/numpy/tests/typing/pass/scalars.py b/numpy/tests/typing/pass/scalars.py index 1c7ace282..c02e1ed36 100644 --- a/numpy/tests/typing/pass/scalars.py +++ b/numpy/tests/typing/pass/scalars.py @@ -1,27 +1,38 @@ +import sys +import datetime as dt + import numpy as np # Construction +class D: + def __index__(self) -> int: + return 0 + + class C: - def __complex__(self): + def __complex__(self) -> complex: return 3j class B: - def __int__(self): + def __int__(self) -> int: return 4 class A: - def __float__(self): + def __float__(self) -> float: return 4.0 np.complex64(3j) +np.complex64(A()) np.complex64(C()) np.complex128(3j) np.complex128(C()) np.complex128(None) +np.complex64("1.2") +np.complex128(b"2j") np.int8(4) np.int16(3.4) @@ -29,11 +40,20 @@ np.int32(4) np.int64(-1) np.uint8(B()) np.uint32() +np.int32("1") +np.int64(b"2") np.float16(A()) np.float32(16) np.float64(3.0) np.float64(None) +np.float32("1") +np.float16(b"2.5") + +if sys.version_info >= (3, 8): + np.uint64(D()) + np.float32(D()) + np.complex64(D()) np.bytes_(b"hello") np.bytes_("hello", 'utf-8') @@ -66,14 +86,25 @@ np.uint64().shape # Time structures np.datetime64() np.datetime64(0, "D") +np.datetime64(0, b"D") +np.datetime64(0, ('ms', 3)) np.datetime64("2019") +np.datetime64(b"2019") np.datetime64("2019", "D") +np.datetime64(np.datetime64()) +np.datetime64(dt.datetime(2000, 5, 3)) np.datetime64(None) np.datetime64(None, "D") np.timedelta64() np.timedelta64(0) np.timedelta64(0, "D") +np.timedelta64(0, ('ms', 3)) +np.timedelta64(0, b"D") +np.timedelta64("3") +np.timedelta64(b"5") +np.timedelta64(np.timedelta64(2)) +np.timedelta64(dt.timedelta(2)) np.timedelta64(None) np.timedelta64(None, "D") diff --git a/numpy/tests/typing/reveal/linspace.py b/numpy/tests/typing/reveal/linspace.py new file mode 100644 index 000000000..cfbbdf390 --- /dev/null +++ b/numpy/tests/typing/reveal/linspace.py @@ -0,0 +1,6 @@ +import numpy as np + +reveal_type(np.linspace(0, 10)) # E: numpy.ndarray +reveal_type(np.linspace(0, 10, retstep=True)) # E: Tuple[numpy.ndarray, numpy.inexact] +reveal_type(np.logspace(0, 10)) # E: numpy.ndarray +reveal_type(np.geomspace(1, 10)) # E: numpy.ndarray diff --git a/numpy/tests/typing/reveal/modules.py b/numpy/tests/typing/reveal/modules.py new file mode 100644 index 000000000..406463152 --- /dev/null +++ b/numpy/tests/typing/reveal/modules.py @@ -0,0 +1,20 @@ +import numpy as np + +reveal_type(np) # E: ModuleType + +reveal_type(np.char) # E: ModuleType +reveal_type(np.ctypeslib) # E: ModuleType +reveal_type(np.emath) # E: ModuleType +reveal_type(np.fft) # E: ModuleType +reveal_type(np.lib) # E: ModuleType +reveal_type(np.linalg) # E: ModuleType +reveal_type(np.ma) # E: ModuleType +reveal_type(np.matrixlib) # E: ModuleType +reveal_type(np.polynomial) # E: ModuleType +reveal_type(np.random) # E: ModuleType +reveal_type(np.rec) # E: ModuleType +reveal_type(np.testing) # E: ModuleType +reveal_type(np.version) # E: ModuleType + +# TODO: Remove when annotations have been added to `np.testing.assert_equal` +reveal_type(np.testing.assert_equal) # E: Any diff --git a/numpy/version.pyi b/numpy/version.pyi new file mode 100644 index 000000000..6f3659e43 --- /dev/null +++ b/numpy/version.pyi @@ -0,0 +1,7 @@ +from typing import Any + +short_version: Any +version: Any +full_version: Any +git_revision: Any +release: Any |