repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
numpy
numpy/core/__init__.py
.py
""" 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...
34
1,290
numpy
numpy/core/overrides.py
.py
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") ...
11
335
numpy
numpy/core/_internal.py
.py
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...
28
949
numpy
numpy/core/_multiarray_umath.py
.py
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,...
58
2,098
numpy
numpy/core/umath.py
.py
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
11
319
numpy
numpy/core/shape_base.py
.py
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...
11
339
numpy
numpy/core/arrayprint.py
.py
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...
11
339
numpy
numpy/core/numerictypes.py
.py
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...
11
347
numpy
numpy/core/_dtype.py
.py
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...
11
323
numpy
numpy/core/fromnumeric.py
.py
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...
11
343
numpy
numpy/core/_dtype_ctypes.py
.py
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, "...
11
351
numpy
numpy/core/multiarray.py
.py
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...
26
793
numpy
numpy/tests/test__all__.py
.py
import collections import numpy as np def test_no_duplicates_in_np__all__(): # Regression test for gh-10198. dups = {k: v for k, v in collections.Counter(np.__all__).items() if v > 1} assert len(dups) == 0
11
222
numpy
numpy/tests/test_matlib.py
.py
import numpy as np import numpy.matlib from numpy.testing import assert_, assert_array_equal def test_empty(): x = numpy.matlib.empty((2,)) assert_(isinstance(x, np.matrix)) assert_(x.shape, (1, 2)) def test_ones(): assert_array_equal(numpy.matlib.ones((2, 3)), np.matrix([[ 1.,...
60
1,854
numpy
numpy/tests/test_configtool.py
.py
import importlib.metadata import os import pathlib import subprocess import pytest import numpy as np import numpy._core.include import numpy._core.lib.pkgconfig from numpy.testing import HAS_SUBPROCESSES, IS_EDITABLE, IS_INSTALLED, NUMPY_ROOT INCLUDE_DIR = NUMPY_ROOT / '_core' / 'include' PKG_CONFIG_DIR = NUMPY_ROO...
52
1,828
numpy
numpy/tests/test_reloading.py
.py
import pickle import sys import textwrap from importlib import reload import pytest import numpy.exceptions as ex from numpy.testing import HAS_SUBPROCESSES, assert_, assert_equal, assert_raises from numpy.testing._private.utils import run_subprocess @pytest.mark.thread_unsafe(reason="reloads global module") def te...
70
2,587
numpy
numpy/tests/test_numpy_config.py
.py
""" Check the numpy config is valid. """ from unittest.mock import patch import pytest import numpy as np pytestmark = pytest.mark.skipif( not hasattr(np.__config__, "_built_with_meson"), reason="Requires Meson builds", ) class TestNumPyConfigs: REQUIRED_CONFIG_KEYS = [ "Compilers", "Ma...
48
1,317
numpy
numpy/tests/test_scripts.py
.py
""" Test scripts Test that we can run executable scripts that have been installed with numpy. """ import os import subprocess import sys from os.path import dirname import pytest import numpy as np from numpy.testing import HAS_SUBPROCESSES, assert_equal def find_f2py_commands(): if sys.platform == 'win32': ...
46
1,507
numpy
numpy/tests/test_lazyloading.py
.py
import sys import textwrap import pytest from numpy.testing import HAS_SUBPROCESSES from numpy.testing._private.utils import run_subprocess @pytest.mark.skipif(not HAS_SUBPROCESSES, reason="platform cannot start subprocesses") def test_lazy_load(): # gh-22045. lazyload doesn't import submodule names into the na...
36
1,163
numpy
numpy/tests/test_ctypeslib.py
.py
import sys import sysconfig import weakref from pathlib import Path import pytest import numpy as np from numpy.ctypeslib import as_array, load_library, ndpointer from numpy.testing import assert_, assert_array_equal, assert_equal, assert_raises try: import ctypes except ImportError: ctypes = None else: ...
407
13,544
numpy
numpy/tests/test_numpy_version.py
.py
""" Check the numpy version is valid. Note that a development version is marked by the presence of 'dev0' or '+' in the version string, all else is treated as a release. The version string itself is set from the output of ``git describe`` which relies on tags. Examples -------- Valid Development: 1.22.0.dev0 1.22.0....
55
1,744
numpy
numpy/tests/test_warnings.py
.py
""" Tests which scan for certain occurrences in the code, they may not find all of these occurrences but should catch almost all. """ import ast import tokenize from pathlib import Path import pytest import numpy class ParseCall(ast.NodeVisitor): def __init__(self): self.ls = [] def visit_Attribute...
82
2,546
numpy
numpy/tests/test_public_api.py
.py
import functools import importlib import inspect import pkgutil import sys import sysconfig import types import warnings import pytest import numpy import numpy as np from numpy.testing import HAS_SUBPROCESSES from numpy.testing._private.utils import run_subprocess try: import ctypes except ImportError: ctyp...
723
25,046
numpy
numpy/doc/ufuncs.py
.py
""" =================== Universal Functions =================== Ufuncs are, generally speaking, mathematical functions or operations that are applied element-by-element to the contents of an array. That is, the result in each output array element only depends on the value in the corresponding input array (or arrays) a...
139
5,424
numpy
numpy/_pyinstaller/hook-numpy.py
.py
"""This hook should collect all binary files and any hidden modules that numpy needs. Our (some-what inadequate) docs for writing PyInstaller hooks are kept here: https://pyinstaller.readthedocs.io/en/stable/hooks.html """ from PyInstaller.compat import is_pure_conda from PyInstaller.utils.hooks import collect_dynami...
36
1,339
numpy
numpy/_pyinstaller/tests/pyinstaller-smoke.py
.py
"""A crude *bit of everything* smoke test to verify PyInstaller compatibility. PyInstaller typically goes wrong by forgetting to package modules, extension modules or shared libraries. This script should aim to touch as many of those as possible in an attempt to trip a ModuleNotFoundError or a DLL load failure due to ...
33
1,143
numpy
numpy/_pyinstaller/tests/test_pyinstaller.py
.py
import subprocess from pathlib import Path import pytest # PyInstaller has been very unproactive about replacing 'imp' with 'importlib'. @pytest.mark.filterwarnings('ignore::DeprecationWarning') # It also leaks io.BytesIO()s. @pytest.mark.filterwarnings('ignore::ResourceWarning') @pytest.mark.parametrize("mode", ["-...
36
1,135
numpy
numpy/fft/_helper.py
.py
""" 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) ...
236
6,801
numpy
numpy/fft/__init__.py
.py
""" 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...
214
8,156
numpy
numpy/fft/_pocketfft.py
.py
""" Discrete Fourier Transforms Routines in this module: fft(a, n=None, axis=-1, norm="backward") ifft(a, n=None, axis=-1, norm="backward") rfft(a, n=None, axis=-1, norm="backward") irfft(a, n=None, axis=-1, norm="backward") hfft(a, n=None, axis=-1, norm="backward") ihfft(a, n=None, axis=-1, norm="backward") fftn(a, ...
1,694
62,612
numpy
numpy/fft/tests/test_helper.py
.py
"""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,...
168
6,154
numpy
numpy/fft/tests/test_pocketfft.py
.py
import queue import threading import pytest import numpy as np from numpy.random import random from numpy.testing import IS_WASM, assert_allclose, assert_array_equal, assert_raises def fft1(x): L = len(x) phase = -2j * np.pi * (np.arange(L) / L) phase = np.arange(L).reshape(-1, 1) * phase return np....
610
25,161
numpy
numpy/random/_pickle.py
.py
from ._generator import Generator from ._mt19937 import MT19937 from ._pcg64 import PCG64, PCG64DXSM from ._philox import Philox from ._sfc64 import SFC64 from .bit_generator import BitGenerator from .mtrand import RandomState BitGenerators = {'MT19937': MT19937, 'PCG64': PCG64, 'PCG6...
89
2,742
numpy
numpy/random/__init__.py
.py
""" ======================== Random Number Generation ======================== Use ``default_rng()`` to create a `Generator` and call its methods. =============== ========================================================= Generator --------------- --------------------------------------------------------- Generator ...
214
7,480
numpy
numpy/random/tests/test_randomstate.py
.py
import hashlib import pickle import sys import warnings import pytest import numpy as np from numpy import random from numpy.random import MT19937, PCG64 from numpy.testing import ( IS_WASM, assert_, assert_array_almost_equal, assert_array_equal, assert_equal, assert_no_warnings, assert_ra...
2,108
88,050
numpy
numpy/random/tests/test_regression.py
.py
import inspect import sys import pytest import numpy as np from numpy import random from numpy.testing import assert_, assert_array_equal, assert_raises class TestRegression: def test_VonMises_range(self): # Make sure generated random variables are in [-pi, pi]. # Regression test for ticket #98...
175
6,244
numpy
numpy/random/tests/test_generator_mt19937_regressions.py
.py
import pytest import numpy as np from numpy.random import MT19937, PCG64, Generator from numpy.testing import assert_, assert_array_equal class TestRegression: def _create_generator(self): return Generator(MT19937(121263137472525314065)) def test_vonmises_range(self): # Make sure generated r...
241
9,328
numpy
numpy/random/tests/test_smoke.py
.py
import pickle from dataclasses import dataclass from functools import partial import pytest import numpy as np from numpy.random import MT19937, PCG64, PCG64DXSM, SFC64, Generator, Philox from numpy.testing import assert_, assert_array_equal, assert_equal DTYPES_BOOL_INT_UINT = (np.bool, np.int8, np.int16, np.int32,...
883
29,939
numpy
numpy/random/tests/test_random.py
.py
import sys import warnings import pytest import numpy as np from numpy import random from numpy.testing import ( IS_WASM, assert_, assert_array_almost_equal, assert_array_equal, assert_equal, assert_no_warnings, assert_raises, ) class TestSeed: def test_scalar(self): s = np.r...
1,724
71,231
numpy
numpy/random/tests/test_seed_sequence.py
.py
import numpy as np from numpy.random import SeedSequence from numpy.testing import ( assert_array_compare, assert_array_equal, assert_raises, assert_raises_regex, ) def test_reference_data(): """ Check that SeedSequence generates data the same as the C++ reference. https://gist.github.com/imn...
104
3,972
numpy
numpy/random/tests/test_extending.py
.py
import os import shutil import sys import sysconfig import warnings from importlib.util import module_from_spec, spec_from_file_location import pytest import numpy as np from numpy.testing import HAS_SUBPROCESSES, IS_EDITABLE from numpy.testing._private.utils import run_subprocess try: import cffi except ImportE...
130
4,623
numpy
numpy/random/tests/test_randomstate_regression.py
.py
import sys import pytest import numpy as np from numpy import random from numpy.testing import assert_, assert_array_equal, assert_raises class TestRegression: def test_VonMises_range(self): # Make sure generated random variables are in [-pi, pi]. # Regression test for ticket #986. for ...
250
9,319
numpy
numpy/random/tests/test_direct.py
.py
import os import sys from os.path import join import pytest import numpy as np from numpy.random import ( MT19937, PCG64, PCG64DXSM, SFC64, Generator, Philox, RandomState, SeedSequence, default_rng, ) from numpy.random._common import interface from numpy.testing import ( assert...
621
20,852
numpy
numpy/random/tests/test_generator_mt19937.py
.py
import hashlib import os.path import sys import warnings import pytest import numpy as np from numpy.exceptions import AxisError from numpy.linalg import LinAlgError from numpy.random import MT19937, Generator, RandomState, SeedSequence from numpy.testing import ( IS_64BIT, IS_WASM, assert_, assert_al...
2,830
118,963
numpy
numpy/random/_examples/numba/extending.py
.py
from timeit import timeit import numba as nb import numpy as np from numpy.random import PCG64 bit_gen = PCG64() next_d = bit_gen.cffi.next_double state_addr = bit_gen.cffi.state_address def normals(n, state): out = np.empty(n) for i in range((n + 1) // 2): x1 = 2.0 * next_d(state) - 1.0 x2 ...
87
1,959
numpy
numpy/random/_examples/numba/extending_distributions.py
.py
r""" Building the required library in this example requires a source distribution of NumPy or clone of the NumPy git repository since distributions.c is not included in binary distributions. On *nix, execute in numpy/random/src/distributions export ${PYTHON_VERSION}=3.8 # Python version export PYTHON_INCLUDE=#path to...
68
2,036
numpy
numpy/random/_examples/cffi/extending.py
.py
""" Use cffi to access any of the underlying C functions from distributions.h """ import os import cffi import numpy as np from .parse import parse_distributions_h ffi = cffi.FFI() inc_dir = os.path.join(np.get_include(), 'numpy') # Basic numpy types ffi.cdef(''' typedef intptr_t npy_intp; typedef unsigne...
45
882
numpy
numpy/random/_examples/cffi/parse.py
.py
import os def parse_distributions_h(ffi, inc_dir): """ Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef Read the function declarations without the "#define ..." macros that will be filled in when loading the library. """ with open(os.path.join(inc_dir, 'random', 'bi...
54
1,750
numpy
numpy/polynomial/legendre.py
.py
""" ================================================== Legendre Series (:mod:`numpy.polynomial.legendre`) ================================================== This module provides a number of objects (mostly functions) useful for dealing with Legendre series, including a `Legendre` class that encapsulates the usual arit...
1,656
53,023
numpy
numpy/polynomial/chebyshev.py
.py
""" ==================================================== Chebyshev Series (:mod:`numpy.polynomial.chebyshev`) ==================================================== This module provides a number of objects (mostly functions) useful for dealing with Chebyshev series, including a `Chebyshev` class that encapsulates the us...
2,054
64,229
numpy
numpy/polynomial/laguerre.py
.py
""" ================================================== Laguerre Series (:mod:`numpy.polynomial.laguerre`) ================================================== This module provides a number of objects (mostly functions) useful for dealing with Laguerre series, including a `Laguerre` class that encapsulates the usual arit...
1,730
54,515
numpy
numpy/polynomial/polyutils.py
.py
""" Utility classes and functions for the polynomial modules. This module provides: error and warning objects; a polynomial base class; and some routines used in both the `polynomial` and `chebyshev` modules. Functions --------- .. autosummary:: :toctree: generated/ as_series convert list of array_likes in...
760
22,635
numpy
numpy/polynomial/polynomial.py
.py
""" ================================================= Power Series (:mod:`numpy.polynomial.polynomial`) ================================================= This module provides a number of objects (mostly functions) useful for dealing with polynomials, including a `Polynomial` class that encapsulates the usual arithmeti...
1,684
54,834
numpy
numpy/polynomial/__init__.py
.py
""" A sub-package for efficiently dealing with polynomials. Within the documentation for this sub-package, a "finite power series," i.e., a polynomial (also referred to simply as a "series") is represented by a 1-D numpy array of the polynomial's coefficients, ordered from lowest order term to highest. For example, a...
188
6,726
numpy
numpy/polynomial/_polybase.py
.py
""" Abstract base class for the various polynomial Classes. The ABCPolyBase class provides the methods needed to implement the common API for the various polynomial classes. It operates as a mixin, but uses the abc module from the stdlib, hence it is only available for Python >= 2.6. """ import abc import numbers imp...
1,192
39,358
numpy
numpy/polynomial/hermite_e.py
.py
""" =================================================================== HermiteE Series, "Probabilists" (:mod:`numpy.polynomial.hermite_e`) =================================================================== This module provides a number of objects (mostly functions) useful for dealing with Hermite_e series, including...
1,693
54,210
numpy
numpy/polynomial/hermite.py
.py
""" ============================================================== Hermite Series, "Physicists" (:mod:`numpy.polynomial.hermite`) ============================================================== This module provides a number of objects (mostly functions) useful for dealing with Hermite series, including a `Hermite` clas...
1,795
56,647
numpy
numpy/polynomial/tests/test_legendre.py
.py
"""Tests for legendre module. """ from functools import reduce import numpy as np import numpy.polynomial.legendre as leg from numpy.polynomial.polynomial import polyval from numpy.testing import assert_, assert_almost_equal, assert_equal, assert_raises L0 = np.array([1]) L1 = np.array([0, 1]) L2 = np.array([-1, 0, ...
588
19,356
numpy
numpy/polynomial/tests/test_hermite.py
.py
"""Tests for hermite module. """ from functools import reduce import numpy as np import numpy.polynomial.hermite as herm from numpy.polynomial.polynomial import polyval from numpy.testing import assert_, assert_almost_equal, assert_equal, assert_raises H0 = np.array([1]) H1 = np.array([0, 2]) H2 = np.array([-2, 0, 4...
575
19,247
numpy
numpy/polynomial/tests/test_laguerre.py
.py
"""Tests for laguerre module. """ from functools import reduce import numpy as np import numpy.polynomial.laguerre as lag from numpy.polynomial.polynomial import polyval from numpy.testing import assert_, assert_almost_equal, assert_equal, assert_raises L0 = np.array([1]) / 1 L1 = np.array([1, -1]) / 1 L2 = np.array...
557
18,188
numpy
numpy/polynomial/tests/test_chebyshev.py
.py
"""Tests for chebyshev module. """ from functools import reduce import numpy as np import numpy.polynomial.chebyshev as cheb from numpy.polynomial.polynomial import polyval from numpy.testing import assert_, assert_almost_equal, assert_equal, assert_raises def trim(x): return cheb.chebtrim(x, tol=1e-6) T0 = [...
640
21,210
numpy
numpy/polynomial/tests/test_classes.py
.py
"""Test inter-conversion of different polynomial classes. This tests the convert and cast methods of all the polynomial classes. """ import operator as op from numbers import Number import pytest import numpy as np from numpy.exceptions import RankWarning from numpy.polynomial import ( Chebyshev, Hermite, ...
626
18,933
numpy
numpy/polynomial/tests/test_symbol.py
.py
""" Tests related to the ``symbol`` attribute of the ABCPolyBase class. """ import pytest import numpy.polynomial as poly from numpy._core import array from numpy.testing import assert_, assert_equal, assert_raises class TestInit: """ Test polynomial creation with symbol kwarg. """ c = [1, 2, 3] ...
218
5,375
numpy
numpy/polynomial/tests/test_polyutils.py
.py
"""Tests for polyutils module. """ import numpy as np import numpy.polynomial.polyutils as pu from numpy.testing import assert_, assert_almost_equal, assert_equal, assert_raises class TestMisc: def test_trimseq(self): tgt = [1] for num_trailing_zeros in range(5): res = pu.trimseq([1]...
124
3,759
numpy
numpy/polynomial/tests/test_printing.py
.py
from decimal import Decimal # For testing polynomial printing with object arrays from fractions import Fraction from math import inf, nan import pytest import numpy.polynomial as poly from numpy._core import arange, array, printoptions from numpy.testing import assert_, assert_equal class TestStrUnicodeSuperSubscr...
563
21,617
numpy
numpy/polynomial/tests/test_polynomial.py
.py
"""Tests for polynomial module. """ import pickle from copy import deepcopy from fractions import Fraction from functools import reduce import pytest import numpy as np import numpy.polynomial.polynomial as poly from numpy.testing import ( assert_, assert_almost_equal, assert_array_equal, assert_equa...
714
24,195
numpy
numpy/polynomial/tests/test_hermite_e.py
.py
"""Tests for hermite_e module. """ from functools import reduce import numpy as np import numpy.polynomial.hermite_e as herme from numpy.polynomial.polynomial import polyval from numpy.testing import assert_, assert_almost_equal, assert_equal, assert_raises He0 = np.array([1]) He1 = np.array([0, 1]) He2 = np.array([...
576
19,595
numpy
numpy/char/__init__.py
.py
from numpy._core.defchararray import __all__, __doc__ __DEPRECATED = frozenset({"chararray", "array", "asarray"}) def __getattr__(name: str): if name in __DEPRECATED: # Deprecated in NumPy 2.5, 2026-01-07 import warnings warnings.warn( ( "The chararray class i...
32
828
numpy
numpy/typing/__init__.py
.py
""" ============================ 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...
217
6,692
numpy
numpy/typing/tests/test_runtime.py
.py
"""Test the runtime usage of `numpy.typing`.""" from typing import ( Any, NamedTuple, Self, TypeAliasType, get_args, get_origin, get_type_hints, ) import pytest import numpy as np import numpy._typing as _npt import numpy.typing as npt class TypeTup(NamedTuple): typ: type # type ex...
104
3,114
numpy
numpy/typing/tests/test_isfile.py
.py
import os from pathlib import Path import pytest import numpy as np from numpy.testing import assert_ ROOT = Path(np.__file__).parents[0] FILES = [ ROOT / "py.typed", ROOT / "__init__.pyi", ROOT / "ctypeslib" / "__init__.pyi", ROOT / "_core" / "__init__.pyi", ROOT / "f2py" / "__init__.pyi", R...
36
954
numpy
numpy/typing/tests/test_typing.py
.py
import importlib.util import os import re import shutil import textwrap from collections import defaultdict from typing import TYPE_CHECKING import pytest # Only trigger a full `mypy` run if this environment variable is set # Note that these tests tend to take over a minute even on a macOS M1 CPU, # and more than tha...
208
6,420
numpy
numpy/typing/tests/data/pass/bitwise_ops.py
.py
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 = 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 & AR ...
132
959
numpy
numpy/typing/tests/data/pass/simple.py
.py
"""Simple expression that should pass with mypy.""" import operator from collections.abc import Iterable import numpy as np import numpy.typing as npt # 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...
171
2,755
numpy
numpy/typing/tests/data/pass/comparisons.py
.py
from __future__ import annotations from typing import Any, cast 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 = False c = 0j...
317
3,405
numpy
numpy/typing/tests/data/pass/flatiter.py
.py
import numpy as np a = np.empty((2, 2)).flat a.base a.copy() a.coords a.index iter(a) next(a) a[0] a[...] a[:] a.__array__() b = np.array([1]).flat a[b] a[0] = "1" a[:] = "2" a[...] = "3" a[[]] = "4" a[[0]] = "5" a[[[0]]] = "6" a[[[[[0]]]]] = "7" a[b] = "8"
27
262
numpy
numpy/typing/tests/data/pass/ndarray_misc.py
.py
""" 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 collections.abc import Hashable from typing import Any, cast import nump...
200
3,408
numpy
numpy/typing/tests/data/pass/einsumfunc.py
.py
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....
37
1,370
numpy
numpy/typing/tests/data/pass/lib_utils.py
.py
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)
20
317
numpy
numpy/typing/tests/data/pass/recfunctions.py
.py
"""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)], ...
165
4,974
numpy
numpy/typing/tests/data/pass/numeric.py
.py
""" Tests for :mod:`numpy._core.numeric`. Does not include tests which fall under ``array_constructors``. """ from typing import Any import numpy as np class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]): ... i8 = np.int64(1) A = np.arange(27).reshape(3, 3, 3) B = A.tolist() C = np.empty((27, 27))...
91
1,492
numpy
numpy/typing/tests/data/pass/arrayterator.py
.py
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: pas...
29
394
numpy
numpy/typing/tests/data/pass/random.py
.py
from __future__ import annotations from typing import Any import numpy as np SEED_NONE = None SEED_INT = 4579435749574957634658964293569 SEED_ARR: np.ndarray[Any, np.dtype[np.int64]] = np.array([1, 2, 3, 4], dtype=np.int64) SEED_ARRLIKE: list[int] = [1, 2, 3, 4] SEED_SEED_SEQ: np.random.SeedSequence = np.random.Seed...
1,499
61,825
numpy
numpy/typing/tests/data/pass/scalars.py
.py
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: ...
263
4,147
numpy
numpy/typing/tests/data/pass/ndarray_conversion.py
.py
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...
82
1,449
numpy
numpy/typing/tests/data/pass/array_constructors.py
.py
from typing import Any import numpy as np class Index: def __index__(self) -> int: return 0 class SubClass(np.ndarray[tuple[Any, ...], np.dtype[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...
138
2,447
numpy
numpy/typing/tests/data/pass/ufuncs.py
.py
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(....
17
422
numpy
numpy/typing/tests/data/pass/modules.py
.py
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...
46
625
numpy
numpy/typing/tests/data/pass/ufunc_config.py
.py
"""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...
65
1,205
numpy
numpy/typing/tests/data/pass/ma.py
.py
import datetime as dt from typing import Any, cast import numpy as np import numpy.typing as npt from numpy._typing import _Shape type MaskedArray[ScalarT: np.generic] = np.ma.MaskedArray[_Shape, np.dtype[ScalarT]] MAR_b: MaskedArray[np.bool] = np.ma.MaskedArray([True]) MAR_u: MaskedArray[np.uint32] = np.ma.MaskedAr...
200
3,894
numpy
numpy/typing/tests/data/pass/lib_version.py
.py
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"
19
299
numpy
numpy/typing/tests/data/pass/arrayprint.py
.py
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...
38
766
numpy
numpy/typing/tests/data/pass/ufunclike.py
.py
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 __trunc__(self) -> Object: return self def __ge__(self, value: object) -> bool: retur...
53
1,351
numpy
numpy/typing/tests/data/pass/array_like.py
.py
import numpy as np from numpy._typing import ArrayLike, NDArray, _SupportsArray x1: ArrayLike = True x2: ArrayLike = 5 x3: ArrayLike = 1.0 x4: ArrayLike = 1 + 1j x5: ArrayLike = np.int8(1) x6: ArrayLike = np.float64(1) x7: ArrayLike = np.complex128(1) x8: ArrayLike = np.array([1, 2, 3]) x9: ArrayLike = [1, 2, 3] x10: ...
38
939
numpy
numpy/typing/tests/data/pass/ndarray_shape_manipulation.py
.py
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() # type: ignore[deprecated] nd1.resize(4) # type: ignore[deprecated] nd1.resize(2, 2) # type: ignore[deprecated] nd1.res...
48
808
numpy
numpy/typing/tests/data/pass/lib_user_array.py
.py
"""Based on the `if __name__ == "__main__"` test code in `lib/_user_array_impl.py`.""" from __future__ import annotations import numpy as np from numpy.lib.user_array import container # type: ignore[deprecated] N = 10_000 W = H = int(N**0.5) a: np.ndarray[tuple[int, int], np.dtype[np.int32]] ua: container[tuple[in...
23
618
numpy
numpy/typing/tests/data/pass/numerictypes.py
.py
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...
18
331
numpy
numpy/typing/tests/data/pass/literal.py
.py
from __future__ import annotations from functools import partial from typing import TYPE_CHECKING, Any 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",...
53
1,473
numpy
numpy/typing/tests/data/pass/arithmetic.py
.py
from __future__ import annotations from typing import Any, cast import pytest import numpy as np import numpy.typing as npt 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.tim...
615
7,934
numpy
numpy/typing/tests/data/pass/warnings_and_errors.py
.py
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)
7
161