text
stringlengths
0
20k
# Vendored implementation of pandas.NA, adapted from pandas/_libs/missing.pyx # # This is vendored to avoid adding pandas as a test dependency. __all__ = ["pd_NA"] import numbers import numpy as np def _create_binary_propagating_op(name, is_divmod=False): is_cmp = name.strip("_") in ["eq", "ne", "le", "lt", "g...
""" Test functions for limits module. """ import types import warnings import pytest import numpy as np from numpy import double, half, longdouble, single from numpy._core import finfo, iinfo from numpy._core.getlimits import _discovered_machar, _float_ma from numpy.testing import assert_, assert_equal, assert_raise...
""" Tests of the ._exceptions module. Primarily for exercising the __str__ methods. """ import pickle import pytest import numpy as np from numpy.exceptions import AxisError _ArrayMemoryError = np._core._exceptions._ArrayMemoryError _UFuncNoLoopError = np._core._exceptions._UFuncNoLoopError class TestArrayMemoryEr...
import sys import sysconfig import pytest import numpy as np from numpy.testing import IS_EDITABLE, IS_WASM, extbuild @pytest.fixture def get_module(tmp_path): """ Some codes to generate data and manage temporary buffers use when sharing with numpy via the array interface protocol. """ if sys.platfo...
import random import pytest from numpy._core._multiarray_tests import identityhash_tester @pytest.mark.parametrize("key_length", [1, 3, 6]) @pytest.mark.parametrize("length", [1, 16, 2000]) def test_identity_hashtable(key_length, length): # use a 30 object pool for everything (duplicates will happen) pool = ...
import numpy as np from numpy.testing import assert_, assert_array_equal, assert_equal def buffer_length(arr): if isinstance(arr, str): if not arr: charmax = 0 else: charmax = max(ord(c) for c in arr) if charmax < 256: size = 1 elif charmax < 65...
import sysconfig import pytest import numpy as np from numpy.testing import IS_WASM, assert_raises # The floating point emulation on ARM EABI systems lacking a hardware FPU is # known to be buggy. This is an attempt to identify these hosts. It may not # catch all possible cases, but it catches the known cases of gh-...
""" This file tests the generic aspects of ArrayMethod. At the time of writing this is private API, but when added, public API may be added here. """ import types from typing import Any import pytest from numpy._core._multiarray_umath import _get_castingimpl as get_castingimpl import numpy as np class TestResolve...
""" Provide python-space access to the functions exposed in numpy/__init__.pxd for testing. """ import os from distutils.core import setup import Cython from Cython.Build import cythonize from setuptools.extension import Extension import numpy as np from numpy._utils import _pep440 macros = [ ("NPY_NO_DEPRECATE...
#cython: language_level=3 """ Functions in this module give python-space wrappers for cython functions exposed in numpy/__init__.pxd, so they can be tested in test_cython.py """ cimport numpy as cnp cnp.import_array() def is_td64(obj): return cnp.is_timedelta64_object(obj) def is_dt64(obj): return cnp.is_d...
#define Py_LIMITED_API 0x03060000 #include <Python.h> #include <numpy/arrayobject.h> #include <numpy/ufuncobject.h> static PyModuleDef moduledef = { .m_base = PyModuleDef_HEAD_INIT, .m_name = "limited_api1" }; PyMODINIT_FUNC PyInit_limited_api1(void) { import_array(); import_umath(); return PyMod...
""" Build an example package using the limited Python C API. """ import os from setuptools import Extension, setup import numpy as np macros = [("NPY_NO_DEPRECATED_API", 0), ("Py_LIMITED_API", "0x03060000")] limited_api = Extension( "limited_api", sources=[os.path.join('.', "limited_api.c")], include_d...
#if Py_LIMITED_API != PY_VERSION_HEX & 0xffff0000 # error "Py_LIMITED_API not defined to Python major+minor version" #endif #include <Python.h> #include <numpy/arrayobject.h> #include <numpy/ufuncobject.h> static PyModuleDef moduledef = { .m_base = PyModuleDef_HEAD_INIT, .m_name = "limited_api_latest" }; ...
#cython: language_level=3 """ Make sure cython can compile in limited API mode (see meson.build) """ cdef extern from "numpy/arrayobject.h": pass cdef extern from "numpy/arrayscalars.h": pass
import sys import pytest import numpy as np from numpy.testing import HAS_REFCOUNT, assert_, assert_array_equal, assert_raises class TestTake: def test_simple(self): a = [[1, 2], [3, 4]] a_str = [[b'1', b'2'], [b'3', b'4']] modes = ['raise', 'wrap', 'clip'] indices = [-1, 4] ...
from numpy._core.strings import * from numpy._core.strings import __all__, __doc__
""" Module defining global singleton classes. This module raises a RuntimeError if an attempt to reload it is made. In that way the identities of the classes defined here are fixed and will remain so even if numpy itself is reloaded. In particular, a function like the following will still work correctly after numpy is...
#!/usr/bin/env python3 """Prints type-coercion tables for the built-in NumPy types """ from collections import namedtuple import numpy as np from numpy._core.numerictypes import obj2sctype # Generic object that can be added, but doesn't do anything else class GenericObject: def __init__(self, v): self.v...
"""Common test support for all numpy test scripts. This single module should provide all the common functionality for numpy tests in a single location, so that test scripts can just import it and work right away. """ from unittest import TestCase from . import _private, overrides from ._private import extbuild from ...
""" Build a c-extension module on-the-fly in tests. See build_and_import_extensions for usage hints """ import os import pathlib import subprocess import sys import sysconfig import textwrap __all__ = ['build_and_import_extension', 'compile_extension_module'] def build_and_import_extension( modname, functi...
"""Tools for testing implementations of __array_function__ and ufunc overrides """ import numpy._core.umath as _umath from numpy import ufunc as _ufunc from numpy._core.overrides import ARRAY_FUNCTIONS as _array_functions def get_overridable_numpy_ufuncs(): """List all numpy ufuncs overridable via `__array_ufu...
import sys from collections.abc import Callable, Collection, Sequence from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, TypeVar, runtime_checkable import numpy as np from numpy import dtype from ._nbit_base import _32Bit, _64Bit from ._nested_sequence import _NestedSequence from ._shape import _AnyShape if...
from typing import Any, TypeAlias import numpy as np # NOTE: `_StrLike_co` and `_BytesLike_co` are pointless, as `np.str_` and # `np.bytes_` are already subclasses of their builtin counterpart _CharLike_co: TypeAlias = str | bytes # The `<X>Like_co` type-aliases below represent all scalars that can be # coerced into...
"""A module with the precisions of generic `~numpy.number` types.""" from typing import final from numpy._utils import set_module @final # Disallow the creation of arbitrary `NBitBase` subclasses @set_module("numpy.typing") class NBitBase: """ A type representing `numpy.number` precision during static type ...
"""A module with platform-specific extended precision `numpy.number` subclasses. The subclasses are defined here (instead of ``__init__.pyi``) such that they can be imported conditionally via the numpy's mypy plugin. """ import numpy as np from . import _96Bit, _128Bit float96 = np.floating[_96Bit] float128 = np.fl...
from typing import Literal _BoolCodes = Literal[ "bool", "bool_", "?", "|?", "=?", "<?", ">?", "b1", "|b1", "=b1", "<b1", ">b1", ] # fmt: skip _UInt8Codes = Literal["uint8", "u1", "|u1", "=u1", "<u1", ">u1"] _UInt16Codes = Literal["uint16", "u2", "|u2", "=u2", "<u2", ">u2"] _UInt32Codes = Literal["uint32...
from collections.abc import Sequence from typing import Any, SupportsIndex, TypeAlias _Shape: TypeAlias = tuple[int, ...] _AnyShape: TypeAlias = tuple[Any, ...] # Anything that can be coerced to a shape tuple _ShapeLike: TypeAlias = SupportsIndex | Sequence[SupportsIndex]
"""A module with the precisions of platform-specific `~numpy.number`s.""" from typing import TypeAlias from ._nbit_base import _8Bit, _16Bit, _32Bit, _64Bit, _96Bit, _128Bit # To-be replaced with a `npt.NBitBase` subclass by numpy's mypy plugin _NBitByte: TypeAlias = _8Bit _NBitShort: TypeAlias = _16Bit _NBitIntC: T...
"""A module for creating docstrings for sphinx ``data`` domains.""" import re import textwrap from ._array_like import NDArray _docstrings_list = [] def add_newdoc(name: str, value: str, doc: str) -> None: """Append ``_docstrings_list`` with a docstring for `name`. Parameters ---------- name : str...
"""Private counterpart of ``numpy.typing``.""" from ._array_like import ArrayLike as ArrayLike from ._array_like import NDArray as NDArray from ._array_like import _ArrayLike as _ArrayLike from ._array_like import _ArrayLikeAnyString_co as _ArrayLikeAnyString_co from ._array_like import _ArrayLikeBool_co as _ArrayLike...
from numpy import ufunc _UFunc_Nin1_Nout1 = ufunc _UFunc_Nin2_Nout1 = ufunc _UFunc_Nin1_Nout2 = ufunc _UFunc_Nin2_Nout2 = ufunc _GUFunc_Nin2_Nout1 = ufunc
"""A module containing the `_NestedSequence` protocol.""" from typing import TYPE_CHECKING, Any, Protocol, TypeVar, runtime_checkable if TYPE_CHECKING: from collections.abc import Iterator __all__ = ["_NestedSequence"] _T_co = TypeVar("_T_co", covariant=True) @runtime_checkable class _NestedSequence(Protocol[...
from collections.abc import Sequence # noqa: F811 from typing import ( Any, Protocol, TypeAlias, TypedDict, TypeVar, runtime_checkable, ) import numpy as np from ._char_codes import ( _BoolCodes, _BytesCodes, _ComplexFloatingCodes, _DT64Codes, _FloatingCodes, _NumberCo...
import argparse import sys from pathlib import Path from .lib._utils_impl import get_include from .version import __version__ def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--version", action="version", version=__version__, help="Print the version...
""" Module to expose more detailed version info for the installed `numpy` """ version = "2.3.5" __version__ = version full_version = version git_revision = "c3d60fc8393f3ca3306b8ce8b6453d43737e3d90" release = 'dev' not in version and '+' not in version short_version = version.split("+")[0]
""" This module is home to specific dtypes related functionality and their classes. For more general information about dtypes, also see `numpy.dtype` and :ref:`arrays.dtypes`. Similar to the builtin ``types`` module, this submodule defines types (classes) that are not widely used directly. .. versionadded:: NumPy 1.2...
import warnings # 2018-05-29, PendingDeprecationWarning added to matrix.__new__ # 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. " "The matrix subclass is not the recommended way to represent " "matrices or deal with ...
from numpy._core.defchararray import * from numpy._core.defchararray import __all__, __doc__
""" Dict of expired attributes that are discontinued since 2.0 release. Each item is associated with a migration note. """ __expired_attributes__ = { "geterrobj": "Use the np.errstate context manager instead.", "seterrobj": "Use the np.errstate context manager instead.", "cast": "Use `np.asarray(arr, dtype...
""" ============================ ``ctypes`` Utility Functions ============================ See Also -------- load_library : Load a C library. ndpointer : Array restype/argtype with verification. as_ctypes : Create a ctypes array from an ndarray. as_array : Create an ndarray from a ctypes array. References ---------- ...
from ._ctypeslib import ( __all__, __doc__, _concrete_ndptr, _ndptr, as_array, as_ctypes, as_ctypes_type, c_intp, ctypes, load_library, ndpointer, )
""" Discrete Fourier Transforms - _helper.py """ from numpy._core import arange, asarray, empty, integer, roll from numpy._core.overrides import array_function_dispatch, set_module # Created by Pearu Peterson, September 2002 __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq'] integer_types = (int, integer) ...
def __getattr__(attr_name): import warnings from numpy.fft import _helper ret = getattr(_helper, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.fft.helper' has no attribute {attr_name}") warnings.warn( "The numpy.fft.helper has been made private a...
""" Discrete Fourier Transform ========================== .. currentmodule:: numpy.fft The SciPy module `scipy.fft` is a more comprehensive superset of `numpy.fft`, which includes only a basic set of routines. Standard FFTs ------------- .. autosummary:: :toctree: generated/ fft Discrete Fourier transf...
"""Test functions for fftpack.helper module Copied from fftpack.helper by Pearu Peterson, October 2005 """ import numpy as np from numpy import fft, pi from numpy.testing import assert_array_almost_equal class TestFFTShift: def test_definition(self): x = [0, 1, 2, 3, 4, -4, -3, -2, -1] y = [-4,...
from numpy._core.records import * from numpy._core.records import __all__, __doc__
def __getattr__(attr_name): from numpy._core import numerictypes from ._utils import _raise_warning ret = getattr(numerictypes, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.numerictypes' has no attribute {attr_name}") _raise_warning(attr_name, "num...
def __getattr__(attr_name): from numpy._core import shape_base from ._utils import _raise_warning ret = getattr(shape_base, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.shape_base' has no attribute {attr_name}") _raise_warning(attr_name, "shape_bas...
from numpy._core import _internal # Build a new array from the information in a pickle. # Note that the name numpy.core._internal._reconstruct is embedded in # pickles of ndarrays made with NumPy before release 1.0 # so don't remove the name here, or you'll # break backward compatibility. def _reconstruct(subtype, sh...
def __getattr__(attr_name): from numpy._core import defchararray from ._utils import _raise_warning ret = getattr(defchararray, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.defchararray' has no attribute {attr_name}") _raise_warning(attr_name, "def...
from numpy._core import multiarray # these must import without warning or error from numpy.core.multiarray to # support old pickle files for item in ["_reconstruct", "scalar"]: globals()[item] = getattr(multiarray, item) # Pybind11 (in versions <= 2.11.1) imports _ARRAY_API from the multiarray # submodule as a pa...
def __getattr__(attr_name): from numpy._core import getlimits from ._utils import _raise_warning ret = getattr(getlimits, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.getlimits' has no attribute {attr_name}") _raise_warning(attr_name, "getlimits") ...
def __getattr__(attr_name): from numpy._core import arrayprint from ._utils import _raise_warning ret = getattr(arrayprint, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.arrayprint' has no attribute {attr_name}") _raise_warning(attr_name, "arrayprin...
def __getattr__(attr_name): from numpy._core import _dtype_ctypes from ._utils import _raise_warning ret = getattr(_dtype_ctypes, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core._dtype_ctypes' has no attribute {attr_name}") _raise_warning(attr_name, "...
from numpy import ufunc from numpy._core import _multiarray_umath for item in _multiarray_umath.__dir__(): # ufuncs appear in pickles with a path in numpy.core._multiarray_umath # and so must import from this namespace without warning or error attr = getattr(_multiarray_umath, item) if isinstance(attr,...
def __getattr__(attr_name): from numpy._core import function_base from ._utils import _raise_warning ret = getattr(function_base, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.function_base' has no attribute {attr_name}") _raise_warning(attr_name, "...
def __getattr__(attr_name): from numpy._core import records from ._utils import _raise_warning ret = getattr(records, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.records' has no attribute {attr_name}") _raise_warning(attr_name, "records") retu...
def __getattr__(attr_name): from numpy._core import einsumfunc from ._utils import _raise_warning ret = getattr(einsumfunc, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.einsumfunc' has no attribute {attr_name}") _raise_warning(attr_name, "einsumfun...
""" The `numpy.core` submodule exists solely for backward compatibility purposes. The original `core` was renamed to `_core` and made private. `numpy.core` will be removed in the future. """ from numpy import _core from ._utils import _raise_warning # We used to use `np.core._ufunc_reconstruct` to unpickle. # This i...
def __getattr__(attr_name): from numpy._core import _dtype from ._utils import _raise_warning ret = getattr(_dtype, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core._dtype' has no attribute {attr_name}") _raise_warning(attr_name, "_dtype") return r...
def __getattr__(attr_name): from numpy._core import umath from ._utils import _raise_warning ret = getattr(umath, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.umath' has no attribute {attr_name}") _raise_warning(attr_name, "umath") return ret
def __getattr__(attr_name): from numpy._core import overrides from ._utils import _raise_warning ret = getattr(overrides, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.overrides' has no attribute {attr_name}") _raise_warning(attr_name, "overrides") ...
import warnings def _raise_warning(attr: str, submodule: str | None = None) -> None: new_module = "numpy._core" old_module = "numpy.core" if submodule is not None: new_module = f"{new_module}.{submodule}" old_module = f"{old_module}.{submodule}" warnings.warn( f"{old_module} is...
def __getattr__(attr_name): from numpy._core import fromnumeric from ._utils import _raise_warning ret = getattr(fromnumeric, attr_name, None) if ret is None: raise AttributeError( f"module 'numpy.core.fromnumeric' has no attribute {attr_name}") _raise_warning(attr_name, "fromnu...
def __getattr__(attr_name): from numpy._core import numeric from ._utils import _raise_warning sentinel = object() ret = getattr(numeric, attr_name, sentinel) if ret is sentinel: raise AttributeError( f"module 'numpy.core.numeric' has no attribute {attr_name}") _raise_warni...
""" ============================ Typing (:mod:`numpy.typing`) ============================ .. versionadded:: 1.20 Large parts of the NumPy API have :pep:`484`-style type annotations. In addition a number of type aliases are available to users, most prominently the two below: - `ArrayLike`: objects that can be conver...
"""A mypy_ plugin for managing a number of platform-specific annotations. Its functionality can be split into three distinct parts: * Assigning the (platform-dependent) precisions of certain `~numpy.number` subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and `~numpy.longlong`. See the documentation...
from __future__ import annotations from typing import Any import numpy as np AR_i8: np.ndarray[Any, np.dtype[np.int_]] = np.arange(10) ar_iter = np.lib.Arrayterator(AR_i8) ar_iter.var ar_iter.buf_size ar_iter.start ar_iter.stop ar_iter.step ar_iter.shape ar_iter.flat ar_iter.__array__() for i in ar_iter: pass...
import numpy as np nd1 = np.array([[1, 2], [3, 4]]) # reshape nd1.reshape(4) nd1.reshape(2, 2) nd1.reshape((2, 2)) nd1.reshape((2, 2), order="C") nd1.reshape(4, order="C") # resize nd1.resize() nd1.resize(4) nd1.resize(2, 2) nd1.resize((2, 2)) nd1.resize((2, 2), refcheck=True) nd1.resize(4, refcheck=True) nd2 = n...
import numpy as np np.isdtype(np.float64, (np.int64, np.float64)) np.isdtype(np.int64, "signed integer") np.issubdtype("S1", np.bytes_) np.issubdtype(np.float64, np.float32) np.ScalarType np.ScalarType[0] np.ScalarType[3] np.ScalarType[8] np.ScalarType[10] np.typecodes["Character"] np.typecodes["Complex"] np.typeco...
""" Tests for miscellaneous (non-magic) ``np.ndarray``/``np.generic`` methods. More extensive tests are performed for the methods' function-based counterpart in `../from_numeric.py`. """ from __future__ import annotations import operator from typing import cast, Any import numpy as np import numpy.typing as npt c...
from __future__ import annotations from typing import Any import numpy as np class Object: def __ceil__(self) -> Object: return self def __floor__(self) -> Object: return self def __ge__(self, value: object) -> bool: return True def __array__(self, dtype: np.typing.DTypeLike...
"""These tests are based on the doctests from `numpy/lib/recfunctions.py`.""" from typing import Any, assert_type import numpy as np import numpy.typing as npt from numpy.lib import recfunctions as rfn def test_recursive_fill_fields() -> None: a: npt.NDArray[np.void] = np.array( [(1, 10.0), (2, 20.0)], ...
from __future__ import annotations from typing import Any, cast import numpy as np import numpy.typing as npt import pytest c16 = np.complex128(1) f8 = np.float64(1) i8 = np.int64(1) u8 = np.uint64(1) c8 = np.complex64(1) f4 = np.float32(1) i4 = np.int32(1) u4 = np.uint32(1) dt = np.datetime64(1, "D") td = np.timed...
import numpy as np f8 = np.float64(1) i8 = np.int64(1) u8 = np.uint64(1) f4 = np.float32(1) i4 = np.int32(1) u4 = np.uint32(1) td = np.timedelta64(1, "D") b_ = np.bool(1) b = bool(1) f = float(1) i = int(1) AR = np.array([1], dtype=np.bool) AR.setflags(write=False) AR2 = np.array([1], dtype=np.timedelta64) AR2.se...
import datetime as dt import pytest import numpy as np b = np.bool() b_ = np.bool_() u8 = np.uint64() i8 = np.int64() f8 = np.float64() c16 = np.complex128() U = np.str_() S = np.bytes_() # Construction class D: def __index__(self) -> int: return 0 class C: def __complex__(self) -> complex: ...
from numpy.lib import NumpyVersion version = NumpyVersion("1.8.0") version.vstring version.version version.major version.minor version.bugfix version.pre_release version.is_devversion version == version version != version version < "1.8.0" version <= version version > version version >= "1.8.0"
import numpy as np arr = np.array([1]) np.nditer([arr, None])
import numpy as np import numpy.typing as npt AR_f8: npt.NDArray[np.float64] = np.array([1.0]) AR_i4 = np.array([1], dtype=np.int32) AR_u1 = np.array([1], dtype=np.uint8) AR_LIKE_f = [1.5] AR_LIKE_i = [1] b_f8 = np.broadcast(AR_f8) b_i4_f8_f8 = np.broadcast(AR_i4, AR_f8, AR_f8) next(b_f8) b_f8.reset() b_f8.index b_...
from typing import Any, NamedTuple, cast import numpy as np # Subtype of tuple[int, int] class XYGrid(NamedTuple): x_axis: int y_axis: int # Test variance of _ShapeT_co def accepts_2d(a: np.ndarray[tuple[int, int], Any]) -> None: return None accepts_2d(np.empty(XYGrid(2, 2))) accepts_2d(np.zeros(XYGri...
import numpy as np np.sin(1) np.sin([1, 2, 3]) np.sin(1, out=np.empty(1)) np.matmul(np.ones((2, 2, 2)), np.ones((2, 2, 2)), axes=[(0, 1), (0, 1), (0, 1)]) np.sin(1, signature="D->D") # NOTE: `np.generic` subclasses are not guaranteed to support addition; # re-enable this we can infer the exact return type of `np.sin(....
import numpy as np AR = np.arange(10) AR.setflags(write=False) with np.printoptions(): np.set_printoptions( precision=1, threshold=2, edgeitems=3, linewidth=4, suppress=False, nanstr="Bob", infstr="Bill", formatter={}, sign="+", float...
import numpy as np dtype_obj = np.dtype(np.str_) void_dtype_obj = np.dtype([("f0", np.float64), ("f1", np.float32)]) np.dtype(dtype=np.int64) np.dtype(int) np.dtype("int") np.dtype(None) np.dtype((int, 2)) np.dtype((int, (1,))) np.dtype({"names": ["a", "b"], "formats": [int, float]}) np.dtype({"names": ["a"], "form...
import numpy as np i8 = np.int64(1) u8 = np.uint64(1) i4 = np.int32(1) u4 = np.uint32(1) b_ = np.bool(1) b = bool(1) i = int(1) AR = np.array([0, 1, 2], dtype=np.int32) AR.setflags(write=False) i8 << i8 i8 >> i8 i8 | i8 i8 ^ i8 i8 & i8 i << AR i >> AR i | AR i ^ AR i & AR i8 << AR i8 >> AR i8 | AR i8 ^ AR i8 &...
import numpy.exceptions as ex ex.AxisError("test") ex.AxisError(1, ndim=2) ex.AxisError(1, ndim=2, msg_prefix="error") ex.AxisError(1, ndim=2, msg_prefix=None)
from typing import Any import numpy as np import numpy.typing as npt class Index: def __index__(self) -> int: return 0 class SubClass(npt.NDArray[np.float64]): pass def func(i: int, j: int, **kwargs: Any) -> SubClass: return B i8 = np.int64(1) A = np.array([1]) B = A.view(SubClass).copy() B...
import numpy as np from numpy import f2py np.char np.ctypeslib np.emath np.fft np.lib np.linalg np.ma np.matrixlib np.polynomial np.random np.rec np.strings np.testing np.version np.lib.format np.lib.mixins np.lib.scimath np.lib.stride_tricks np.lib.array_utils np.ma.extras np.polynomial.chebyshev np.polynomial.hermi...
from __future__ import annotations from typing import Any import numpy as np AR_LIKE_b = [True, True, True] AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)] AR_LIKE_i = [1, 2, 3] AR_LIKE_f = [1.0, 2.0, 3.0] AR_LIKE_c = [1j, 2j, 3j] AR_LIKE_U = ["1", "2", "3"] OUT_f: np.ndarray[Any, np.dtype[np.float64]] = np....
from __future__ import annotations from typing import Any, TYPE_CHECKING from functools import partial import pytest import numpy as np if TYPE_CHECKING: from collections.abc import Callable AR = np.array(0) AR.setflags(write=False) KACF = frozenset({None, "K", "A", "C", "F"}) ACF = frozenset({None, "A", "C", ...
"""Typing tests for `numpy._core._ufunc_config`.""" import numpy as np def func1(a: str, b: int) -> None: return None def func2(a: str, b: int, c: float = 1.0) -> None: return None def func3(a: str, b: int) -> int: return 0 class Write1: def write(self, a: str) -> None: return None cl...
from typing import Any, TypeAlias, TypeVar, cast import numpy as np import numpy.typing as npt from numpy._typing import _Shape _ScalarT = TypeVar("_ScalarT", bound=np.generic) MaskedArray: TypeAlias = np.ma.MaskedArray[_Shape, np.dtype[_ScalarT]] MAR_b: MaskedArray[np.bool] = np.ma.MaskedArray([True]) MAR_u: Masked...
import os import tempfile import numpy as np nd = np.array([[1, 2], [3, 4]]) scalar_array = np.array(1) # item scalar_array.item() nd.item(1) nd.item(0, 1) nd.item((0, 1)) # tobytes nd.tobytes() nd.tobytes("C") nd.tobytes(None) # tofile if os.name != "nt": with tempfile.NamedTemporaryFile(suffix=".txt") as tmp...
"""Simple expression that should pass with mypy.""" import operator import numpy as np import numpy.typing as npt from collections.abc import Iterable # Basic checks array = np.array([1, 2]) def ndarray_func(x: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]: return x ndarray_func(np.array([1, 2], dtype=n...
from __future__ import annotations from io import StringIO import numpy as np import numpy.lib.array_utils as array_utils FILE = StringIO() AR = np.arange(10, dtype=np.float64) def func(a: int) -> bool: return True array_utils.byte_bounds(AR) array_utils.byte_bounds(np.float64()) np.info(1, output=FILE)
from __future__ import annotations from typing import Any import numpy as np AR_LIKE_b = [[True, True], [True, True]] AR_LIKE_i = [[1, 2], [3, 4]] AR_LIKE_f = [[1.0, 2.0], [3.0, 4.0]] AR_LIKE_U = [["1", "2"], ["3", "4"]] AR_i8: np.ndarray[Any, np.dtype[np.int64]] = np.array(AR_LIKE_i, dtype=np.int64) np.ndenumerate(...
from __future__ import annotations from typing import cast, Any import numpy as np c16 = np.complex128() f8 = np.float64() i8 = np.int64() u8 = np.uint64() c8 = np.complex64() f4 = np.float32() i4 = np.int32() u4 = np.uint32() dt = np.datetime64(0, "D") td = np.timedelta64(0, "D") b_ = np.bool() b = bool() c = co...
import numpy as np array = np.array([1, 2]) # The @ operator is not in python 2 array @ array