diff options
author | Eric Wieser <wieser.eric@gmail.com> | 2020-01-06 12:11:25 +0000 |
---|---|---|
committer | Eric Wieser <wieser.eric@gmail.com> | 2020-01-06 12:11:25 +0000 |
commit | 679c83407ca95eab7eec844e945a725b932fbb60 (patch) | |
tree | be7f65c9ff3e4335aca57de874e0736c37a23988 | |
parent | d7523e21aa65abb8ef58895c6bf3c768059f74aa (diff) | |
parent | c28fc48328e9621160debae4d0d99feeff3b8fdf (diff) | |
download | numpy-679c83407ca95eab7eec844e945a725b932fbb60.tar.gz |
Merge remote-tracking branch 'upstream/master' into remove-numpy.distutils.compat
461 files changed, 1411 insertions, 2543 deletions
diff --git a/azure-steps-windows.yml b/azure-steps-windows.yml index f17039455..fdc969890 100644 --- a/azure-steps-windows.yml +++ b/azure-steps-windows.yml @@ -9,7 +9,7 @@ steps: - script: python -m pip install -r test_requirements.txt displayName: 'Install dependencies; some are optional to avoid test skips' - powershell: | - $pyversion = python -c "from __future__ import print_function; import sys; print(sys.version.split()[0])" + $pyversion = python -c "import sys; print(sys.version.split()[0])" Write-Host "Python Version: $pyversion" $target = "C:\\hostedtoolcache\\windows\\Python\\$pyversion\\$(PYTHON_ARCH)\\lib\\openblas$env:OPENBLAS_SUFFIX.a" Write-Host "target path: $target" @@ -53,4 +53,4 @@ steps: inputs: testResultsFiles: '**/test-*.xml' failTaskOnFailedTests: true - testRunTitle: 'Publish test results for Python $(PYTHON_VERSION) $(BITS)-bit $(TEST_MODE) Windows'
\ No newline at end of file + testRunTitle: 'Publish test results for Python $(PYTHON_VERSION) $(BITS)-bit $(TEST_MODE) Windows' diff --git a/benchmarks/benchmarks/__init__.py b/benchmarks/benchmarks/__init__.py index e8a859ff4..e4193cf05 100644 --- a/benchmarks/benchmarks/__init__.py +++ b/benchmarks/benchmarks/__init__.py @@ -1,3 +1 @@ -from __future__ import absolute_import, division, print_function - from . import common diff --git a/benchmarks/benchmarks/bench_app.py b/benchmarks/benchmarks/bench_app.py index ccf6e4c4a..2a649f39b 100644 --- a/benchmarks/benchmarks/bench_app.py +++ b/benchmarks/benchmarks/bench_app.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np diff --git a/benchmarks/benchmarks/bench_avx.py b/benchmarks/benchmarks/bench_avx.py index f7b524e43..023696b90 100644 --- a/benchmarks/benchmarks/bench_avx.py +++ b/benchmarks/benchmarks/bench_avx.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np @@ -31,4 +29,3 @@ class AVX_UFunc(Benchmark): def time_ufunc(self, ufuncname, stride, dtype): self.f(self.arr[::stride]) - diff --git a/benchmarks/benchmarks/bench_core.py b/benchmarks/benchmarks/bench_core.py index f7ce61b8f..94d3ad503 100644 --- a/benchmarks/benchmarks/bench_core.py +++ b/benchmarks/benchmarks/bench_core.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np diff --git a/benchmarks/benchmarks/bench_function_base.py b/benchmarks/benchmarks/bench_function_base.py index 2170c4fc4..b1e592749 100644 --- a/benchmarks/benchmarks/bench_function_base.py +++ b/benchmarks/benchmarks/bench_function_base.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np @@ -106,7 +104,7 @@ def memoize(f): return f -class SortGenerator(object): +class SortGenerator: # The size of the unsorted area in the "random unsorted area" # benchmarks AREA_SIZE = 100 diff --git a/benchmarks/benchmarks/bench_import.py b/benchmarks/benchmarks/bench_import.py index 83edecafe..4b6ecbc7b 100644 --- a/benchmarks/benchmarks/bench_import.py +++ b/benchmarks/benchmarks/bench_import.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from subprocess import call from sys import executable from timeit import default_timer diff --git a/benchmarks/benchmarks/bench_indexing.py b/benchmarks/benchmarks/bench_indexing.py index a62a2050e..bb7596d0a 100644 --- a/benchmarks/benchmarks/bench_indexing.py +++ b/benchmarks/benchmarks/bench_indexing.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark, get_squares_, get_indexes_, get_indexes_rand_ from os.path import join as pjoin diff --git a/benchmarks/benchmarks/bench_io.py b/benchmarks/benchmarks/bench_io.py index 439cd422f..d5ce9a271 100644 --- a/benchmarks/benchmarks/bench_io.py +++ b/benchmarks/benchmarks/bench_io.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark, get_squares import numpy as np diff --git a/benchmarks/benchmarks/bench_lib.py b/benchmarks/benchmarks/bench_lib.py index f65a96dad..c22ceaa5e 100644 --- a/benchmarks/benchmarks/bench_lib.py +++ b/benchmarks/benchmarks/bench_lib.py @@ -1,8 +1,6 @@ """Benchmarks for `numpy.lib`.""" -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np diff --git a/benchmarks/benchmarks/bench_linalg.py b/benchmarks/benchmarks/bench_linalg.py index 5c44162a2..3abbe3670 100644 --- a/benchmarks/benchmarks/bench_linalg.py +++ b/benchmarks/benchmarks/bench_linalg.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark, get_squares_, get_indexes_rand, TYPES1 import numpy as np diff --git a/benchmarks/benchmarks/bench_ma.py b/benchmarks/benchmarks/bench_ma.py index aff78df0a..b214c0b86 100644 --- a/benchmarks/benchmarks/bench_ma.py +++ b/benchmarks/benchmarks/bench_ma.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np diff --git a/benchmarks/benchmarks/bench_overrides.py b/benchmarks/benchmarks/bench_overrides.py index 58572d07d..e44951785 100644 --- a/benchmarks/benchmarks/bench_overrides.py +++ b/benchmarks/benchmarks/bench_overrides.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark try: @@ -35,7 +33,7 @@ def mock_concatenate(arrays, axis=0, out=None): pass -class DuckArray(object): +class DuckArray: def __array_function__(self, func, types, args, kwargs): pass diff --git a/benchmarks/benchmarks/bench_random.py b/benchmarks/benchmarks/bench_random.py index c52b463e5..9a5125876 100644 --- a/benchmarks/benchmarks/bench_random.py +++ b/benchmarks/benchmarks/bench_random.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np diff --git a/benchmarks/benchmarks/bench_records.py b/benchmarks/benchmarks/bench_records.py index 41a6dd775..92e0fca16 100644 --- a/benchmarks/benchmarks/bench_records.py +++ b/benchmarks/benchmarks/bench_records.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import, division, print_function import os from .common import Benchmark diff --git a/benchmarks/benchmarks/bench_reduce.py b/benchmarks/benchmarks/bench_reduce.py index 0043d5357..76c573a51 100644 --- a/benchmarks/benchmarks/bench_reduce.py +++ b/benchmarks/benchmarks/bench_reduce.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark, TYPES1, get_squares import numpy as np diff --git a/benchmarks/benchmarks/bench_shape_base.py b/benchmarks/benchmarks/bench_shape_base.py index 187b923cd..0c7dc4e72 100644 --- a/benchmarks/benchmarks/bench_shape_base.py +++ b/benchmarks/benchmarks/bench_shape_base.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark import numpy as np diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py index 62e70782d..9f45a7257 100644 --- a/benchmarks/benchmarks/bench_ufunc.py +++ b/benchmarks/benchmarks/bench_ufunc.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - from .common import Benchmark, get_squares_ import numpy as np @@ -152,7 +150,7 @@ class Scalar(Benchmark): (self.y + self.z) -class ArgPack(object): +class ArgPack: __slots__ = ['args', 'kwargs'] def __init__(self, *args, **kwargs): self.args = args diff --git a/benchmarks/benchmarks/common.py b/benchmarks/benchmarks/common.py index 18a09fd40..3fd81a164 100644 --- a/benchmarks/benchmarks/common.py +++ b/benchmarks/benchmarks/common.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - import numpy import random @@ -112,5 +110,5 @@ def get_indexes_rand_(): return indexes_rand_ -class Benchmark(object): +class Benchmark: goal_time = 0.25 diff --git a/doc/DISTUTILS.rst.txt b/doc/DISTUTILS.rst.txt index bcef82500..677398baa 100644 --- a/doc/DISTUTILS.rst.txt +++ b/doc/DISTUTILS.rst.txt @@ -577,9 +577,6 @@ The header of a typical SciPy ``__init__.py`` is:: Package docstring, typically with a brief description and function listing. """ - # py3k related imports - from __future__ import division, print_function, absolute_import - # import functions into module namespace from .subpackage import * ... diff --git a/doc/Py3K.rst.txt b/doc/Py3K.rst.txt index b23536ca5..fe2dd13c4 100644 --- a/doc/Py3K.rst.txt +++ b/doc/Py3K.rst.txt @@ -225,6 +225,8 @@ A #define in config.h, defined when building for Py3. Currently, this is generated as a part of the config. Is this sensible (we could also use Py_VERSION_HEX)? + This is being cleaned up in the C code. + private/npy_3kcompat.h ---------------------- @@ -355,9 +357,7 @@ The Py2/Py3 compatible structure definition looks like:: (binaryfunc)0, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 (unaryfunc)NULL, /*nb_index*/ - #endif }; @@ -394,14 +394,6 @@ There are a couple of places that need further attention: In some cases, this returns a buffer object on Python 2. On Python 3, there is no stand-alone buffer object, so we return a byte array instead. -- multiarray.int_asbuffer - - Converts an integer to a void* pointer -- in Python. - - Should we just remove this for Py3? It doesn't seem like it is used - anywhere, and it doesn't sound very useful. - - The Py2/Py3 compatible PyBufferMethods definition looks like:: NPY_NO_EXPORT PyBufferProcs array_as_buffer = { @@ -430,10 +422,6 @@ The Py2/Py3 compatible PyBufferMethods definition looks like:: .. todo:: - Figure out what to do with int_asbuffer - -.. todo:: - There's stuff to clean up in numarray/_capi.c diff --git a/doc/TESTS.rst.txt b/doc/TESTS.rst.txt index 14cb28df8..9023c7100 100644 --- a/doc/TESTS.rst.txt +++ b/doc/TESTS.rst.txt @@ -119,7 +119,7 @@ that makes it hard to identify the test from the output of running the test suite with ``verbose=2`` (or similar verbosity setting). Use plain comments (``#``) if necessary. -Labeling tests +Labeling tests -------------- As an alternative to ``pytest.mark.<label>``, there are a number of labels you @@ -174,7 +174,7 @@ name; thus:: print 'doing teardown' - class TestMe(object): + class TestMe: def setup(): """Class-level setup""" print 'doing setup' diff --git a/doc/cdoc/numpyfilter.py b/doc/cdoc/numpyfilter.py index 0ec50697e..65c801206 100755 --- a/doc/cdoc/numpyfilter.py +++ b/doc/cdoc/numpyfilter.py @@ -6,8 +6,6 @@ Interpret C comments as ReStructuredText, and replace them by the HTML output. Also, add Doxygen /** and /**< syntax automatically where appropriate. """ -from __future__ import division, absolute_import, print_function - import sys import re import os diff --git a/doc/changelog/1.16.6-changelog.rst b/doc/changelog/1.16.6-changelog.rst new file mode 100644 index 000000000..62ff46c34 --- /dev/null +++ b/doc/changelog/1.16.6-changelog.rst @@ -0,0 +1,36 @@ + +Contributors +============ + +A total of 10 people contributed to this release. + +* CakeWithSteak +* Charles Harris +* Chris Burr +* Eric Wieser +* Fernando Saravia +* Lars Grueter +* Matti Picus +* Maxwell Aladago +* Qiming Sun +* Warren Weckesser + +Pull requests merged +==================== + +A total of 14 pull requests were merged for this release. + +* `#14211 <https://github.com/numpy/numpy/pull/14211>`__: BUG: Fix uint-overflow if padding with linear_ramp and negative... +* `#14275 <https://github.com/numpy/numpy/pull/14275>`__: BUG: fixing to allow unpickling of PY3 pickles from PY2 +* `#14340 <https://github.com/numpy/numpy/pull/14340>`__: BUG: Fix misuse of .names and .fields in various places (backport... +* `#14423 <https://github.com/numpy/numpy/pull/14423>`__: BUG: test, fix regression in converting to ctypes. +* `#14434 <https://github.com/numpy/numpy/pull/14434>`__: BUG: Fixed maximum relative error reporting in assert_allclose +* `#14509 <https://github.com/numpy/numpy/pull/14509>`__: BUG: Fix regression in boolean matmul. +* `#14686 <https://github.com/numpy/numpy/pull/14686>`__: BUG: properly define PyArray_DescrCheck +* `#14853 <https://github.com/numpy/numpy/pull/14853>`__: BLD: add 'apt update' to shippable +* `#14854 <https://github.com/numpy/numpy/pull/14854>`__: BUG: Fix _ctypes class circular reference. (#13808) +* `#14856 <https://github.com/numpy/numpy/pull/14856>`__: BUG: Fix `np.einsum` errors on Power9 Linux and z/Linux +* `#14863 <https://github.com/numpy/numpy/pull/14863>`__: BLD: Prevent -flto from optimising long double representation... +* `#14864 <https://github.com/numpy/numpy/pull/14864>`__: BUG: lib: Fix histogram problem with signed integer arrays. +* `#15172 <https://github.com/numpy/numpy/pull/15172>`__: ENH: Backport improvements to testing functions. +* `#15191 <https://github.com/numpy/numpy/pull/15191>`__: REL: Prepare for 1.16.6 release. diff --git a/doc/changelog/1.17.5-changelog.rst b/doc/changelog/1.17.5-changelog.rst new file mode 100644 index 000000000..7ac758075 --- /dev/null +++ b/doc/changelog/1.17.5-changelog.rst @@ -0,0 +1,26 @@ + +Contributors +============ + +A total of 6 people contributed to this release. People with a "+" by their +names contributed a patch for the first time. + +* Charles Harris +* Eric Wieser +* Ilhan Polat +* Matti Picus +* Michael Hudson-Doyle +* Ralf Gommers + +Pull requests merged +==================== + +A total of 7 pull requests were merged for this release. + +* `#14593 <https://github.com/numpy/numpy/pull/14593>`__: MAINT: backport Cython API cleanup to 1.17.x, remove docs +* `#14937 <https://github.com/numpy/numpy/pull/14937>`__: BUG: fix integer size confusion in handling array's ndmin argument +* `#14939 <https://github.com/numpy/numpy/pull/14939>`__: BUILD: remove SSE2 flag from numpy.random builds +* `#14993 <https://github.com/numpy/numpy/pull/14993>`__: MAINT: Added Python3.8 branch to dll lib discovery +* `#15038 <https://github.com/numpy/numpy/pull/15038>`__: BUG: Fix refcounting in ufunc object loops +* `#15067 <https://github.com/numpy/numpy/pull/15067>`__: BUG: Exceptions tracebacks are dropped +* `#15175 <https://github.com/numpy/numpy/pull/15175>`__: ENH: Backport improvements to testing functions. diff --git a/doc/example.py b/doc/example.py index 8a5f9948f..5e3d79807 100644 --- a/doc/example.py +++ b/doc/example.py @@ -8,8 +8,6 @@ extend over multiple lines, the closing three quotation marks must be on a line by itself, preferably preceded by a blank line. """ -from __future__ import division, absolute_import, print_function - import os # standard library imports first # Do NOT import using *, e.g. from numpy import * diff --git a/doc/postprocess.py b/doc/postprocess.py index 2e50c115e..b6d067437 100755 --- a/doc/postprocess.py +++ b/doc/postprocess.py @@ -6,8 +6,6 @@ Post-processes HTML and Latex files output by Sphinx. MODE is either 'html' or 'tex'. """ -from __future__ import division, absolute_import, print_function - import re import optparse import io diff --git a/doc/release/upcoming_changes/15218.improvement.rst b/doc/release/upcoming_changes/15218.improvement.rst new file mode 100644 index 000000000..ccbbbd66f --- /dev/null +++ b/doc/release/upcoming_changes/15218.improvement.rst @@ -0,0 +1,6 @@ +Use 64-bit integer size on 64-bit platforms in fallback lapack_lite +------------------------------------------------------------------- + +Use 64-bit integer size on 64-bit platforms in the fallback LAPACK library, +which is used when the system has no LAPACK installed, allowing it to deal with +linear algebra for large arrays. diff --git a/doc/release/upcoming_changes/15229.compatibility.rst b/doc/release/upcoming_changes/15229.compatibility.rst new file mode 100644 index 000000000..404f7774f --- /dev/null +++ b/doc/release/upcoming_changes/15229.compatibility.rst @@ -0,0 +1,7 @@ +Removed ``multiarray.int_asbuffer`` +----------------------------------- + +As part of the continued removal of Python 2 compatibility, +``multiarray.int_asbuffer`` was removed. On Python 3, it threw a +``NotImplementedError`` and was unused internally. It is expected that there +are no downstream use cases for this method with Python 3. diff --git a/doc/release/upcoming_changes/15251.c_api.rst b/doc/release/upcoming_changes/15251.c_api.rst new file mode 100644 index 000000000..f391c904b --- /dev/null +++ b/doc/release/upcoming_changes/15251.c_api.rst @@ -0,0 +1,10 @@ +Better support for ``const`` dimensions in API functions +-------------------------------------------------------- +The following functions now accept a constant array of ``npy_intp``: + +* `PyArray_BroadcastToShape` +* `PyArray_IntTupleFromIntp` +* `PyArray_OverflowMultiplyList` + +Previously the caller would have to cast away the const-ness to call these +functions. diff --git a/doc/source/conf.py b/doc/source/conf.py index 09770535b..7e3a145f5 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import division, absolute_import, print_function - import sys, os, re # Minimum version, enforced by sphinx diff --git a/doc/source/f2py/setup_example.py b/doc/source/f2py/setup_example.py index 54af77299..479acc004 100644 --- a/doc/source/f2py/setup_example.py +++ b/doc/source/f2py/setup_example.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.distutils.core import Extension ext1 = Extension(name = 'scalar', diff --git a/doc/source/reference/arrays.ndarray.rst b/doc/source/reference/arrays.ndarray.rst index 831d211bc..47692c8b4 100644 --- a/doc/source/reference/arrays.ndarray.rst +++ b/doc/source/reference/arrays.ndarray.rst @@ -512,10 +512,6 @@ Arithmetic: - Any third argument to :func:`pow()` is silently ignored, as the underlying :func:`ufunc <power>` takes only two arguments. - - The three division operators are all defined; :obj:`div` is active - by default, :obj:`truediv` is active when - :obj:`__future__` division is in effect. - - Because :class:`ndarray` is a built-in type (written in C), the ``__r{op}__`` special methods are not directly defined. diff --git a/doc/source/reference/c-api/array.rst b/doc/source/reference/c-api/array.rst index c910efa60..2eaf3a27a 100644 --- a/doc/source/reference/c-api/array.rst +++ b/doc/source/reference/c-api/array.rst @@ -2514,7 +2514,7 @@ this useful approach to looping over an array. stride and that axis will be used. .. c:function:: PyObject *PyArray_BroadcastToShape( \ - PyObject* arr, npy_intp *dimensions, int nd) + PyObject* arr, npy_intp const *dimensions, int nd) Return an array iterator that is broadcast to iterate as an array of the shape provided by *dimensions* and *nd*. diff --git a/doc/source/reference/random/multithreading.rst b/doc/source/reference/random/multithreading.rst index a0a31d0ea..8502429ce 100644 --- a/doc/source/reference/random/multithreading.rst +++ b/doc/source/reference/random/multithreading.rst @@ -24,7 +24,7 @@ seed will produce the same outputs. import concurrent.futures import numpy as np - class MultithreadedRNG(object): + class MultithreadedRNG: def __init__(self, n, seed=None, threads=None): rg = PCG64(seed) if threads is None: diff --git a/doc/source/release.rst b/doc/source/release.rst index 26373ad07..9679ec6c8 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -7,11 +7,13 @@ Release Notes 1.19.0 <release/1.19.0-notes> 1.18.0 <release/1.18.0-notes> + 1.17.5 <release/1.17.5-notes> 1.17.4 <release/1.17.4-notes> 1.17.3 <release/1.17.3-notes> 1.17.2 <release/1.17.2-notes> 1.17.1 <release/1.17.1-notes> 1.17.0 <release/1.17.0-notes> + 1.16.6 <release/1.16.6-notes> 1.16.5 <release/1.16.5-notes> 1.16.4 <release/1.16.4-notes> 1.16.3 <release/1.16.3-notes> diff --git a/doc/source/release/1.16.6-notes.rst b/doc/source/release/1.16.6-notes.rst new file mode 100644 index 000000000..0aeba3cd3 --- /dev/null +++ b/doc/source/release/1.16.6-notes.rst @@ -0,0 +1,87 @@ +.. currentmodule:: numpy + +========================== +NumPy 1.16.6 Release Notes +========================== + +The NumPy 1.16.6 release fixes bugs reported against the 1.16.5 release, and +also backports several enhancements from master that seem appropriate for a +release series that is the last to support Python 2.7. The wheels on PyPI are +linked with OpenBLAS v0.3.7, which should fix errors on Skylake series +cpus. + +Downstream developers building this release should use Cython >= 0.29.2 and, if +using OpenBLAS, OpenBLAS >= v0.3.7. The supported Python versions are 2.7 and +3.5-3.7. + +Highlights +========== + +- The ``np.testing.utils`` functions have been updated from 1.19.0-dev0. + This improves the function documentation and error messages as well + extending the ``assert_array_compare`` function to additional types. + + +New functions +============= + +Allow matmul (`@` operator) to work with object arrays. +------------------------------------------------------- +This is an enhancement that was added in NumPy 1.17 and seems reasonable to +include in the LTS 1.16 release series. + + +Compatibility notes +=================== + +Fix regression in matmul (`@` operator) for boolean types +--------------------------------------------------------- +Booleans were being treated as integers rather than booleans, +which was a regression from previous behavior. + + +Improvements +============ + +Array comparison assertions include maximum differences +------------------------------------------------------- +Error messages from array comparison tests such as ``testing.assert_allclose`` +now include "max absolute difference" and "max relative difference," in +addition to the previous "mismatch" percentage. This information makes it +easier to update absolute and relative error tolerances. + +Contributors +============ + +A total of 10 people contributed to this release. + +* CakeWithSteak +* Charles Harris +* Chris Burr +* Eric Wieser +* Fernando Saravia +* Lars Grueter +* Matti Picus +* Maxwell Aladago +* Qiming Sun +* Warren Weckesser + +Pull requests merged +==================== + +A total of 14 pull requests were merged for this release. + +* `#14211 <https://github.com/numpy/numpy/pull/14211>`__: BUG: Fix uint-overflow if padding with linear_ramp and negative... +* `#14275 <https://github.com/numpy/numpy/pull/14275>`__: BUG: fixing to allow unpickling of PY3 pickles from PY2 +* `#14340 <https://github.com/numpy/numpy/pull/14340>`__: BUG: Fix misuse of .names and .fields in various places (backport... +* `#14423 <https://github.com/numpy/numpy/pull/14423>`__: BUG: test, fix regression in converting to ctypes. +* `#14434 <https://github.com/numpy/numpy/pull/14434>`__: BUG: Fixed maximum relative error reporting in assert_allclose +* `#14509 <https://github.com/numpy/numpy/pull/14509>`__: BUG: Fix regression in boolean matmul. +* `#14686 <https://github.com/numpy/numpy/pull/14686>`__: BUG: properly define PyArray_DescrCheck +* `#14853 <https://github.com/numpy/numpy/pull/14853>`__: BLD: add 'apt update' to shippable +* `#14854 <https://github.com/numpy/numpy/pull/14854>`__: BUG: Fix _ctypes class circular reference. (#13808) +* `#14856 <https://github.com/numpy/numpy/pull/14856>`__: BUG: Fix `np.einsum` errors on Power9 Linux and z/Linux +* `#14863 <https://github.com/numpy/numpy/pull/14863>`__: BLD: Prevent -flto from optimising long double representation... +* `#14864 <https://github.com/numpy/numpy/pull/14864>`__: BUG: lib: Fix histogram problem with signed integer arrays. +* `#15172 <https://github.com/numpy/numpy/pull/15172>`__: ENH: Backport improvements to testing functions. +* `#15191 <https://github.com/numpy/numpy/pull/15191>`__: REL: Prepare for 1.16.6 release. diff --git a/doc/source/release/1.17.5-notes.rst b/doc/source/release/1.17.5-notes.rst new file mode 100644 index 000000000..0f1d3e1a5 --- /dev/null +++ b/doc/source/release/1.17.5-notes.rst @@ -0,0 +1,45 @@ +.. currentmodule:: numpy + +========================== +NumPy 1.17.5 Release Notes +========================== + +This release contains fixes for bugs reported against NumPy 1.17.4 along with +some build improvements. The Python versions supported in this release +are 3.5-3.8. + +Downstream developers should use Cython >= 0.29.14 for Python 3.8 support and +OpenBLAS >= 3.7 to avoid errors on the Skylake architecture. + +It is recommended that developers interested in the new random bit generators +upgrade to the NumPy 1.18.x series, as it has updated documentation and +many small improvements. + + +Contributors +============ + +A total of 6 people contributed to this release. People with a "+" by their +names contributed a patch for the first time. + +* Charles Harris +* Eric Wieser +* Ilhan Polat +* Matti Picus +* Michael Hudson-Doyle +* Ralf Gommers + + +Pull requests merged +==================== + +A total of 8 pull requests were merged for this release. + +* `#14593 <https://github.com/numpy/numpy/pull/14593>`__: MAINT: backport Cython API cleanup to 1.17.x, remove docs +* `#14937 <https://github.com/numpy/numpy/pull/14937>`__: BUG: fix integer size confusion in handling array's ndmin argument +* `#14939 <https://github.com/numpy/numpy/pull/14939>`__: BUILD: remove SSE2 flag from numpy.random builds +* `#14993 <https://github.com/numpy/numpy/pull/14993>`__: MAINT: Added Python3.8 branch to dll lib discovery +* `#15038 <https://github.com/numpy/numpy/pull/15038>`__: BUG: Fix refcounting in ufunc object loops +* `#15067 <https://github.com/numpy/numpy/pull/15067>`__: BUG: Exceptions tracebacks are dropped +* `#15175 <https://github.com/numpy/numpy/pull/15175>`__: ENH: Backport improvements to testing functions. +* `#15213 <https://github.com/numpy/numpy/pull/15213>`__: REL: Prepare for the NumPy 1.17.5 release. diff --git a/doc/source/user/c-info.ufunc-tutorial.rst b/doc/source/user/c-info.ufunc-tutorial.rst index 96a73f9a6..8ff45a934 100644 --- a/doc/source/user/c-info.ufunc-tutorial.rst +++ b/doc/source/user/c-info.ufunc-tutorial.rst @@ -137,7 +137,6 @@ the module. /* This initiates the module using the above definitions. */ - #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "spam", @@ -159,17 +158,6 @@ the module. } return m; } - #else - PyMODINIT_FUNC initspam(void) - { - PyObject *m; - - m = Py_InitModule("spam", SpamMethods); - if (m == NULL) { - return; - } - } - #endif To use the setup.py file, place setup.py and spammodule.c in the same folder. Then python setup.py build will build the module to import, @@ -322,7 +310,6 @@ the primary thing that must be changed to create your own ufunc. static void *data[1] = {NULL}; - #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", @@ -357,30 +344,6 @@ the primary thing that must be changed to create your own ufunc. return m; } - #else - PyMODINIT_FUNC initnpufunc(void) - { - PyObject *m, *logit, *d; - - - m = Py_InitModule("npufunc", LogitMethods); - if (m == NULL) { - return; - } - - import_array(); - import_umath(); - - logit = PyUFunc_FromFuncAndData(funcs, data, types, 1, 1, 1, - PyUFunc_None, "logit", - "logit_docstring", 0); - - d = PyModule_GetDict(m); - - PyDict_SetItemString(d, "logit", logit); - Py_DECREF(logit); - } - #endif This is a setup.py file for the above code. As before, the module can be build via calling python setup.py build at the command prompt, @@ -601,7 +564,6 @@ the primary thing that must be changed to create your own ufunc. NPY_LONGDOUBLE, NPY_LONGDOUBLE}; static void *data[4] = {NULL, NULL, NULL, NULL}; - #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", @@ -636,30 +598,6 @@ the primary thing that must be changed to create your own ufunc. return m; } - #else - PyMODINIT_FUNC initnpufunc(void) - { - PyObject *m, *logit, *d; - - - m = Py_InitModule("npufunc", LogitMethods); - if (m == NULL) { - return; - } - - import_array(); - import_umath(); - - logit = PyUFunc_FromFuncAndData(funcs, data, types, 4, 1, 1, - PyUFunc_None, "logit", - "logit_docstring", 0); - - d = PyModule_GetDict(m); - - PyDict_SetItemString(d, "logit", logit); - Py_DECREF(logit); - } - #endif This is a setup.py file for the above code. As before, the module can be build via calling python setup.py build at the command prompt, @@ -824,7 +762,6 @@ as well as all other properties of a ufunc. static void *data[1] = {NULL}; - #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", @@ -859,30 +796,6 @@ as well as all other properties of a ufunc. return m; } - #else - PyMODINIT_FUNC initnpufunc(void) - { - PyObject *m, *logit, *d; - - - m = Py_InitModule("npufunc", LogitMethods); - if (m == NULL) { - return; - } - - import_array(); - import_umath(); - - logit = PyUFunc_FromFuncAndData(funcs, data, types, 1, 2, 2, - PyUFunc_None, "logit", - "logit_docstring", 0); - - d = PyModule_GetDict(m); - - PyDict_SetItemString(d, "logit", logit); - Py_DECREF(logit); - } - #endif .. _`sec:NumPy-struct-dtype`: @@ -976,7 +889,6 @@ The C file is given below. static void *data[1] = {NULL}; - #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "struct_ufunc_test", @@ -988,31 +900,18 @@ The C file is given below. NULL, NULL }; - #endif - #if defined(NPY_PY3K) PyMODINIT_FUNC PyInit_struct_ufunc_test(void) - #else - PyMODINIT_FUNC initstruct_ufunc_test(void) - #endif { PyObject *m, *add_triplet, *d; PyObject *dtype_dict; PyArray_Descr *dtype; PyArray_Descr *dtypes[3]; - #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); - #else - m = Py_InitModule("struct_ufunc_test", StructUfuncTestMethods); - #endif if (m == NULL) { - #if defined(NPY_PY3K) return NULL; - #else - return; - #endif } import_array(); @@ -1043,9 +942,7 @@ The C file is given below. PyDict_SetItemString(d, "add_triplet", add_triplet); Py_DECREF(add_triplet); - #if defined(NPY_PY3K) return m; - #endif } .. index:: diff --git a/doc/source/user/quickstart.rst b/doc/source/user/quickstart.rst index 6211d0c69..34e327d75 100644 --- a/doc/source/user/quickstart.rst +++ b/doc/source/user/quickstart.rst @@ -117,9 +117,8 @@ from the type of the elements in the sequences. >>> b.dtype dtype('float64') -A frequent error consists in calling ``array`` with multiple numeric -arguments, rather than providing a single list of numbers as an -argument. +A frequent error consists in calling ``array`` with multiple arguments, +rather than providing a single sequence as an argument. :: @@ -174,8 +173,9 @@ state of the memory. By default, the dtype of the created array is array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260], [ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]]) -To create sequences of numbers, NumPy provides a function analogous to -``range`` that returns arrays instead of lists. +To create sequences of numbers, NumPy provides the ``arange`` function +which is analogous to the Python built-in ``range``, but returns an +array. :: @@ -300,9 +300,9 @@ elementwise in NumPy arrays. The matrix product can be performed using the ``@`` operator (in python >=3.5) or the ``dot`` function or method:: >>> A = np.array( [[1,1], - ... [0,1]] ) + ... [0,1]] ) >>> B = np.array( [[2,0], - ... [3,4]] ) + ... [3,4]] ) >>> A * B # elementwise product array([[2, 0], [0, 4]]) @@ -437,7 +437,7 @@ operate elementwise on an array, producing an array as output. `dot`, `floor`, `inner`, - `inv`, + `invert`, `lexsort`, `max`, `maximum`, @@ -732,8 +732,14 @@ stacks 1D arrays as columns into a 2D array. It is equivalent to array([[ 4., 3.], [ 2., 8.]]) -On the other hand, the function `ma.row_stack` is equivalent to `vstack` -for any input arrays. +On the other hand, the function `row_stack` is equivalent to `vstack` +for any input arrays. In fact, `row_stack` is an alias for `vstack`:: + + >>> np.column_stack is np.hstack + False + >>> np.row_stack is np.vstack + True + In general, for arrays with more than two dimensions, `hstack` stacks along their second axes, `vstack` stacks along their @@ -917,7 +923,7 @@ Array Creation `ogrid`, `ones`, `ones_like`, - `r`, + `r_`, `zeros`, `zeros_like` Conversions @@ -1431,11 +1437,15 @@ functions ``column_stack``, ``dstack``, ``hstack`` and ``vstack``, depending on the dimension in which the stacking is to be done. For example:: - x = np.arange(0,10,2) # x=([0,2,4,6,8]) - y = np.arange(5) # y=([0,1,2,3,4]) - m = np.vstack([x,y]) # m=([[0,2,4,6,8], - # [0,1,2,3,4]]) - xy = np.hstack([x,y]) # xy =([0,2,4,6,8,0,1,2,3,4]) + >>> x = np.arange(0,10,2) + >>> y = np.arange(5) + >>> m = np.vstack([x,y]) + >>> m + array([[0, 2, 4, 6, 8], + [0, 1, 2, 3, 4]]) + >>> xy = np.hstack([x,y]) + >>> xy + array([0, 2, 4, 6, 8, 0, 1, 2, 3, 4]) The logic behind those functions in more than two dimensions can be strange. @@ -1448,7 +1458,7 @@ Histograms ---------- The NumPy ``histogram`` function applied to an array returns a pair of -vectors: the histogram of the array and the vector of bins. Beware: +vectors: the histogram of the array and a vector of the bin edges. Beware: ``matplotlib`` also has a function to build histograms (called ``hist``, as in Matlab) that differs from the one in NumPy. The main difference is that ``pylab.hist`` plots the histogram automatically, while diff --git a/doc/summarize.py b/doc/summarize.py index cfce2713e..9b02a408c 100755 --- a/doc/summarize.py +++ b/doc/summarize.py @@ -5,8 +5,6 @@ summarize.py Show a summary about which NumPy functions are documented and which are not. """ -from __future__ import division, absolute_import, print_function - import os, glob, re, sys, inspect, optparse try: # Accessing collections abstract classes from collections diff --git a/numpy/__init__.py b/numpy/__init__.py index 349914b2f..73e979a18 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -104,8 +104,6 @@ available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. Exceptions to this rule are documented. """ -from __future__ import division, absolute_import, print_function - import sys import warnings diff --git a/numpy/_build_utils/__init__.py b/numpy/_build_utils/__init__.py index 1d0f69b67..e69de29bb 100644 --- a/numpy/_build_utils/__init__.py +++ b/numpy/_build_utils/__init__.py @@ -1 +0,0 @@ -from __future__ import division, absolute_import, print_function diff --git a/numpy/_build_utils/apple_accelerate.py b/numpy/_build_utils/apple_accelerate.py index 36dd7584a..b26aa12ad 100644 --- a/numpy/_build_utils/apple_accelerate.py +++ b/numpy/_build_utils/apple_accelerate.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys import re diff --git a/numpy/_globals.py b/numpy/_globals.py index f5c0761b5..9f44c7729 100644 --- a/numpy/_globals.py +++ b/numpy/_globals.py @@ -15,8 +15,6 @@ That was not the case when the singleton classes were defined in the numpy motivated this module. """ -from __future__ import division, absolute_import, print_function - __ALL__ = [ 'ModuleDeprecationWarning', 'VisibleDeprecationWarning', '_NoValue' ] @@ -56,7 +54,7 @@ class VisibleDeprecationWarning(UserWarning): VisibleDeprecationWarning.__module__ = 'numpy' -class _NoValueType(object): +class _NoValueType: """Special keyword value. The instance of this class may be used as the default value assigned to a diff --git a/numpy/_pytesttester.py b/numpy/_pytesttester.py index 6462fc5e6..56eb3ac67 100644 --- a/numpy/_pytesttester.py +++ b/numpy/_pytesttester.py @@ -27,8 +27,6 @@ This module is imported by every numpy subpackage, so lies at the top level to simplify circular import issues. For the same reason, it contains no numpy imports at module scope, instead importing numpy within function calls. """ -from __future__ import division, absolute_import, print_function - import sys import os @@ -44,7 +42,7 @@ def _show_numpy_info(): print("NumPy relaxed strides checking option:", relaxed_strides) -class PytestTester(object): +class PytestTester: """ Pytest test runner. @@ -166,7 +164,6 @@ class PytestTester(object): # Ignore python2.7 -3 warnings pytest_args += [ - r"-W ignore:sys\.exc_clear\(\) not supported in 3\.x:DeprecationWarning", r"-W ignore:in 3\.x, __setslice__:DeprecationWarning", r"-W ignore:in 3\.x, __getslice__:DeprecationWarning", r"-W ignore:buffer\(\) not supported in 3\.x:DeprecationWarning", diff --git a/numpy/compat/__init__.py b/numpy/compat/__init__.py index 5b371f5c0..afee621b8 100644 --- a/numpy/compat/__init__.py +++ b/numpy/compat/__init__.py @@ -8,8 +8,6 @@ extensions, which may be included for the following reasons: * we may only need a small subset of the copied library/module """ -from __future__ import division, absolute_import, print_function - from . import _inspect from . import py3k from ._inspect import getargspec, formatargspec diff --git a/numpy/compat/_inspect.py b/numpy/compat/_inspect.py index 439d0d2c2..9a874a71d 100644 --- a/numpy/compat/_inspect.py +++ b/numpy/compat/_inspect.py @@ -5,8 +5,6 @@ significantly contributes to numpy import times. Importing this copy has almost no overhead. """ -from __future__ import division, absolute_import, print_function - import types __all__ = ['getargspec', 'formatargspec'] diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py index f24a8af27..3d3002744 100644 --- a/numpy/compat/py3k.py +++ b/numpy/compat/py3k.py @@ -113,7 +113,7 @@ def is_pathlib_path(obj): return Path is not None and isinstance(obj, Path) # from Python 3.7 -class contextlib_nullcontext(object): +class contextlib_nullcontext: """Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular diff --git a/numpy/compat/setup.py b/numpy/compat/setup.py index 882857428..afa511673 100644 --- a/numpy/compat/setup.py +++ b/numpy/compat/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/compat/tests/test_compat.py b/numpy/compat/tests/test_compat.py index 1543aafaf..2b8acbaa0 100644 --- a/numpy/compat/tests/test_compat.py +++ b/numpy/compat/tests/test_compat.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from os.path import join from numpy.compat import isfileobj diff --git a/numpy/conftest.py b/numpy/conftest.py index 1baf4adda..a843f725f 100644 --- a/numpy/conftest.py +++ b/numpy/conftest.py @@ -1,8 +1,6 @@ """ Pytest configuration and fixtures for the Numpy test suite. """ -from __future__ import division, absolute_import, print_function - import os import pytest diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index c3b3f0392..815c61924 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -6,8 +6,6 @@ are available in the main ``numpy`` namespace - use that instead. """ -from __future__ import division, absolute_import, print_function - from numpy.version import version as __version__ import os diff --git a/numpy/core/_add_newdocs.py b/numpy/core/_add_newdocs.py index d552348d0..0dc46b6ad 100644 --- a/numpy/core/_add_newdocs.py +++ b/numpy/core/_add_newdocs.py @@ -8,8 +8,6 @@ NOTE: Many of the methods of ndarray have corresponding functions. core/fromnumeric.py, core/defmatrix.py up-to-date. """ -from __future__ import division, absolute_import, print_function - import sys from numpy.core import numerictypes as _numerictypes @@ -1036,7 +1034,7 @@ add_newdoc('numpy.core.multiarray', 'fromstring', A string containing the data. dtype : data-type, optional The data type of the array; default: float. For binary input data, - the data must be in exactly this format. Most builtin numeric types are + the data must be in exactly this format. Most builtin numeric types are supported and extension types may be supported. .. versionadded:: 1.18.0 @@ -1486,59 +1484,6 @@ add_newdoc('numpy.core.multiarray', 'promote_types', """) -if sys.version_info.major < 3: - add_newdoc('numpy.core.multiarray', 'newbuffer', - """ - newbuffer(size) - - Return a new uninitialized buffer object. - - Parameters - ---------- - size : int - Size in bytes of returned buffer object. - - Returns - ------- - newbuffer : buffer object - Returned, uninitialized buffer object of `size` bytes. - - """) - - add_newdoc('numpy.core.multiarray', 'getbuffer', - """ - getbuffer(obj [,offset[, size]]) - - Create a buffer object from the given object referencing a slice of - length size starting at offset. - - Default is the entire buffer. A read-write buffer is attempted followed - by a read-only buffer. - - Parameters - ---------- - obj : object - - offset : int, optional - - size : int, optional - - Returns - ------- - buffer_obj : buffer - - Examples - -------- - >>> buf = np.getbuffer(np.ones(5), 1, 3) - >>> len(buf) - 3 - >>> buf[0] - '\\x00' - >>> buf - <read-write buffer for 0x8af1e70, size 3, offset 1 at 0x8ba4ec0> - - """) - add_newdoc('numpy.core.multiarray', 'c_einsum', """ c_einsum(subscripts, *operands, out=None, dtype=None, order='K', @@ -3953,7 +3898,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', Examples -------- - For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``, + For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``, except that ``tolist`` changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2]) diff --git a/numpy/core/_asarray.py b/numpy/core/_asarray.py index 0ad4161f4..df569f22d 100644 --- a/numpy/core/_asarray.py +++ b/numpy/core/_asarray.py @@ -3,8 +3,6 @@ Functions in the ``as*array`` family that promote array-likes into arrays. `require` fits this category despite its name not matching this pattern. """ -from __future__ import division, absolute_import, print_function - from .overrides import set_module from .multiarray import array diff --git a/numpy/core/_dtype.py b/numpy/core/_dtype.py index df1ff180e..fa39dfcd4 100644 --- a/numpy/core/_dtype.py +++ b/numpy/core/_dtype.py @@ -3,8 +3,6 @@ A place for code to be called from the implementation of np.dtype String handling is much easier to do correctly in python. """ -from __future__ import division, absolute_import, print_function - import sys import numpy as np diff --git a/numpy/core/_internal.py b/numpy/core/_internal.py index 05e401e0b..88cf10a38 100644 --- a/numpy/core/_internal.py +++ b/numpy/core/_internal.py @@ -4,8 +4,6 @@ A place for internal code Some things are more easily handled Python. """ -from __future__ import division, absolute_import, print_function - import re import sys import platform @@ -203,7 +201,7 @@ def _commastring(astr): return result -class dummy_ctype(object): +class dummy_ctype: def __init__(self, cls): self._cls = cls def __mul__(self, other): @@ -238,16 +236,16 @@ _getintp_ctype.cache = None # Used for .ctypes attribute of ndarray -class _missing_ctypes(object): +class _missing_ctypes: def cast(self, num, obj): return num.value - class c_void_p(object): + class c_void_p: def __init__(self, ptr): self.value = ptr -class _ctypes(object): +class _ctypes: def __init__(self, array, ptr=None): self._arr = array @@ -523,7 +521,7 @@ _pep3118_unsupported_map = { 'X': 'function pointers', } -class _Stream(object): +class _Stream: def __init__(self, s): self.s = s self.byteorder = '@' @@ -845,7 +843,7 @@ def npy_ctypes_check(cls): return False -class recursive(object): +class recursive: ''' A decorator class for recursive nested functions. Naive recursive nested functions hold a reference to themselves: diff --git a/numpy/core/_methods.py b/numpy/core/_methods.py index 269e509b8..694523b20 100644 --- a/numpy/core/_methods.py +++ b/numpy/core/_methods.py @@ -3,8 +3,6 @@ Array methods which are called by both the C-code for the method and the Python code for the NumPy-namespace function """ -from __future__ import division, absolute_import, print_function - import warnings from numpy.core import multiarray as mu diff --git a/numpy/core/_ufunc_config.py b/numpy/core/_ufunc_config.py index c3951cc09..cc8d2bcb0 100644 --- a/numpy/core/_ufunc_config.py +++ b/numpy/core/_ufunc_config.py @@ -3,8 +3,6 @@ Functions for changing global ufunc configuration This provides helpers which wrap `umath.geterrobj` and `umath.seterrobj` """ -from __future__ import division, absolute_import, print_function - try: # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 @@ -290,7 +288,7 @@ def seterrcall(func): Log error message: - >>> class Log(object): + >>> class Log: ... def write(self, msg): ... print("LOG: %s" % msg) ... @@ -365,7 +363,7 @@ def geterrcall(): return umath.geterrobj()[2] -class _unspecified(object): +class _unspecified: pass @@ -431,8 +429,6 @@ class errstate(contextlib.ContextDecorator): OrderedDict([('divide', 'ignore'), ('invalid', 'ignore'), ('over', 'ignore'), ('under', 'ignore')]) """ - # Note that we don't want to run the above doctests because they will fail - # without a from __future__ import with_statement def __init__(self, **kwargs): self.call = kwargs.pop('call', _Unspecified) diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 401018015..136b9ecff 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -3,8 +3,6 @@ $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ """ -from __future__ import division, absolute_import, print_function - __all__ = ["array2string", "array_str", "array_repr", "set_string_function", "set_printoptions", "get_printoptions", "printoptions", "format_float_positional", "format_float_scientific"] @@ -851,7 +849,7 @@ def _none_or_positive_arg(x, name): raise ValueError("{} must be >= 0".format(name)) return x -class FloatingFormat(object): +class FloatingFormat: """ Formatter for subtypes of np.floating """ def __init__(self, data, precision, floatmode, suppress_small, sign=False, **kwarg): @@ -1140,7 +1138,7 @@ def format_float_positional(x, precision=None, unique=True, pad_right=pad_right) -class IntegerFormat(object): +class IntegerFormat: def __init__(self, data): if data.size > 0: max_str_len = max(len(str(np.max(data))), @@ -1153,7 +1151,7 @@ class IntegerFormat(object): return self.format % x -class BoolFormat(object): +class BoolFormat: def __init__(self, data, **kwargs): # add an extra space so " True" and "False" have the same length and # array elements align nicely when printed, except in 0d arrays @@ -1163,7 +1161,7 @@ class BoolFormat(object): return self.truestr if x else "False" -class ComplexFloatingFormat(object): +class ComplexFloatingFormat: """ Formatter for subtypes of np.complexfloating """ def __init__(self, x, precision, floatmode, suppress_small, sign=False, **kwarg): @@ -1192,7 +1190,7 @@ class ComplexFloatingFormat(object): return r + i -class _TimelikeFormat(object): +class _TimelikeFormat: def __init__(self, data): non_nat = data[~isnat(data)] if len(non_nat) > 0: @@ -1255,7 +1253,7 @@ class TimedeltaFormat(_TimelikeFormat): return str(x.astype('i8')) -class SubArrayFormat(object): +class SubArrayFormat: def __init__(self, format_function): self.format_function = format_function @@ -1265,7 +1263,7 @@ class SubArrayFormat(object): return "[" + ", ".join(self.__call__(a) for a in arr) + "]" -class StructuredVoidFormat(object): +class StructuredVoidFormat: """ Formatter for structured np.void objects. diff --git a/numpy/core/code_generators/__init__.py b/numpy/core/code_generators/__init__.py index 1d0f69b67..e69de29bb 100644 --- a/numpy/core/code_generators/__init__.py +++ b/numpy/core/code_generators/__init__.py @@ -1 +0,0 @@ -from __future__ import division, absolute_import, print_function diff --git a/numpy/core/code_generators/genapi.py b/numpy/core/code_generators/genapi.py index 22afa0320..4fa68a1f0 100644 --- a/numpy/core/code_generators/genapi.py +++ b/numpy/core/code_generators/genapi.py @@ -6,8 +6,6 @@ See ``find_function`` for how functions should be formatted, and specified. """ -from __future__ import division, absolute_import, print_function - from numpy.distutils.conv_template import process_file as process_c_file import sys, os, re @@ -76,7 +74,7 @@ def _repl(str): return str.replace('Bool', 'npy_bool') -class StealRef(object): +class StealRef: def __init__(self, arg): self.arg = arg # counting from 1 @@ -87,7 +85,7 @@ class StealRef(object): return 'NPY_STEALS_REF_TO_ARG(%d)' % self.arg -class NonNull(object): +class NonNull: def __init__(self, arg): self.arg = arg # counting from 1 @@ -98,7 +96,7 @@ class NonNull(object): return 'NPY_GCC_NONNULL(%d)' % self.arg -class Function(object): +class Function: def __init__(self, name, return_type, args, doc=''): self.name = name self.return_type = _repl(return_type) @@ -309,7 +307,7 @@ def write_file(filename, data): # Those *Api classes instances know how to output strings for the generated code -class TypeApi(object): +class TypeApi: def __init__(self, name, index, ptr_cast, api_name): self.index = index self.name = name @@ -331,7 +329,7 @@ extern NPY_NO_EXPORT PyTypeObject %(type)s; """ % {'type': self.name} return astr -class GlobalVarApi(object): +class GlobalVarApi: def __init__(self, name, index, type, api_name): self.name = name self.index = index @@ -355,7 +353,7 @@ extern NPY_NO_EXPORT %(type)s %(name)s; # Dummy to be able to consistently use *Api instances for all items in the # array api -class BoolValuesApi(object): +class BoolValuesApi: def __init__(self, name, index, api_name): self.name = name self.index = index @@ -377,7 +375,7 @@ extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; """ return astr -class FunctionApi(object): +class FunctionApi: def __init__(self, name, index, annotations, return_type, args, api_name): self.name = name self.index = index diff --git a/numpy/core/code_generators/generate_numpy_api.py b/numpy/core/code_generators/generate_numpy_api.py index 5e04fb86d..fe21bc543 100644 --- a/numpy/core/code_generators/generate_numpy_api.py +++ b/numpy/core/code_generators/generate_numpy_api.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - import os import genapi @@ -59,21 +57,12 @@ _import_array(void) return -1; } -#if PY_VERSION_HEX >= 0x03000000 if (!PyCapsule_CheckExact(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCapsule object"); Py_DECREF(c_api); return -1; } PyArray_API = (void **)PyCapsule_GetPointer(c_api, NULL); -#else - if (!PyCObject_Check(c_api)) { - PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCObject object"); - Py_DECREF(c_api); - return -1; - } - PyArray_API = (void **)PyCObject_AsVoidPtr(c_api); -#endif Py_DECREF(c_api); if (PyArray_API == NULL) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is NULL pointer"); @@ -120,13 +109,7 @@ _import_array(void) return 0; } -#if PY_VERSION_HEX >= 0x03000000 -#define NUMPY_IMPORT_ARRAY_RETVAL NULL -#else -#define NUMPY_IMPORT_ARRAY_RETVAL -#endif - -#define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NUMPY_IMPORT_ARRAY_RETVAL; } } +#define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NULL; } } #define import_array1(ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ret; } } diff --git a/numpy/core/code_generators/generate_ufunc_api.py b/numpy/core/code_generators/generate_ufunc_api.py index 1b0143e88..c32cf3e44 100644 --- a/numpy/core/code_generators/generate_ufunc_api.py +++ b/numpy/core/code_generators/generate_ufunc_api.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - import os import genapi @@ -51,21 +49,12 @@ _import_umath(void) return -1; } -#if PY_VERSION_HEX >= 0x03000000 if (!PyCapsule_CheckExact(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCapsule object"); Py_DECREF(c_api); return -1; } PyUFunc_API = (void **)PyCapsule_GetPointer(c_api, NULL); -#else - if (!PyCObject_Check(c_api)) { - PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCObject object"); - Py_DECREF(c_api); - return -1; - } - PyUFunc_API = (void **)PyCObject_AsVoidPtr(c_api); -#endif Py_DECREF(c_api); if (PyUFunc_API == NULL) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is NULL pointer"); @@ -74,12 +63,6 @@ _import_umath(void) return 0; } -#if PY_VERSION_HEX >= 0x03000000 -#define NUMPY_IMPORT_UMATH_RETVAL NULL -#else -#define NUMPY_IMPORT_UMATH_RETVAL -#endif - #define import_umath() \ do {\ UFUNC_NOFPE\ @@ -87,7 +70,7 @@ _import_umath(void) PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ - return NUMPY_IMPORT_UMATH_RETVAL;\ + return NULL;\ }\ } while(0) diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index 6d76f7ca2..c517248de 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - import os import re import struct @@ -21,16 +19,16 @@ ReorderableNone = "(Py_INCREF(Py_None), Py_None)" # Sentinel value to specify using the full type description in the # function name -class FullTypeDescr(object): +class FullTypeDescr: pass -class FuncNameSuffix(object): +class FuncNameSuffix: """Stores the suffix to append when generating functions names. """ def __init__(self, suffix): self.suffix = suffix -class TypeDescription(object): +class TypeDescription: """Type signature for a ufunc. Attributes @@ -120,7 +118,7 @@ def TD(types, f=None, astype=None, in_=None, out=None, simd=None): tds.append(TypeDescription(t, f=fd, in_=i, out=o, astype=astype, simd=simdt)) return tds -class Ufunc(object): +class Ufunc: """Description of a ufunc. Attributes diff --git a/numpy/core/code_generators/numpy_api.py b/numpy/core/code_generators/numpy_api.py index a71c236fd..916fb537e 100644 --- a/numpy/core/code_generators/numpy_api.py +++ b/numpy/core/code_generators/numpy_api.py @@ -13,8 +13,6 @@ When adding a function, make sure to use the next integer not used as an index exception, so it should hopefully not get unnoticed). """ -from __future__ import division, absolute_import, print_function - from code_generators.genapi import StealRef, NonNull # index, type diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index 9560eb31b..33ad1502d 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -9,7 +9,6 @@ for the ufuncs in numpy.core at the C level when the ufuncs are created at compile time. """ -from __future__ import division, absolute_import, print_function import textwrap docdict = {} @@ -3826,12 +3825,7 @@ add_newdoc('numpy.core.umath', 'true_divide', Notes ----- - The floor division operator ``//`` was added in Python 2.2 making - ``//`` and ``/`` equivalent operators. The default floor division - operation of ``/`` can be replaced by true division with ``from - __future__ import division``. - - In Python 3.0, ``//`` is the floor division operator and ``/`` the + In Python, ``//`` is the floor division operator and ``/`` the true division operator. The ``true_divide(x1, x2)`` function is equivalent to true division in Python. @@ -3844,7 +3838,6 @@ add_newdoc('numpy.core.umath', 'true_divide', >>> x//4 array([0, 0, 0, 0, 1]) - >>> from __future__ import division >>> x/4 array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4 diff --git a/numpy/core/cversions.py b/numpy/core/cversions.py index 7995dd993..00159c3a8 100644 --- a/numpy/core/cversions.py +++ b/numpy/core/cversions.py @@ -3,8 +3,6 @@ The API has is defined by numpy_api_order and ufunc_api_order. """ -from __future__ import division, absolute_import, print_function - from os.path import dirname from code_generators.genapi import fullapi_hash diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 168fd8c79..ff1474d9d 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -15,8 +15,6 @@ available in your version of Python. The preferred alias for `defchararray` is `numpy.char`. """ -from __future__ import division, absolute_import, print_function - import functools import sys from .numerictypes import string_, unicode_, integer, object_, bool_, character diff --git a/numpy/core/einsumfunc.py b/numpy/core/einsumfunc.py index 3412c3fd5..8ae14ce30 100644 --- a/numpy/core/einsumfunc.py +++ b/numpy/core/einsumfunc.py @@ -2,8 +2,6 @@ Implementation of optimized einsum. """ -from __future__ import division, absolute_import, print_function - import itertools from numpy.compat import basestring diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index f09f2a465..51b143762 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -1,8 +1,6 @@ """Module containing non-deprecated functions borrowed from Numeric. """ -from __future__ import division, absolute_import, print_function - import functools import types import warnings diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index 538ac8b84..8f92a4f71 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import functools import warnings import operator diff --git a/numpy/core/getlimits.py b/numpy/core/getlimits.py index 31fa6b9bf..a80db1c81 100644 --- a/numpy/core/getlimits.py +++ b/numpy/core/getlimits.py @@ -1,8 +1,6 @@ """Machine limits for Float32 and Float64 and (long double) if available... """ -from __future__ import division, absolute_import, print_function - __all__ = ['finfo', 'iinfo'] import warnings @@ -31,7 +29,7 @@ def _fr1(a): a.shape = () return a -class MachArLike(object): +class MachArLike: """ Object to simulate MachAr instance """ def __init__(self, @@ -291,7 +289,7 @@ def _discovered_machar(ftype): @set_module('numpy') -class finfo(object): +class finfo: """ finfo(dtype) @@ -442,7 +440,7 @@ class finfo(object): @set_module('numpy') -class iinfo(object): +class iinfo: """ iinfo(type) diff --git a/numpy/core/include/numpy/ndarrayobject.h b/numpy/core/include/numpy/ndarrayobject.h index 95e9cb060..b18d75f35 100644 --- a/numpy/core/include/numpy/ndarrayobject.h +++ b/numpy/core/include/numpy/ndarrayobject.h @@ -45,7 +45,6 @@ extern "C" { #define PyArray_CheckScalar(m) (PyArray_IsScalar(m, Generic) || \ PyArray_IsZeroDim(m)) -#if PY_MAJOR_VERSION >= 3 #define PyArray_IsPythonNumber(obj) \ (PyFloat_Check(obj) || PyComplex_Check(obj) || \ PyLong_Check(obj) || PyBool_Check(obj)) @@ -54,17 +53,6 @@ extern "C" { #define PyArray_IsPythonScalar(obj) \ (PyArray_IsPythonNumber(obj) || PyBytes_Check(obj) || \ PyUnicode_Check(obj)) -#else -#define PyArray_IsPythonNumber(obj) \ - (PyInt_Check(obj) || PyFloat_Check(obj) || PyComplex_Check(obj) || \ - PyLong_Check(obj) || PyBool_Check(obj)) -#define PyArray_IsIntegerScalar(obj) (PyInt_Check(obj) \ - || PyLong_Check(obj) \ - || PyArray_IsScalar((obj), Integer)) -#define PyArray_IsPythonScalar(obj) \ - (PyArray_IsPythonNumber(obj) || PyString_Check(obj) || \ - PyUnicode_Check(obj)) -#endif #define PyArray_IsAnyScalar(obj) \ (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonScalar(obj)) @@ -248,11 +236,6 @@ NPY_TITLE_KEY_check(PyObject *key, PyObject *value) if (PyUnicode_Check(title) && PyUnicode_Check(key)) { return PyUnicode_Compare(title, key) == 0 ? 1 : 0; } -#if PY_VERSION_HEX < 0x03000000 - if (PyString_Check(title) && PyString_Check(key)) { - return PyObject_Compare(title, key) == 0 ? 1 : 0; - } -#endif #endif return 0; } diff --git a/numpy/core/include/numpy/npy_1_7_deprecated_api.h b/numpy/core/include/numpy/npy_1_7_deprecated_api.h index a6ee21219..440458010 100644 --- a/numpy/core/include/numpy/npy_1_7_deprecated_api.h +++ b/numpy/core/include/numpy/npy_1_7_deprecated_api.h @@ -69,18 +69,11 @@ #define PyArray_DEFAULT NPY_DEFAULT_TYPE /* These DATETIME bits aren't used internally */ -#if PY_VERSION_HEX >= 0x03000000 #define PyDataType_GetDatetimeMetaData(descr) \ ((descr->metadata == NULL) ? NULL : \ ((PyArray_DatetimeMetaData *)(PyCapsule_GetPointer( \ PyDict_GetItemString( \ descr->metadata, NPY_METADATA_DTSTR), NULL)))) -#else -#define PyDataType_GetDatetimeMetaData(descr) \ - ((descr->metadata == NULL) ? NULL : \ - ((PyArray_DatetimeMetaData *)(PyCObject_AsVoidPtr( \ - PyDict_GetItemString(descr->metadata, NPY_METADATA_DTSTR))))) -#endif /* * Deprecated as of NumPy 1.7, this kind of shortcut doesn't diff --git a/numpy/core/include/numpy/npy_3kcompat.h b/numpy/core/include/numpy/npy_3kcompat.h index 7ed263796..6fe53caa1 100644 --- a/numpy/core/include/numpy/npy_3kcompat.h +++ b/numpy/core/include/numpy/npy_3kcompat.h @@ -13,11 +13,9 @@ #include <Python.h> #include <stdio.h> -#if PY_VERSION_HEX >= 0x03000000 #ifndef NPY_PY3K #define NPY_PY3K 1 #endif -#endif #include "numpy/npy_common.h" #include "numpy/ndarrayobject.h" diff --git a/numpy/core/machar.py b/numpy/core/machar.py index 202580bdb..a48dc3d50 100644 --- a/numpy/core/machar.py +++ b/numpy/core/machar.py @@ -5,8 +5,6 @@ floating-point arithmetic system Author: Pearu Peterson, September 2003 """ -from __future__ import division, absolute_import, print_function - __all__ = ['MachAr'] from numpy.core.fromnumeric import any @@ -16,7 +14,7 @@ from numpy.core.overrides import set_module # Need to speed this up...especially for longfloat @set_module('numpy') -class MachAr(object): +class MachAr: """ Diagnosing machine parameters. diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 062645551..ad0d7ad79 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from .numeric import uint8, ndarray, dtype from numpy.compat import ( diff --git a/numpy/core/multiarray.py b/numpy/core/multiarray.py index c0fcc10ff..5749afdcc 100644 --- a/numpy/core/multiarray.py +++ b/numpy/core/multiarray.py @@ -33,7 +33,7 @@ __all__ = [ 'digitize', 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype', 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat', 'frombuffer', 'fromfile', 'fromiter', 'fromstring', 'inner', - 'int_asbuffer', 'interp', 'interp_complex', 'is_busday', 'lexsort', + 'interp', 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters', 'normalize_axis_index', 'packbits', 'promote_types', 'putmask', 'ravel_multi_index', 'result_type', 'scalar', @@ -41,8 +41,6 @@ __all__ = [ 'set_string_function', 'set_typeDict', 'shares_memory', 'test_interrupt', 'tracemalloc_domain', 'typeinfo', 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros'] -if sys.version_info.major < 3: - __all__ += ['newbuffer', 'getbuffer'] # For backward compatibility, make sure pickle imports these functions from here _reconstruct.__module__ = 'numpy.core.multiarray' diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1e011e2e7..505218a2e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import functools import itertools import operator @@ -17,12 +15,10 @@ from .multiarray import ( WRAP, arange, array, broadcast, can_cast, compare_chararrays, concatenate, copyto, dot, dtype, empty, empty_like, flatiter, frombuffer, fromfile, fromiter, fromstring, - inner, int_asbuffer, lexsort, matmul, may_share_memory, + inner, lexsort, matmul, may_share_memory, min_scalar_type, ndarray, nditer, nested_iters, promote_types, putmask, result_type, set_numeric_ops, shares_memory, vdot, where, zeros, normalize_axis_index) -if sys.version_info[0] < 3: - from .multiarray import newbuffer, getbuffer from . import overrides from . import umath @@ -52,7 +48,7 @@ array_function_dispatch = functools.partial( __all__ = [ 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', - 'fromstring', 'fromfile', 'frombuffer', 'int_asbuffer', 'where', + 'fromstring', 'fromfile', 'frombuffer', 'where', 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort', 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type', 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', @@ -67,9 +63,6 @@ __all__ = [ 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError'] -if sys.version_info[0] < 3: - __all__.extend(['getbuffer', 'newbuffer']) - @set_module('numpy') class ComplexWarning(RuntimeWarning): diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 761c7087c..c63ea08c7 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -79,8 +79,6 @@ Exported symbols include: \\-> object_ (not used much) (kind=O) """ -from __future__ import division, absolute_import, print_function - import types as _types import sys import numbers diff --git a/numpy/core/records.py b/numpy/core/records.py index a1cad9075..6717dc69b 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -33,8 +33,6 @@ Record arrays allow us to access fields as properties:: array([2., 2.]) """ -from __future__ import division, absolute_import, print_function - import sys import os import warnings @@ -98,7 +96,7 @@ def find_duplicate(list): @set_module('numpy') -class format_parser(object): +class format_parser: """ Class to convert formats, names, titles description to a dtype. diff --git a/numpy/core/setup.py b/numpy/core/setup.py index 974ec4628..0d383b251 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - import os import sys import pickle @@ -38,7 +36,7 @@ NPY_RELAXED_STRIDES_DEBUG = NPY_RELAXED_STRIDES_DEBUG and NPY_RELAXED_STRIDES_CH # Use pickle in all cases, as cPickle is gone in python3 and the difference # in time is only in build. -- Charles Harris, 2013-03-30 -class CallOnceOnly(object): +class CallOnceOnly: def __init__(self): self._check_types = None self._check_ieee_macros = None diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index 6356f08ba..a947f7a3d 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - # Code common to build tools import sys import warnings diff --git a/numpy/core/shape_base.py b/numpy/core/shape_base.py index 31b1c20b9..d2f26149b 100644 --- a/numpy/core/shape_base.py +++ b/numpy/core/shape_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - __all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'block', 'hstack', 'stack', 'vstack'] diff --git a/numpy/core/src/common/array_assign.c b/numpy/core/src/common/array_assign.c index 0ac1b01c6..d626d1260 100644 --- a/numpy/core/src/common/array_assign.c +++ b/numpy/core/src/common/array_assign.c @@ -27,9 +27,9 @@ /* See array_assign.h for parameter documentation */ NPY_NO_EXPORT int -broadcast_strides(int ndim, npy_intp *shape, - int strides_ndim, npy_intp *strides_shape, npy_intp *strides, - char *strides_name, +broadcast_strides(int ndim, npy_intp const *shape, + int strides_ndim, npy_intp const *strides_shape, npy_intp const *strides, + char const *strides_name, npy_intp *out_strides) { int idim, idim_start = ndim - strides_ndim; @@ -84,8 +84,8 @@ broadcast_error: { /* See array_assign.h for parameter documentation */ NPY_NO_EXPORT int -raw_array_is_aligned(int ndim, npy_intp *shape, - char *data, npy_intp *strides, int alignment) +raw_array_is_aligned(int ndim, npy_intp const *shape, + char *data, npy_intp const *strides, int alignment) { /* diff --git a/numpy/core/src/common/array_assign.h b/numpy/core/src/common/array_assign.h index 69ef56bb4..f5d884dd9 100644 --- a/numpy/core/src/common/array_assign.h +++ b/numpy/core/src/common/array_assign.h @@ -44,8 +44,8 @@ PyArray_AssignRawScalar(PyArrayObject *dst, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -raw_array_assign_scalar(int ndim, npy_intp *shape, - PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, +raw_array_assign_scalar(int ndim, npy_intp const *shape, + PyArray_Descr *dst_dtype, char *dst_data, npy_intp const *dst_strides, PyArray_Descr *src_dtype, char *src_data); /* @@ -55,11 +55,11 @@ raw_array_assign_scalar(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, - PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, +raw_array_wheremasked_assign_scalar(int ndim, npy_intp const *shape, + PyArray_Descr *dst_dtype, char *dst_data, npy_intp const *dst_strides, PyArray_Descr *src_dtype, char *src_data, PyArray_Descr *wheremask_dtype, char *wheremask_data, - npy_intp *wheremask_strides); + npy_intp const *wheremask_strides); /******** LOW-LEVEL ARRAY MANIPULATION HELPERS ********/ @@ -80,9 +80,9 @@ raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -broadcast_strides(int ndim, npy_intp *shape, - int strides_ndim, npy_intp *strides_shape, npy_intp *strides, - char *strides_name, +broadcast_strides(int ndim, npy_intp const *shape, + int strides_ndim, npy_intp const *strides_shape, npy_intp const *strides, + char const *strides_name, npy_intp *out_strides); /* @@ -93,8 +93,8 @@ broadcast_strides(int ndim, npy_intp *shape, * cannot-be-aligned, in which case 0 (false) is always returned. */ NPY_NO_EXPORT int -raw_array_is_aligned(int ndim, npy_intp *shape, - char *data, npy_intp *strides, int alignment); +raw_array_is_aligned(int ndim, npy_intp const *shape, + char *data, npy_intp const *strides, int alignment); /* * Checks if an array is aligned to its "true alignment" diff --git a/numpy/core/src/common/lowlevel_strided_loops.h b/numpy/core/src/common/lowlevel_strided_loops.h index bacd27473..9208d5499 100644 --- a/numpy/core/src/common/lowlevel_strided_loops.h +++ b/numpy/core/src/common/lowlevel_strided_loops.h @@ -306,30 +306,30 @@ PyArray_CastRawArrays(npy_intp count, NPY_NO_EXPORT npy_intp PyArray_TransferNDimToStrided(npy_intp ndim, char *dst, npy_intp dst_stride, - char *src, npy_intp *src_strides, npy_intp src_strides_inc, - npy_intp *coords, npy_intp coords_inc, - npy_intp *shape, npy_intp shape_inc, + char *src, npy_intp const *src_strides, npy_intp src_strides_inc, + npy_intp const *coords, npy_intp coords_inc, + npy_intp const *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *transferdata); NPY_NO_EXPORT npy_intp PyArray_TransferStridedToNDim(npy_intp ndim, - char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, + char *dst, npy_intp const *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, - npy_intp *coords, npy_intp coords_inc, - npy_intp *shape, npy_intp shape_inc, + npy_intp const *coords, npy_intp coords_inc, + npy_intp const *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *transferdata); NPY_NO_EXPORT npy_intp PyArray_TransferMaskedStridedToNDim(npy_intp ndim, - char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, + char *dst, npy_intp const *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, npy_bool *mask, npy_intp mask_stride, - npy_intp *coords, npy_intp coords_inc, - npy_intp *shape, npy_intp shape_inc, + npy_intp const *coords, npy_intp coords_inc, + npy_intp const *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_MaskedStridedUnaryOp *stransfer, NpyAuxData *data); @@ -365,8 +365,8 @@ mapiter_set(PyArrayMapIterObject *mit); * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -PyArray_PrepareOneRawArrayIter(int ndim, npy_intp *shape, - char *data, npy_intp *strides, +PyArray_PrepareOneRawArrayIter(int ndim, npy_intp const *shape, + char *data, npy_intp const *strides, int *out_ndim, npy_intp *out_shape, char **out_data, npy_intp *out_strides); @@ -387,9 +387,9 @@ PyArray_PrepareOneRawArrayIter(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp *shape, - char *dataA, npy_intp *stridesA, - char *dataB, npy_intp *stridesB, +PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp const *shape, + char *dataA, npy_intp const *stridesA, + char *dataB, npy_intp const *stridesB, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB); @@ -411,10 +411,10 @@ PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -PyArray_PrepareThreeRawArrayIter(int ndim, npy_intp *shape, - char *dataA, npy_intp *stridesA, - char *dataB, npy_intp *stridesB, - char *dataC, npy_intp *stridesC, +PyArray_PrepareThreeRawArrayIter(int ndim, npy_intp const *shape, + char *dataA, npy_intp const *stridesA, + char *dataB, npy_intp const *stridesB, + char *dataC, npy_intp const *stridesC, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB, diff --git a/numpy/core/src/dummymodule.c b/numpy/core/src/dummymodule.c index 718199f70..e26875736 100644 --- a/numpy/core/src/dummymodule.c +++ b/numpy/core/src/dummymodule.c @@ -16,7 +16,6 @@ static struct PyMethodDef methods[] = { }; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "dummy", @@ -28,10 +27,8 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif /* Initialization function for the module */ -#if defined(NPY_PY3K) PyMODINIT_FUNC PyInit__dummy(void) { PyObject *m; m = PyModule_Create(&moduledef); @@ -40,9 +37,3 @@ PyMODINIT_FUNC PyInit__dummy(void) { } return m; } -#else -PyMODINIT_FUNC -init_dummy(void) { - Py_InitModule("_dummy", methods); -} -#endif diff --git a/numpy/core/src/multiarray/_multiarray_tests.c.src b/numpy/core/src/multiarray/_multiarray_tests.c.src index fa2efb428..1a51c06c7 100644 --- a/numpy/core/src/multiarray/_multiarray_tests.c.src +++ b/numpy/core/src/multiarray/_multiarray_tests.c.src @@ -55,7 +55,7 @@ EXPORT(void*) forward_pointer(void *x) * #typenum = NPY_DOUBLE, NPY_INT# */ static int copy_@name@(PyArrayIterObject *itx, PyArrayNeighborhoodIterObject *niterx, - npy_intp *bounds, + npy_intp const *bounds, PyObject **out) { npy_intp i, j; @@ -97,7 +97,7 @@ static int copy_@name@(PyArrayIterObject *itx, PyArrayNeighborhoodIterObject *ni /**end repeat**/ static int copy_object(PyArrayIterObject *itx, PyArrayNeighborhoodIterObject *niterx, - npy_intp *bounds, + npy_intp const *bounds, PyObject **out) { npy_intp i, j; @@ -251,7 +251,7 @@ clean_ax: static int copy_double_double(PyArrayNeighborhoodIterObject *itx, PyArrayNeighborhoodIterObject *niterx, - npy_intp *bounds, + npy_intp const *bounds, PyObject **out) { npy_intp i, j; @@ -2126,7 +2126,6 @@ static PyMethodDef Multiarray_TestsMethods[] = { }; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_multiarray_tests", @@ -2138,33 +2137,21 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif -#if defined(NPY_PY3K) -#define RETVAL m PyMODINIT_FUNC PyInit__multiarray_tests(void) -#else -#define RETVAL -PyMODINIT_FUNC -init_multiarray_tests(void) -#endif { PyObject *m; -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule("_multiarray_tests", Multiarray_TestsMethods); -#endif if (m == NULL) { - return RETVAL; + return m; } import_array(); if (PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load _multiarray_tests module."); } - return RETVAL; + return m; } NPY_NO_EXPORT int diff --git a/numpy/core/src/multiarray/array_assign_array.c b/numpy/core/src/multiarray/array_assign_array.c index 7ff33ebd7..e40b6c719 100644 --- a/numpy/core/src/multiarray/array_assign_array.c +++ b/numpy/core/src/multiarray/array_assign_array.c @@ -29,8 +29,8 @@ * elements, as required by the copy/casting code in lowlevel_strided_loops.c */ NPY_NO_EXPORT int -copycast_isaligned(int ndim, npy_intp *shape, - PyArray_Descr *dtype, char *data, npy_intp *strides) +copycast_isaligned(int ndim, npy_intp const *shape, + PyArray_Descr *dtype, char *data, npy_intp const *strides) { int aligned; int big_aln, small_aln; @@ -72,9 +72,9 @@ copycast_isaligned(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -raw_array_assign_array(int ndim, npy_intp *shape, - PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, - PyArray_Descr *src_dtype, char *src_data, npy_intp *src_strides) +raw_array_assign_array(int ndim, npy_intp const *shape, + PyArray_Descr *dst_dtype, char *dst_data, npy_intp const *dst_strides, + PyArray_Descr *src_dtype, char *src_data, npy_intp const *src_strides) { int idim; npy_intp shape_it[NPY_MAXDIMS]; @@ -152,11 +152,11 @@ raw_array_assign_array(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -raw_array_wheremasked_assign_array(int ndim, npy_intp *shape, - PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, - PyArray_Descr *src_dtype, char *src_data, npy_intp *src_strides, +raw_array_wheremasked_assign_array(int ndim, npy_intp const *shape, + PyArray_Descr *dst_dtype, char *dst_data, npy_intp const *dst_strides, + PyArray_Descr *src_dtype, char *src_data, npy_intp const *src_strides, PyArray_Descr *wheremask_dtype, char *wheremask_data, - npy_intp *wheremask_strides) + npy_intp const *wheremask_strides) { int idim; npy_intp shape_it[NPY_MAXDIMS]; diff --git a/numpy/core/src/multiarray/array_assign_scalar.c b/numpy/core/src/multiarray/array_assign_scalar.c index ecb5be47b..6bc9bcfee 100644 --- a/numpy/core/src/multiarray/array_assign_scalar.c +++ b/numpy/core/src/multiarray/array_assign_scalar.c @@ -30,8 +30,8 @@ * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -raw_array_assign_scalar(int ndim, npy_intp *shape, - PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, +raw_array_assign_scalar(int ndim, npy_intp const *shape, + PyArray_Descr *dst_dtype, char *dst_data, npy_intp const *dst_strides, PyArray_Descr *src_dtype, char *src_data) { int idim; @@ -101,11 +101,11 @@ raw_array_assign_scalar(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, - PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, +raw_array_wheremasked_assign_scalar(int ndim, npy_intp const *shape, + PyArray_Descr *dst_dtype, char *dst_data, npy_intp const *dst_strides, PyArray_Descr *src_dtype, char *src_data, PyArray_Descr *wheremask_dtype, char *wheremask_data, - npy_intp *wheremask_strides) + npy_intp const *wheremask_strides) { int idim; npy_intp shape_it[NPY_MAXDIMS], dst_strides_it[NPY_MAXDIMS]; diff --git a/numpy/core/src/multiarray/arrayobject.c b/numpy/core/src/multiarray/arrayobject.c index a5cebfbd8..6a500bd3f 100644 --- a/numpy/core/src/multiarray/arrayobject.c +++ b/numpy/core/src/multiarray/arrayobject.c @@ -1601,7 +1601,7 @@ PyArray_ElementStrides(PyObject *obj) /*NUMPY_API*/ NPY_NO_EXPORT npy_bool PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp offset, - npy_intp *dims, npy_intp *newstrides) + npy_intp const *dims, npy_intp const *newstrides) { npy_intp begin, end; npy_intp lower_offset; diff --git a/numpy/core/src/multiarray/arraytypes.c.src b/numpy/core/src/multiarray/arraytypes.c.src index 99897f9c2..077fb0ec8 100644 --- a/numpy/core/src/multiarray/arraytypes.c.src +++ b/numpy/core/src/multiarray/arraytypes.c.src @@ -748,7 +748,7 @@ _setup_field(int i, PyArray_Descr *descr, PyArrayObject *arr, } ((PyArrayObject_fields *)(arr))->descr = new; - if ((new->alignment > 1) && + if ((new->alignment > 1) && ((((uintptr_t)dstdata + offset) % new->alignment) != 0)) { PyArray_CLEARFLAGS(arr, NPY_ARRAY_ALIGNED); } @@ -836,7 +836,7 @@ VOID_setitem(PyObject *op, void *input, void *vap) if (names_size != PyTuple_Size(op)) { errmsg = PyUString_FromFormat( "could not assign tuple of length %zd to structure " - "with %" NPY_INTP_FMT " fields.", + "with %" NPY_INTP_FMT " fields.", PyTuple_Size(op), names_size); PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); @@ -3000,7 +3000,7 @@ OBJECT_compare(PyObject **ip1, PyObject **ip2, PyArrayObject *NPY_UNUSED(ap)) ret = PyObject_RichCompareBool(*ip1, *ip2, Py_LT); if (ret < 0) { - /* error occurred, avoid the next call to PyObject_RichCompareBool */ + /* error occurred, avoid the next call to PyObject_RichCompareBool */ return 0; } if (ret == 1) { @@ -4429,7 +4429,7 @@ static PyArray_ArrFuncs _Py@NAME@_ArrFuncs = { #if @rsort@ aradixsort_@suff@ #else - atimsort_@suff@ + atimsort_@suff@ #endif }, #else diff --git a/numpy/core/src/multiarray/common.c b/numpy/core/src/multiarray/common.c index c991f7428..64113c40b 100644 --- a/numpy/core/src/multiarray/common.c +++ b/numpy/core/src/multiarray/common.c @@ -695,7 +695,7 @@ _IsWriteable(PyArrayObject *ap) * @return Python unicode string */ NPY_NO_EXPORT PyObject * -convert_shape_to_string(npy_intp n, npy_intp *vals, char *ending) +convert_shape_to_string(npy_intp n, npy_intp const *vals, char *ending) { npy_intp i; PyObject *ret, *tmp; diff --git a/numpy/core/src/multiarray/common.h b/numpy/core/src/multiarray/common.h index 7eee9ddc5..281fc437c 100644 --- a/numpy/core/src/multiarray/common.h +++ b/numpy/core/src/multiarray/common.h @@ -61,7 +61,7 @@ NPY_NO_EXPORT npy_bool _IsWriteable(PyArrayObject *ap); NPY_NO_EXPORT PyObject * -convert_shape_to_string(npy_intp n, npy_intp *vals, char *ending); +convert_shape_to_string(npy_intp n, npy_intp const *vals, char *ending); /* * Sets ValueError with "matrices not aligned" message for np.dot and friends diff --git a/numpy/core/src/multiarray/compiled_base.c b/numpy/core/src/multiarray/compiled_base.c index 055d3e60f..67c861549 100644 --- a/numpy/core/src/multiarray/compiled_base.c +++ b/numpy/core/src/multiarray/compiled_base.c @@ -1159,12 +1159,12 @@ fail: } -/* +/* * Inner loop for unravel_index * order must be NPY_CORDER or NPY_FORTRANORDER */ static int -unravel_index_loop(int unravel_ndim, npy_intp *unravel_dims, +unravel_index_loop(int unravel_ndim, npy_intp const *unravel_dims, npy_intp unravel_size, npy_intp count, char *indices, npy_intp indices_stride, npy_intp *coords, NPY_ORDER order) @@ -1186,7 +1186,7 @@ unravel_index_loop(int unravel_ndim, npy_intp *unravel_dims, } idx = idx_start; for (i = 0; i < unravel_ndim; ++i) { - /* + /* * Using a local seems to enable single-divide optimization * but only if the / precedes the % */ diff --git a/numpy/core/src/multiarray/conversion_utils.c b/numpy/core/src/multiarray/conversion_utils.c index ca126b4b1..531d138d6 100644 --- a/numpy/core/src/multiarray/conversion_utils.c +++ b/numpy/core/src/multiarray/conversion_utils.c @@ -1145,7 +1145,7 @@ PyArray_TypestrConvert(int itemsize, int gentype) PyArray_IntTupleFromIntp */ NPY_NO_EXPORT PyObject * -PyArray_IntTupleFromIntp(int len, npy_intp *vals) +PyArray_IntTupleFromIntp(int len, npy_intp const *vals) { int i; PyObject *intTuple = PyTuple_New(len); diff --git a/numpy/core/src/multiarray/conversion_utils.h b/numpy/core/src/multiarray/conversion_utils.h index cd43f25c3..9bf712c3b 100644 --- a/numpy/core/src/multiarray/conversion_utils.h +++ b/numpy/core/src/multiarray/conversion_utils.h @@ -37,7 +37,7 @@ NPY_NO_EXPORT int PyArray_TypestrConvert(int itemsize, int gentype); NPY_NO_EXPORT PyObject * -PyArray_IntTupleFromIntp(int len, npy_intp *vals); +PyArray_IntTupleFromIntp(int len, npy_intp const *vals); NPY_NO_EXPORT int PyArray_SelectkindConverter(PyObject *obj, NPY_SELECTKIND *selectkind); diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index 6921427ce..599eb9765 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -950,7 +950,7 @@ discover_dimensions(PyObject *obj, int *maxndim, npy_intp *d, int check_it, } static PyObject * -raise_memory_error(int nd, npy_intp *dims, PyArray_Descr *descr) +raise_memory_error(int nd, npy_intp const *dims, PyArray_Descr *descr) { static PyObject *exc_type = NULL; diff --git a/numpy/core/src/multiarray/descriptor.c b/numpy/core/src/multiarray/descriptor.c index d4e18e457..89934bbd4 100644 --- a/numpy/core/src/multiarray/descriptor.c +++ b/numpy/core/src/multiarray/descriptor.c @@ -241,7 +241,7 @@ _convert_from_tuple(PyObject *obj, int align) if (!PyArray_DescrConverter(PyTuple_GET_ITEM(obj, 0), &type)) { return NULL; } - } + } val = PyTuple_GET_ITEM(obj,1); /* try to interpret next item as a type */ res = _use_inherit(type, val, &errflag); @@ -455,11 +455,11 @@ _convert_from_array_descr(PyObject *obj, int align) Py_INCREF(name); #if !defined(NPY_PY3K) - /* convert unicode name to ascii on Python 2 if possible */ + /* convert unicode name to ascii on Python 2 if possible */ if (PyUnicode_Check(name)) { PyObject *tmp = PyUnicode_AsASCIIString(name); Py_DECREF(name); - if (tmp == NULL) { + if (tmp == NULL) { goto fail; } name = tmp; diff --git a/numpy/core/src/multiarray/dtype_transfer.c b/numpy/core/src/multiarray/dtype_transfer.c index ef0dd4a01..b26d5ac89 100644 --- a/numpy/core/src/multiarray/dtype_transfer.c +++ b/numpy/core/src/multiarray/dtype_transfer.c @@ -3832,8 +3832,8 @@ PyArray_CastRawArrays(npy_intp count, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -PyArray_PrepareOneRawArrayIter(int ndim, npy_intp *shape, - char *data, npy_intp *strides, +PyArray_PrepareOneRawArrayIter(int ndim, npy_intp const *shape, + char *data, npy_intp const *strides, int *out_ndim, npy_intp *out_shape, char **out_data, npy_intp *out_strides) { @@ -3953,9 +3953,9 @@ PyArray_PrepareOneRawArrayIter(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp *shape, - char *dataA, npy_intp *stridesA, - char *dataB, npy_intp *stridesB, +PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp const *shape, + char *dataA, npy_intp const *stridesA, + char *dataB, npy_intp const *stridesB, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB) @@ -4077,10 +4077,10 @@ PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp *shape, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -PyArray_PrepareThreeRawArrayIter(int ndim, npy_intp *shape, - char *dataA, npy_intp *stridesA, - char *dataB, npy_intp *stridesB, - char *dataC, npy_intp *stridesC, +PyArray_PrepareThreeRawArrayIter(int ndim, npy_intp const *shape, + char *dataA, npy_intp const *stridesA, + char *dataB, npy_intp const *stridesB, + char *dataC, npy_intp const *stridesC, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB, diff --git a/numpy/core/src/multiarray/einsum.c.src b/numpy/core/src/multiarray/einsum.c.src index 58af44091..70af3fef9 100644 --- a/numpy/core/src/multiarray/einsum.c.src +++ b/numpy/core/src/multiarray/einsum.c.src @@ -107,7 +107,7 @@ */ static void @name@_sum_of_products_@noplabel@(int nop, char **dataptr, - npy_intp *strides, npy_intp count) + npy_intp const *strides, npy_intp count) { #if (@nop@ == 1) || (@nop@ <= 3 && !@complex@) char *data0 = dataptr[0]; @@ -206,7 +206,7 @@ static void static void @name@_sum_of_products_contig_one(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data_out = (@type@ *)dataptr[1]; @@ -268,7 +268,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_contig_two(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @@ -354,7 +354,7 @@ finish_after_unrolled_loop: /* Some extra specializations for the two operand case */ static void @name@_sum_of_products_stride0_contig_outcontig_two(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @temptype@ value0 = @from@(*(@type@ *)dataptr[0]); @type@ *data1 = (@type@ *)dataptr[1]; @@ -483,7 +483,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_contig_stride0_outcontig_two(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @temptype@ value1 = @from@(*(@type@ *)dataptr[1]); @@ -567,7 +567,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_contig_contig_outstride0_two(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @@ -727,7 +727,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_stride0_contig_outstride0_two(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @temptype@ value0 = @from@(*(@type@ *)dataptr[0]); @type@ *data1 = (@type@ *)dataptr[1]; @@ -826,7 +826,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_contig_stride0_outstride0_two(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @temptype@ value1 = @from@(*(@type@ *)dataptr[1]); @@ -927,7 +927,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_contig_three(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @@ -971,7 +971,7 @@ static void static void @name@_sum_of_products_contig_@noplabel@(int nop, char **dataptr, - npy_intp *NPY_UNUSED(strides), npy_intp count) + npy_intp const *NPY_UNUSED(strides), npy_intp count) { NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_@noplabel@ (%d)\n", (int)count); @@ -1024,7 +1024,7 @@ static void static void @name@_sum_of_products_contig_outstride0_one(int nop, char **dataptr, - npy_intp *strides, npy_intp count) + npy_intp const *strides, npy_intp count) { #if @complex@ @temptype@ accum_re = 0, accum_im = 0; @@ -1201,7 +1201,7 @@ finish_after_unrolled_loop: static void @name@_sum_of_products_outstride0_@noplabel@(int nop, char **dataptr, - npy_intp *strides, npy_intp count) + npy_intp const *strides, npy_intp count) { #if @complex@ @temptype@ accum_re = 0, accum_im = 0; @@ -1319,7 +1319,7 @@ static void static void bool_sum_of_products_@noplabel@(int nop, char **dataptr, - npy_intp *strides, npy_intp count) + npy_intp const *strides, npy_intp count) { #if (@nop@ <= 3) char *data0 = dataptr[0]; @@ -1376,7 +1376,7 @@ bool_sum_of_products_@noplabel@(int nop, char **dataptr, static void bool_sum_of_products_contig_@noplabel@(int nop, char **dataptr, - npy_intp *strides, npy_intp count) + npy_intp const *strides, npy_intp count) { #if (@nop@ <= 3) char *data0 = dataptr[0]; @@ -1484,7 +1484,7 @@ finish_after_unrolled_loop: static void bool_sum_of_products_outstride0_@noplabel@(int nop, char **dataptr, - npy_intp *strides, npy_intp count) + npy_intp const *strides, npy_intp count) { npy_bool accum = 0; @@ -1538,7 +1538,7 @@ bool_sum_of_products_outstride0_@noplabel@(int nop, char **dataptr, /**end repeat**/ -typedef void (*sum_of_products_fn)(int, char **, npy_intp *, npy_intp); +typedef void (*sum_of_products_fn)(int, char **, npy_intp const*, npy_intp); /* These tables need to match up with the type enum */ static sum_of_products_fn @@ -1720,7 +1720,7 @@ static sum_of_products_fn _unspecialized_table[NPY_NTYPES][4] = { static sum_of_products_fn get_sum_of_products_function(int nop, int type_num, - npy_intp itemsize, npy_intp *fixed_strides) + npy_intp itemsize, npy_intp const *fixed_strides) { int iop; diff --git a/numpy/core/src/multiarray/item_selection.c b/numpy/core/src/multiarray/item_selection.c index a6ac902d3..e2c3ebd00 100644 --- a/numpy/core/src/multiarray/item_selection.c +++ b/numpy/core/src/multiarray/item_selection.c @@ -825,7 +825,7 @@ PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *out, */ static int _new_sortlike(PyArrayObject *op, int axis, PyArray_SortFunc *sort, - PyArray_PartitionFunc *part, npy_intp *kth, npy_intp nkth) + PyArray_PartitionFunc *part, npy_intp const *kth, npy_intp nkth) { npy_intp N = PyArray_DIM(op, axis); npy_intp elsize = (npy_intp)PyArray_ITEMSIZE(op); @@ -953,7 +953,7 @@ fail: static PyObject* _new_argsortlike(PyArrayObject *op, int axis, PyArray_ArgSortFunc *argsort, PyArray_ArgPartitionFunc *argpart, - npy_intp *kth, npy_intp nkth) + npy_intp const *kth, npy_intp nkth) { npy_intp N = PyArray_DIM(op, axis); npy_intp elsize = (npy_intp)PyArray_ITEMSIZE(op); @@ -2028,7 +2028,7 @@ count_nonzero_bytes_384(const npy_uint64 * w) * Returns -1 on error. */ NPY_NO_EXPORT npy_intp -count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides) +count_boolean_trues(int ndim, char *data, npy_intp const *ashape, npy_intp const *astrides) { int idim; npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS]; @@ -2392,7 +2392,7 @@ PyArray_Nonzero(PyArrayObject *self) Py_DECREF(ret); return NULL; } - + needs_api = NpyIter_IterationNeedsAPI(iter); NPY_BEGIN_THREADS_NDITER(iter); @@ -2436,7 +2436,7 @@ finish: Py_DECREF(ret); return NULL; } - + /* if executed `nonzero()` check for miscount due to side-effect */ if (!is_bool && added_count != nonzero_count) { PyErr_SetString(PyExc_RuntimeError, diff --git a/numpy/core/src/multiarray/item_selection.h b/numpy/core/src/multiarray/item_selection.h index 2276b4db7..c1c8b5567 100644 --- a/numpy/core/src/multiarray/item_selection.h +++ b/numpy/core/src/multiarray/item_selection.h @@ -8,7 +8,7 @@ * Returns -1 on error. */ NPY_NO_EXPORT npy_intp -count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides); +count_boolean_trues(int ndim, char *data, npy_intp const *ashape, npy_intp const *astrides); /* * Gets a single item from the array, based on a single multi-index diff --git a/numpy/core/src/multiarray/lowlevel_strided_loops.c.src b/numpy/core/src/multiarray/lowlevel_strided_loops.c.src index 63b2a8842..d234c366c 100644 --- a/numpy/core/src/multiarray/lowlevel_strided_loops.c.src +++ b/numpy/core/src/multiarray/lowlevel_strided_loops.c.src @@ -974,9 +974,9 @@ PyArray_GetStridedNumericCastFn(int aligned, npy_intp src_stride, NPY_NO_EXPORT npy_intp PyArray_TransferNDimToStrided(npy_intp ndim, char *dst, npy_intp dst_stride, - char *src, npy_intp *src_strides, npy_intp src_strides_inc, - npy_intp *coords, npy_intp coords_inc, - npy_intp *shape, npy_intp shape_inc, + char *src, npy_intp const *src_strides, npy_intp src_strides_inc, + npy_intp const *coords, npy_intp coords_inc, + npy_intp const *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *data) @@ -1092,10 +1092,10 @@ PyArray_TransferNDimToStrided(npy_intp ndim, /* See documentation of arguments in lowlevel_strided_loops.h */ NPY_NO_EXPORT npy_intp PyArray_TransferStridedToNDim(npy_intp ndim, - char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, + char *dst, npy_intp const *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, - npy_intp *coords, npy_intp coords_inc, - npy_intp *shape, npy_intp shape_inc, + npy_intp const *coords, npy_intp coords_inc, + npy_intp const *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *data) @@ -1211,11 +1211,11 @@ PyArray_TransferStridedToNDim(npy_intp ndim, /* See documentation of arguments in lowlevel_strided_loops.h */ NPY_NO_EXPORT npy_intp PyArray_TransferMaskedStridedToNDim(npy_intp ndim, - char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, + char *dst, npy_intp const *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, npy_uint8 *mask, npy_intp mask_stride, - npy_intp *coords, npy_intp coords_inc, - npy_intp *shape, npy_intp shape_inc, + npy_intp const *coords, npy_intp coords_inc, + npy_intp const *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_MaskedStridedUnaryOp *stransfer, NpyAuxData *data) diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index e5845f2f6..ae26bbd4a 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -1469,7 +1469,7 @@ array_argpartition(PyArrayObject *self, PyObject *args, PyObject *kwds) static PyObject * array_searchsorted(PyArrayObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"keys", "side", "sorter", NULL}; + static char *kwlist[] = {"v", "side", "sorter", NULL}; PyObject *keys; PyObject *sorter; NPY_SEARCHSIDE side = NPY_SEARCHLEFT; diff --git a/numpy/core/src/multiarray/multiarraymodule.c b/numpy/core/src/multiarray/multiarraymodule.c index 33b654729..a725d9a49 100644 --- a/numpy/core/src/multiarray/multiarraymodule.c +++ b/numpy/core/src/multiarray/multiarraymodule.c @@ -161,7 +161,7 @@ PyArray_MultiplyList(npy_intp const *l1, int n) * Multiply a List of Non-negative numbers with over-flow detection. */ NPY_NO_EXPORT npy_intp -PyArray_OverflowMultiplyList(npy_intp *l1, int n) +PyArray_OverflowMultiplyList(npy_intp const *l1, int n) { npy_intp prod = 1; int i; @@ -3293,134 +3293,6 @@ array_datetime_data(PyObject *NPY_UNUSED(dummy), PyObject *args) return convert_datetime_metadata_to_tuple(meta); } -#if !defined(NPY_PY3K) -static PyObject * -new_buffer(PyObject *NPY_UNUSED(dummy), PyObject *args) -{ - int size; - - if (!PyArg_ParseTuple(args, "i:buffer", &size)) { - return NULL; - } - return PyBuffer_New(size); -} - -static PyObject * -buffer_buffer(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) -{ - PyObject *obj; - Py_ssize_t offset = 0, n; - Py_ssize_t size = Py_END_OF_BUFFER; - void *unused; - static char *kwlist[] = {"object", "offset", "size", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "O|" NPY_SSIZE_T_PYFMT NPY_SSIZE_T_PYFMT ":get_buffer", kwlist, - &obj, &offset, &size)) { - return NULL; - } - if (PyObject_AsWriteBuffer(obj, &unused, &n) < 0) { - PyErr_Clear(); - return PyBuffer_FromObject(obj, offset, size); - } - else { - return PyBuffer_FromReadWriteObject(obj, offset, size); - } -} -#endif - -#ifndef _MSC_VER -#include <setjmp.h> -#include <signal.h> -jmp_buf _NPY_SIGSEGV_BUF; -static void -_SigSegv_Handler(int signum) -{ - longjmp(_NPY_SIGSEGV_BUF, signum); -} -#endif - -#define _test_code() { \ - test = *((char*)memptr); \ - if (!ro) { \ - *((char *)memptr) = '\0'; \ - *((char *)memptr) = test; \ - } \ - test = *((char*)memptr+size-1); \ - if (!ro) { \ - *((char *)memptr+size-1) = '\0'; \ - *((char *)memptr+size-1) = test; \ - } \ - } - -static PyObject * -as_buffer(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) -{ - PyObject *mem; - Py_ssize_t size; - npy_bool ro = NPY_FALSE, check = NPY_TRUE; - void *memptr; - static char *kwlist[] = {"mem", "size", "readonly", "check", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "O" NPY_SSIZE_T_PYFMT "|O&O&:int_asbuffer", kwlist, - &mem, &size, PyArray_BoolConverter, &ro, - PyArray_BoolConverter, &check)) { - return NULL; - } - memptr = PyLong_AsVoidPtr(mem); - if (memptr == NULL) { - return NULL; - } - if (check) { - /* - * Try to dereference the start and end of the memory region - * Catch segfault and report error if it occurs - */ - char test; - int err = 0; - -#ifdef _MSC_VER - __try { - _test_code(); - } - __except(1) { - err = 1; - } -#else - PyOS_sighandler_t _npy_sig_save; - _npy_sig_save = PyOS_setsig(SIGSEGV, _SigSegv_Handler); - if (setjmp(_NPY_SIGSEGV_BUF) == 0) { - _test_code(); - } - else { - err = 1; - } - PyOS_setsig(SIGSEGV, _npy_sig_save); -#endif - if (err) { - PyErr_SetString(PyExc_ValueError, - "cannot use memory location as a buffer."); - return NULL; - } - } - - -#if defined(NPY_PY3K) - PyErr_SetString(PyExc_RuntimeError, - "XXX -- not implemented!"); - return NULL; -#else - if (ro) { - return PyBuffer_FromMemory(memptr, size); - } - return PyBuffer_FromReadWriteMemory(memptr, size); -#endif -} - -#undef _test_code - - /* * Prints floating-point scalars using the Dragon4 algorithm, scientific mode. * See docstring of `np.format_float_scientific` for description of arguments. @@ -4229,17 +4101,6 @@ static struct PyMethodDef array_module_methods[] = { {"is_busday", (PyCFunction)array_is_busday, METH_VARARGS | METH_KEYWORDS, NULL}, -#if !defined(NPY_PY3K) - {"newbuffer", - (PyCFunction)new_buffer, - METH_VARARGS, NULL}, - {"getbuffer", - (PyCFunction)buffer_buffer, - METH_VARARGS | METH_KEYWORDS, NULL}, -#endif - {"int_asbuffer", - (PyCFunction)as_buffer, - METH_VARARGS | METH_KEYWORDS, NULL}, {"format_longfloat", (PyCFunction)format_longfloat, METH_VARARGS | METH_KEYWORDS, NULL}, @@ -4551,7 +4412,6 @@ intern_strings(void) npy_ma_str_ndmin && npy_ma_str_axis1 && npy_ma_str_axis2; } -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_multiarray_umath", @@ -4563,25 +4423,14 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif /* Initialization function for the module */ -#if defined(NPY_PY3K) -#define RETVAL(x) x PyMODINIT_FUNC PyInit__multiarray_umath(void) { -#else -#define RETVAL(x) -PyMODINIT_FUNC init_multiarray_umath(void) { -#endif PyObject *m, *d, *s; PyObject *c_api; /* Create the module and add the functions */ -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule("_multiarray_umath", array_module_methods); -#endif if (!m) { goto err; } @@ -4766,12 +4615,12 @@ PyMODINIT_FUNC init_multiarray_umath(void) { if (initumath(m) != 0) { goto err; } - return RETVAL(m); + return m; err: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load multiarray module."); } - return RETVAL(NULL); + return NULL; } diff --git a/numpy/core/src/multiarray/nditer_constr.c b/numpy/core/src/multiarray/nditer_constr.c index 5e770338d..e40a2d594 100644 --- a/numpy/core/src/multiarray/nditer_constr.c +++ b/numpy/core/src/multiarray/nditer_constr.c @@ -56,7 +56,7 @@ static int npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itflags, char **op_dataptr, const npy_uint32 *op_flags, int **op_axes, - npy_intp *itershape); + npy_intp const *itershape); static void npyiter_replace_axisdata(NpyIter *iter, int iop, PyArrayObject *op, @@ -80,7 +80,7 @@ npyiter_get_common_dtype(int nop, PyArrayObject **op, static PyArrayObject * npyiter_new_temp_array(NpyIter *iter, PyTypeObject *subtype, npy_uint32 flags, npyiter_opitflags *op_itflags, - int op_ndim, npy_intp *shape, + int op_ndim, npy_intp const *shape, PyArray_Descr *op_dtype, const int *op_axes); static int npyiter_allocate_arrays(NpyIter *iter, @@ -1424,7 +1424,7 @@ static int npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itflags, char **op_dataptr, const npy_uint32 *op_flags, int **op_axes, - npy_intp *itershape) + npy_intp const *itershape) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); @@ -2476,7 +2476,7 @@ npyiter_get_common_dtype(int nop, PyArrayObject **op, static PyArrayObject * npyiter_new_temp_array(NpyIter *iter, PyTypeObject *subtype, npy_uint32 flags, npyiter_opitflags *op_itflags, - int op_ndim, npy_intp *shape, + int op_ndim, npy_intp const *shape, PyArray_Descr *op_dtype, const int *op_axes) { npy_uint32 itflags = NIT_ITFLAGS(iter); diff --git a/numpy/core/src/multiarray/scalartypes.c.src b/numpy/core/src/multiarray/scalartypes.c.src index 91ee64b5f..4cef01f89 100644 --- a/numpy/core/src/multiarray/scalartypes.c.src +++ b/numpy/core/src/multiarray/scalartypes.c.src @@ -1293,7 +1293,6 @@ gentype_sizeof(PyObject *self) return PyLong_FromSsize_t(nbytes); } -#if PY_VERSION_HEX >= 0x03000000 NPY_NO_EXPORT void gentype_struct_free(PyObject *ptr) { @@ -1307,17 +1306,6 @@ gentype_struct_free(PyObject *ptr) PyArray_free(arrif->shape); PyArray_free(arrif); } -#else -NPY_NO_EXPORT void -gentype_struct_free(void *ptr, void *arg) -{ - PyArrayInterface *arrif = (PyArrayInterface *)ptr; - Py_DECREF((PyObject *)arg); - Py_XDECREF(arrif->descr); - PyArray_free(arrif->shape); - PyArray_free(arrif); -} -#endif static PyObject * gentype_struct_get(PyObject *self) diff --git a/numpy/core/src/multiarray/scalartypes.h b/numpy/core/src/multiarray/scalartypes.h index 83b188128..861f2c943 100644 --- a/numpy/core/src/multiarray/scalartypes.h +++ b/numpy/core/src/multiarray/scalartypes.h @@ -19,13 +19,8 @@ initialize_casting_tables(void); NPY_NO_EXPORT void initialize_numeric_types(void); -#if PY_VERSION_HEX >= 0x03000000 NPY_NO_EXPORT void gentype_struct_free(PyObject *ptr); -#else -NPY_NO_EXPORT void -gentype_struct_free(void *ptr, void *arg); -#endif NPY_NO_EXPORT int is_anyscalar_exact(PyObject *obj); diff --git a/numpy/core/src/multiarray/shape.c b/numpy/core/src/multiarray/shape.c index 4e31f003b..127ac5134 100644 --- a/numpy/core/src/multiarray/shape.c +++ b/numpy/core/src/multiarray/shape.c @@ -981,7 +981,7 @@ PyArray_Flatten(PyArrayObject *a, NPY_ORDER order) /* See shape.h for parameters documentation */ NPY_NO_EXPORT PyObject * -build_shape_string(npy_intp n, npy_intp *vals) +build_shape_string(npy_intp n, npy_intp const *vals) { npy_intp i; PyObject *ret, *tmp; diff --git a/numpy/core/src/multiarray/shape.h b/numpy/core/src/multiarray/shape.h index 0451a463e..d25292556 100644 --- a/numpy/core/src/multiarray/shape.h +++ b/numpy/core/src/multiarray/shape.h @@ -6,7 +6,7 @@ * A negative value in 'vals' gets interpreted as newaxis. */ NPY_NO_EXPORT PyObject * -build_shape_string(npy_intp n, npy_intp *vals); +build_shape_string(npy_intp n, npy_intp const *vals); /* * Creates a sorted stride perm matching the KEEPORDER behavior diff --git a/numpy/core/src/multiarray/strfuncs.c b/numpy/core/src/multiarray/strfuncs.c index 495d897b2..33f3a6543 100644 --- a/numpy/core/src/multiarray/strfuncs.c +++ b/numpy/core/src/multiarray/strfuncs.c @@ -64,7 +64,7 @@ extend_str(char **strp, Py_ssize_t n, Py_ssize_t *maxp) static int dump_data(char **string, Py_ssize_t *n, Py_ssize_t *max_n, char *data, int nd, - npy_intp *dimensions, npy_intp *strides, PyArrayObject* self) + npy_intp const *dimensions, npy_intp const *strides, PyArrayObject* self) { PyObject *op = NULL, *sp = NULL; char *ostring; diff --git a/numpy/core/src/umath/_operand_flag_tests.c.src b/numpy/core/src/umath/_operand_flag_tests.c.src index 551a9c632..15fd7be6a 100644 --- a/numpy/core/src/umath/_operand_flag_tests.c.src +++ b/numpy/core/src/umath/_operand_flag_tests.c.src @@ -39,7 +39,6 @@ static char types[2] = {NPY_LONG, NPY_LONG}; static void *data[1] = {NULL}; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_operand_flag_tests", @@ -52,22 +51,12 @@ static struct PyModuleDef moduledef = { NULL }; -#define RETVAL m PyMODINIT_FUNC PyInit__operand_flag_tests(void) { -#else -#define RETVAL -PyMODINIT_FUNC init_operand_flag_tests(void) -{ -#endif PyObject *m = NULL; PyObject *ufunc; -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule("_operand_flag_tests", TestMethods); -#endif if (m == NULL) { goto fail; } @@ -87,19 +76,16 @@ PyMODINIT_FUNC init_operand_flag_tests(void) ((PyUFuncObject*)ufunc)->iter_flags = NPY_ITER_REDUCE_OK; PyModule_AddObject(m, "inplace_add", (PyObject*)ufunc); - return RETVAL; + return m; fail: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load _operand_flag_tests module."); } -#if defined(NPY_PY3K) if (m) { Py_DECREF(m); m = NULL; } -#endif - return RETVAL; - + return m; } diff --git a/numpy/core/src/umath/_rational_tests.c.src b/numpy/core/src/umath/_rational_tests.c.src index 615e395c7..b2b75da74 100644 --- a/numpy/core/src/umath/_rational_tests.c.src +++ b/numpy/core/src/umath/_rational_tests.c.src @@ -609,9 +609,6 @@ static PyNumberMethods pyrational_as_number = { pyrational_add, /* nb_add */ pyrational_subtract, /* nb_subtract */ pyrational_multiply, /* nb_multiply */ -#if PY_MAJOR_VERSION < 3 - pyrational_divide, /* nb_divide */ -#endif pyrational_remainder, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ @@ -625,27 +622,13 @@ static PyNumberMethods pyrational_as_number = { 0, /* nb_and */ 0, /* nb_xor */ 0, /* nb_or */ -#if PY_MAJOR_VERSION < 3 - 0, /* nb_coerce */ -#endif pyrational_int, /* nb_int */ -#if PY_MAJOR_VERSION < 3 - pyrational_int, /* nb_long */ -#else 0, /* reserved */ -#endif pyrational_float, /* nb_float */ -#if PY_MAJOR_VERSION < 3 - 0, /* nb_oct */ - 0, /* nb_hex */ -#endif 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ -#if PY_MAJOR_VERSION < 3 - 0, /* nb_inplace_divide */ -#endif 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ @@ -1126,7 +1109,6 @@ PyMethodDef module_methods[] = { {0} /* sentinel */ }; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_rational_tests", @@ -1138,16 +1120,8 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif -#if defined(NPY_PY3K) -#define RETVAL m PyMODINIT_FUNC PyInit__rational_tests(void) { -#else -#define RETVAL -PyMODINIT_FUNC init_rational_tests(void) { -#endif - PyObject *m = NULL; PyObject* numpy_str; PyObject* numpy; @@ -1292,11 +1266,7 @@ PyMODINIT_FUNC init_rational_tests(void) { REGISTER_UFUNC_UNARY(sign) /* Create module */ -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule("_rational_tests", module_methods); -#endif if (!m) { goto fail; @@ -1392,18 +1362,16 @@ PyMODINIT_FUNC init_rational_tests(void) { GCD_LCM_UFUNC(gcd,NPY_INT64,"greatest common denominator of two integers"); GCD_LCM_UFUNC(lcm,NPY_INT64,"least common multiple of two integers"); - return RETVAL; + return m; fail: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load _rational_tests module."); } -#if defined(NPY_PY3K) if (m) { Py_DECREF(m); m = NULL; } -#endif - return RETVAL; + return m; } diff --git a/numpy/core/src/umath/_struct_ufunc_tests.c.src b/numpy/core/src/umath/_struct_ufunc_tests.c.src index 3eaac73e1..1706dc829 100644 --- a/numpy/core/src/umath/_struct_ufunc_tests.c.src +++ b/numpy/core/src/umath/_struct_ufunc_tests.c.src @@ -100,7 +100,6 @@ static PyMethodDef StructUfuncTestMethods[] = { {NULL, NULL, 0, NULL} }; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_struct_ufunc_tests", @@ -112,31 +111,18 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif -#if defined(NPY_PY3K) PyMODINIT_FUNC PyInit__struct_ufunc_tests(void) -#else -PyMODINIT_FUNC init_struct_ufunc_tests(void) -#endif { PyObject *m, *add_triplet, *d; PyObject *dtype_dict; PyArray_Descr *dtype; PyArray_Descr *dtypes[3]; -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule("_struct_ufunc_tests", StructUfuncTestMethods); -#endif if (m == NULL) { -#if defined(NPY_PY3K) return NULL; -#else - return; -#endif } import_array(); @@ -166,7 +152,5 @@ PyMODINIT_FUNC init_struct_ufunc_tests(void) PyDict_SetItemString(d, "add_triplet", add_triplet); Py_DECREF(add_triplet); -#if defined(NPY_PY3K) return m; -#endif } diff --git a/numpy/core/src/umath/_umath_tests.c.src b/numpy/core/src/umath/_umath_tests.c.src index 6c3bcce71..bd3fe80b6 100644 --- a/numpy/core/src/umath/_umath_tests.c.src +++ b/numpy/core/src/umath/_umath_tests.c.src @@ -586,7 +586,6 @@ static PyMethodDef UMath_TestsMethods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_umath_tests", @@ -598,27 +597,16 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif /* Initialization function for the module */ -#if defined(NPY_PY3K) -#define RETVAL(x) x PyMODINIT_FUNC PyInit__umath_tests(void) { -#else -#define RETVAL(x) -PyMODINIT_FUNC init_umath_tests(void) { -#endif PyObject *m; PyObject *d; PyObject *version; -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule("_umath_tests", UMath_TestsMethods); -#endif if (m == NULL) { - return RETVAL(NULL); + return NULL; } import_array(); @@ -636,8 +624,8 @@ PyMODINIT_FUNC init_umath_tests(void) { PyErr_Print(); PyErr_SetString(PyExc_RuntimeError, "cannot load _umath_tests module."); - return RETVAL(NULL); + return NULL; } - return RETVAL(m); + return m; } diff --git a/numpy/core/src/umath/reduction.h b/numpy/core/src/umath/reduction.h index dfaeabcbb..0c2183ed6 100644 --- a/numpy/core/src/umath/reduction.h +++ b/numpy/core/src/umath/reduction.h @@ -100,8 +100,8 @@ typedef int (PyArray_AssignReduceIdentityFunc)(PyArrayObject *result, */ typedef int (PyArray_ReduceLoopFunc)(NpyIter *iter, char **dataptr, - npy_intp *strideptr, - npy_intp *countptr, + npy_intp const *strideptr, + npy_intp const *countptr, NpyIter_IterNextFunc *iternext, int needs_api, npy_intp skip_first_count, diff --git a/numpy/core/src/umath/ufunc_object.c b/numpy/core/src/umath/ufunc_object.c index 1dc581977..9ef0f822b 100644 --- a/numpy/core/src/umath/ufunc_object.c +++ b/numpy/core/src/umath/ufunc_object.c @@ -929,22 +929,9 @@ parse_ufunc_keywords(PyUFuncObject *ufunc, PyObject *kwds, PyObject **kwnames, . } } else { -#if PY_VERSION_HEX >= 0x03000000 PyErr_Format(PyExc_TypeError, "'%S' is an invalid keyword to ufunc '%s'", key, ufunc_get_name_cstr(ufunc)); -#else - char *str = PyString_AsString(key); - if (str == NULL) { - PyErr_Clear(); - PyErr_SetString(PyExc_TypeError, "invalid keyword argument"); - } - else { - PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword to ufunc '%s'", - str, ufunc_get_name_cstr(ufunc)); - } -#endif return -1; } } @@ -3437,8 +3424,8 @@ reduce_type_resolver(PyUFuncObject *ufunc, PyArrayObject *arr, } static int -reduce_loop(NpyIter *iter, char **dataptrs, npy_intp *strides, - npy_intp *countptr, NpyIter_IterNextFunc *iternext, +reduce_loop(NpyIter *iter, char **dataptrs, npy_intp const *strides, + npy_intp const *countptr, NpyIter_IterNextFunc *iternext, int needs_api, npy_intp skip_first_count, void *data) { PyArray_Descr *dtypes[3], **iter_dtypes; @@ -3515,7 +3502,11 @@ reduce_loop(NpyIter *iter, char **dataptrs, npy_intp *strides, strides_copy[2] = strides[0]; if (!masked) { - innerloop(dataptrs_copy, countptr, + /* gh-15252: The signature of the inner loop considers `countptr` + * mutable. Inner loops aren't actually allowed to modify this + * though, so it's fine to cast it. + */ + innerloop(dataptrs_copy, (npy_intp *)countptr, strides_copy, innerloopdata); } else { @@ -5068,21 +5059,12 @@ _free_loop1d_list(PyUFunc_Loop1d *data) } } -#if PY_VERSION_HEX >= 0x03000000 static void _loop1d_list_free(PyObject *ptr) { PyUFunc_Loop1d *data = (PyUFunc_Loop1d *)PyCapsule_GetPointer(ptr, NULL); _free_loop1d_list(data); } -#else -static void -_loop1d_list_free(void *ptr) -{ - PyUFunc_Loop1d *data = (PyUFunc_Loop1d *)ptr; - _free_loop1d_list(data); -} -#endif /* diff --git a/numpy/core/tests/_locales.py b/numpy/core/tests/_locales.py index 52e4ff36d..ce7b81f00 100644 --- a/numpy/core/tests/_locales.py +++ b/numpy/core/tests/_locales.py @@ -1,8 +1,6 @@ """Provide class for testing in French locale """ -from __future__ import division, absolute_import, print_function - import sys import locale @@ -45,7 +43,7 @@ def find_comma_decimal_point_locale(): return old_locale, new_locale -class CommaDecimalPointLocale(object): +class CommaDecimalPointLocale: """Sets LC_NUMERIC to a locale with comma as decimal point. Classes derived from this class have setup and teardown methods that run diff --git a/numpy/core/tests/test_abc.py b/numpy/core/tests/test_abc.py index d9c61b0c6..30e5748af 100644 --- a/numpy/core/tests/test_abc.py +++ b/numpy/core/tests/test_abc.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.testing import assert_ import numbers @@ -7,7 +5,7 @@ import numbers import numpy as np from numpy.core.numerictypes import sctypes -class TestABC(object): +class TestABC: def test_abstract(self): assert_(issubclass(np.number, numbers.Number)) diff --git a/numpy/core/tests/test_api.py b/numpy/core/tests/test_api.py index 89fc2b0b9..3f0a59eec 100644 --- a/numpy/core/tests/test_api.py +++ b/numpy/core/tests/test_api.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import numpy as np diff --git a/numpy/core/tests/test_arrayprint.py b/numpy/core/tests/test_arrayprint.py index 702e68e76..eac4647c9 100644 --- a/numpy/core/tests/test_arrayprint.py +++ b/numpy/core/tests/test_arrayprint.py @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import division, absolute_import, print_function - import sys import gc import pytest @@ -12,7 +10,7 @@ from numpy.testing import ( ) import textwrap -class TestArrayRepr(object): +class TestArrayRepr: def test_nan_inf(self): x = np.array([np.nan, np.inf]) assert_equal(repr(x), 'array([nan, inf])') @@ -160,7 +158,7 @@ class TestArrayRepr(object): assert_equal(repr(arr_no_fields), 'array([(), (), (), ()], dtype=[])') -class TestComplexArray(object): +class TestComplexArray: def test_str(self): rvals = [0, 1, -1, np.inf, -np.inf, np.nan] cvals = [complex(rp, ip) for rp in rvals for ip in rvals] @@ -207,7 +205,7 @@ class TestComplexArray(object): for res, val in zip(actual, wanted): assert_equal(res, val) -class TestArray2String(object): +class TestArray2String: def test_basic(self): """Basic test of array2string.""" a = np.arange(3) @@ -413,7 +411,7 @@ class TestArray2String(object): gc.enable() assert_(r1 == r2) -class TestPrintOptions(object): +class TestPrintOptions: """Test getting and setting global print options.""" def setup(self): @@ -856,7 +854,7 @@ def test_unicode_object_array(): assert_equal(repr(x), expected) -class TestContextManager(object): +class TestContextManager: def test_ctx_mgr(self): # test that context manager actuall works with np.printoptions(precision=2): diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py index d38444ef7..438d52f97 100644 --- a/numpy/core/tests/test_datetime.py +++ b/numpy/core/tests/test_datetime.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy import numpy as np @@ -24,7 +22,7 @@ except NameError: RecursionError = RuntimeError # python < 3.5 -class TestDateTime(object): +class TestDateTime: def test_datetime_dtype_creation(self): for unit in ['Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', @@ -2368,7 +2366,7 @@ class TestDateTime(object): assert limit_via_str == limit -class TestDateTimeData(object): +class TestDateTimeData: def test_basic(self): a = np.array(['1980-03-23'], dtype=np.datetime64) diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index 7b0e6f8a4..d2a1e86d2 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import numpy as np @@ -12,7 +10,7 @@ from numpy.testing import ( kw_unicode_true = {'unicode': True} # make 2to3 work properly kw_unicode_false = {'unicode': False} -class TestBasic(object): +class TestBasic: def test_from_object_array(self): A = np.array([['abc', 2], ['long ', '0123456789']], dtype='O') @@ -83,7 +81,7 @@ class TestBasic(object): assert_equal(A.itemsize, 4) assert_(issubclass(A.dtype.type, np.unicode_)) -class TestVecString(object): +class TestVecString: def test_non_existent_method(self): def fail(): @@ -134,7 +132,7 @@ class TestVecString(object): assert_raises(ValueError, fail) -class TestWhitespace(object): +class TestWhitespace: def setup(self): self.A = np.array([['abc ', '123 '], ['789 ', 'xyz ']]).view(np.chararray) @@ -149,7 +147,7 @@ class TestWhitespace(object): assert_(not np.any(self.A < self.B)) assert_(not np.any(self.A != self.B)) -class TestChar(object): +class TestChar: def setup(self): self.A = np.array('abc1', dtype='c').view(np.chararray) @@ -157,7 +155,7 @@ class TestChar(object): assert_equal(self.A.shape, (4,)) assert_equal(self.A.upper()[:2].tobytes(), b'AB') -class TestComparisons(object): +class TestComparisons: def setup(self): self.A = np.array([['abc', '123'], ['789', 'xyz']]).view(np.chararray) @@ -198,7 +196,7 @@ class TestComparisonsMixed2(TestComparisons): self.A = np.array([['abc', '123'], ['789', 'xyz']], np.unicode_).view(np.chararray) -class TestInformation(object): +class TestInformation: def setup(self): self.A = np.array([[' abc ', ''], ['12345', 'MixedCase'], @@ -304,7 +302,7 @@ class TestInformation(object): assert_raises(TypeError, fail) -class TestMethods(object): +class TestMethods: def setup(self): self.A = np.array([[' abc ', ''], ['12345', 'MixedCase'], @@ -599,7 +597,7 @@ class TestMethods(object): [False, False], [True, False], [False, False]]) -class TestOperations(object): +class TestOperations: def setup(self): self.A = np.array([['abc', '123'], ['789', 'xyz']]).view(np.chararray) diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index 363ff26db..7232b5949 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -3,8 +3,6 @@ Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ -from __future__ import division, absolute_import, print_function - import datetime import sys import operator @@ -27,7 +25,7 @@ except ImportError: _has_pytz = False -class _DeprecationTestCase(object): +class _DeprecationTestCase: # Just as warning: warnings uses re.match, so the start of this message # must match. message = '' @@ -137,7 +135,7 @@ class _VisibleDeprecationTestCase(_DeprecationTestCase): warning_cls = np.VisibleDeprecationWarning -class TestNonTupleNDIndexDeprecation(object): +class TestNonTupleNDIndexDeprecation: def test_basic(self): a = np.zeros((5, 5)) with warnings.catch_warnings(): @@ -189,7 +187,7 @@ class TestComparisonDeprecations(_DeprecationTestCase): assert_warns(FutureWarning, lambda: a == []) def test_void_dtype_equality_failures(self): - class NotArray(object): + class NotArray: def __array__(self): raise TypeError @@ -342,7 +340,7 @@ class TestNumericStyleTypecodes(_DeprecationTestCase): args=(dt,)) -class TestTestDeprecated(object): +class TestTestDeprecated: def test_assert_deprecated(self): test_case_instance = _DeprecationTestCase() test_case_instance.setup() diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index b347a9de7..1d24d8a3d 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import operator import pytest @@ -23,7 +21,7 @@ def assert_dtype_not_equal(a, b): assert_(hash(a) != hash(b), "two different types hash to the same value !") -class TestBuiltin(object): +class TestBuiltin: @pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object, np.compat.unicode]) def test_run(self, t): @@ -146,7 +144,7 @@ class TestBuiltin(object): 'offsets': [4, 0]}) assert_equal(x == y, False) -class TestRecord(object): +class TestRecord: def test_equivalent_record(self): """Test whether equivalent record dtypes hash the same.""" a = np.dtype([('yo', int)]) @@ -445,7 +443,7 @@ class TestRecord(object): np.ones((1, 2), dtype=bool)) -class TestSubarray(object): +class TestSubarray: def test_single_subarray(self): a = np.dtype((int, (2))) b = np.dtype((int, (2,))) @@ -521,7 +519,7 @@ class TestSubarray(object): assert_(isinstance(dt['a'].shape, tuple)) # - class IntLike(object): + class IntLike: def __index__(self): return 3 @@ -711,7 +709,7 @@ class TestStructuredObjectRefcounting: assert after_repeat - after == count * 2 * 10 -class TestStructuredDtypeSparseFields(object): +class TestStructuredDtypeSparseFields: """Tests subarray fields which contain sparse dtypes so that not all memory is used by the dtype work. Such dtype's should leave the underlying memory unchanged. @@ -741,7 +739,7 @@ class TestStructuredDtypeSparseFields(object): assert_array_equal(arr["a"]["aa"], np.zeros((3, 2, 3))) -class TestMonsterType(object): +class TestMonsterType: """Test deeply nested subtypes.""" def test1(self): @@ -759,7 +757,7 @@ class TestMonsterType(object): ('yi', np.dtype((a, (3, 2))))]) assert_dtype_equal(c, d) -class TestMetadata(object): +class TestMetadata: def test_no_metadata(self): d = np.dtype(int) assert_(d.metadata is None) @@ -781,7 +779,7 @@ class TestMetadata(object): d = np.dtype((np.void, np.dtype('i4,i4', metadata={'datum': 1}))) assert_(d.metadata == {'datum': 1}) -class TestString(object): +class TestString: def test_complex_dtype_str(self): dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), ('rtile', '>f4', (64, 36))], (3,)), @@ -934,7 +932,7 @@ class TestString(object): assert_equal(dt.name, 'record16') -class TestDtypeAttributeDeletion(object): +class TestDtypeAttributeDeletion: def test_dtype_non_writable_attributes_deletion(self): dt = np.dtype(np.double) @@ -952,7 +950,7 @@ class TestDtypeAttributeDeletion(object): assert_raises(AttributeError, delattr, dt, s) -class TestDtypeAttributes(object): +class TestDtypeAttributes: def test_descr_has_trailing_void(self): # see gh-6359 dtype = np.dtype({ @@ -970,7 +968,7 @@ class TestDtypeAttributes(object): assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls') -class TestPickling(object): +class TestPickling: def check_pickling(self, dtype): for proto in range(pickle.HIGHEST_PROTOCOL + 1): @@ -1054,7 +1052,7 @@ def test_invalid_dtype_string(): assert_raises(TypeError, np.dtype, u'Fl\xfcgel') -class TestFromDTypeAttribute(object): +class TestFromDTypeAttribute: def test_simple(self): class dt: dtype = "f8" @@ -1098,7 +1096,7 @@ class TestFromDTypeAttribute(object): with pytest.raises(RecursionError): np.dtype(dt(1)) -class TestFromCTypes(object): +class TestFromCTypes: @staticmethod def check(ctype, dtype): diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py index 1b5b4cb26..6ec61fb1d 100644 --- a/numpy/core/tests/test_einsum.py +++ b/numpy/core/tests/test_einsum.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import itertools import numpy as np @@ -14,7 +12,7 @@ sizes = np.array([2, 3, 4, 5, 4, 3, 2, 6, 5, 4, 3]) global_size_dict = dict(zip(chars, sizes)) -class TestEinsum(object): +class TestEinsum: def test_einsum_errors(self): for do_opt in [True, False]: # Need enough arguments @@ -868,7 +866,7 @@ class TestEinsum(object): self.optimize_compare('obk,ijk->ioj', operands=[g, g]) -class TestEinsumPath(object): +class TestEinsumPath: def build_operands(self, string, size_dict=global_size_dict): # Builds views based off initial operands diff --git a/numpy/core/tests/test_errstate.py b/numpy/core/tests/test_errstate.py index 0008c4cc8..7c1780607 100644 --- a/numpy/core/tests/test_errstate.py +++ b/numpy/core/tests/test_errstate.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import platform import pytest @@ -7,7 +5,7 @@ import numpy as np from numpy.testing import assert_, assert_raises -class TestErrstate(object): +class TestErrstate: @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.") def test_invalid(self): with np.errstate(all='raise', under='ignore'): diff --git a/numpy/core/tests/test_extint128.py b/numpy/core/tests/test_extint128.py index 7c454a603..3b64915f3 100644 --- a/numpy/core/tests/test_extint128.py +++ b/numpy/core/tests/test_extint128.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import itertools import contextlib import operator diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py index c8a7cb6ce..7e5ea1cc6 100644 --- a/numpy/core/tests/test_function_base.py +++ b/numpy/core/tests/test_function_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy import ( logspace, linspace, geomspace, dtype, array, sctypes, arange, isnan, ndarray, sqrt, nextafter, stack @@ -42,7 +40,7 @@ class PhysicalQuantity2(ndarray): __array_priority__ = 10 -class TestLogspace(object): +class TestLogspace: def test_basic(self): y = logspace(0, 6) @@ -92,7 +90,7 @@ class TestLogspace(object): assert_equal(ls, logspace(1.0, 7.0, 1)) -class TestGeomspace(object): +class TestGeomspace: def test_basic(self): y = geomspace(1, 1e6) @@ -222,7 +220,7 @@ class TestGeomspace(object): assert_raises(ValueError, geomspace, 0, 0) -class TestLinspace(object): +class TestLinspace: def test_basic(self): y = linspace(0, 10) @@ -309,7 +307,7 @@ class TestLinspace(object): # Ensure that start/stop can be objects that implement # __array_interface__ and are convertible to numeric scalars - class Arrayish(object): + class Arrayish: """ A generic object that supports the __array_interface__ and hence can in principle be converted to a numeric scalar, but is not diff --git a/numpy/core/tests/test_getlimits.py b/numpy/core/tests/test_getlimits.py index 2f6648183..bcf8cf659 100644 --- a/numpy/core/tests/test_getlimits.py +++ b/numpy/core/tests/test_getlimits.py @@ -1,8 +1,6 @@ """ Test functions for limits module. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.core import finfo, iinfo from numpy import half, single, double, longdouble @@ -11,37 +9,37 @@ from numpy.core.getlimits import _discovered_machar, _float_ma ################################################## -class TestPythonFloat(object): +class TestPythonFloat: def test_singleton(self): ftype = finfo(float) ftype2 = finfo(float) assert_equal(id(ftype), id(ftype2)) -class TestHalf(object): +class TestHalf: def test_singleton(self): ftype = finfo(half) ftype2 = finfo(half) assert_equal(id(ftype), id(ftype2)) -class TestSingle(object): +class TestSingle: def test_singleton(self): ftype = finfo(single) ftype2 = finfo(single) assert_equal(id(ftype), id(ftype2)) -class TestDouble(object): +class TestDouble: def test_singleton(self): ftype = finfo(double) ftype2 = finfo(double) assert_equal(id(ftype), id(ftype2)) -class TestLongdouble(object): +class TestLongdouble: def test_singleton(self): ftype = finfo(longdouble) ftype2 = finfo(longdouble) assert_equal(id(ftype), id(ftype2)) -class TestFinfo(object): +class TestFinfo: def test_basic(self): dts = list(zip(['f2', 'f4', 'f8', 'c8', 'c16'], [np.float16, np.float32, np.float64, np.complex64, @@ -54,7 +52,7 @@ class TestFinfo(object): getattr(finfo(dt2), attr), attr) assert_raises(ValueError, finfo, 'i4') -class TestIinfo(object): +class TestIinfo: def test_basic(self): dts = list(zip(['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'], @@ -71,7 +69,7 @@ class TestIinfo(object): for T in types: assert_equal(iinfo(T).max, T(-1)) -class TestRepr(object): +class TestRepr: def test_iinfo_repr(self): expected = "iinfo(min=-32768, max=32767, dtype=int16)" assert_equal(repr(np.iinfo(np.int16)), expected) diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py index 1e1e6d7d9..c6d046be1 100644 --- a/numpy/core/tests/test_half.py +++ b/numpy/core/tests/test_half.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import platform import pytest @@ -18,7 +16,7 @@ def assert_raises_fpe(strmatch, callable, *args, **kwargs): assert_(False, "Did not raise floating point %s error" % strmatch) -class TestHalf(object): +class TestHalf: def setup(self): # An array of all possible float16 values self.all_f16 = np.arange(0x10000, dtype=uint16) diff --git a/numpy/core/tests/test_indexerrors.py b/numpy/core/tests/test_indexerrors.py index 63b43c473..9d2433fc5 100644 --- a/numpy/core/tests/test_indexerrors.py +++ b/numpy/core/tests/test_indexerrors.py @@ -1,9 +1,7 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_raises -class TestIndexErrors(object): +class TestIndexErrors: '''Tests to exercise indexerrors not covered by other tests.''' def test_arraytypes_fasttake(self): diff --git a/numpy/core/tests/test_indexing.py b/numpy/core/tests/test_indexing.py index 70a5a246f..56bcf0177 100644 --- a/numpy/core/tests/test_indexing.py +++ b/numpy/core/tests/test_indexing.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import warnings import functools @@ -11,11 +9,11 @@ from numpy.core._multiarray_tests import array_indexing from itertools import product from numpy.testing import ( assert_, assert_equal, assert_raises, assert_array_equal, assert_warns, - HAS_REFCOUNT, suppress_warnings, + HAS_REFCOUNT, ) -class TestIndexing(object): +class TestIndexing: def test_index_no_floats(self): a = np.array([[[5]]]) @@ -397,14 +395,14 @@ class TestIndexing(object): def test_scalar_return_type(self): # Full scalar indices should return scalars and object # arrays should not call PyArray_Return on their items - class Zero(object): + class Zero: # The most basic valid indexing def __index__(self): return 0 z = Zero() - class ArrayLike(object): + class ArrayLike: # Simple array, should behave like the array def __array__(self): return np.array(0) @@ -484,7 +482,7 @@ class TestIndexing(object): # on item getting, this should not be converted to an nd-index (tuple) # If this object happens to be a valid index otherwise, it should work # This object here is very dubious and probably bad though: - class SequenceLike(object): + class SequenceLike: def __index__(self): return 0 @@ -527,7 +525,7 @@ class TestIndexing(object): arr[slices] = 10 assert_array_equal(arr, 10.) -class TestFieldIndexing(object): +class TestFieldIndexing: def test_scalar_return_type(self): # Field access on an array should return an array, even if it # is 0-d. @@ -536,7 +534,7 @@ class TestFieldIndexing(object): assert_(isinstance(a[['a']], np.ndarray)) -class TestBroadcastedAssignments(object): +class TestBroadcastedAssignments: def assign(self, a, ind, val): a[ind] = val return a @@ -587,7 +585,7 @@ class TestBroadcastedAssignments(object): assert_((a[::-1] == v).all()) -class TestSubclasses(object): +class TestSubclasses: def test_basic(self): # Test that indexing in various ways produces SubClass instances, # and that the base is set up correctly: the original subclass @@ -671,35 +669,21 @@ class TestSubclasses(object): k[0:5] assert_equal(k.indx, slice(0, 5)) assert_equal(sys.getrefcount(k.indx), 2) - try: + with assert_raises(ValueError): k[0:7] - raise AssertionError - except ValueError: - # The exception holds a reference to the slice so clear on Py2 - if hasattr(sys, 'exc_clear'): - with suppress_warnings() as sup: - sup.filter(DeprecationWarning) - sys.exc_clear() assert_equal(k.indx, slice(0, 7)) assert_equal(sys.getrefcount(k.indx), 2) k[0:3] = 6 assert_equal(k.indx, slice(0, 3)) assert_equal(sys.getrefcount(k.indx), 2) - try: + with assert_raises(ValueError): k[0:4] = 2 - raise AssertionError - except ValueError: - # The exception holds a reference to the slice so clear on Py2 - if hasattr(sys, 'exc_clear'): - with suppress_warnings() as sup: - sup.filter(DeprecationWarning) - sys.exc_clear() assert_equal(k.indx, slice(0, 4)) assert_equal(sys.getrefcount(k.indx), 2) -class TestFancyIndexingCast(object): +class TestFancyIndexingCast: def test_boolean_index_cast_assign(self): # Setup the boolean index and float arrays. shape = (8, 63) @@ -721,7 +705,7 @@ class TestFancyIndexingCast(object): zero_array.__setitem__, bool_index, np.array([1j])) assert_equal(zero_array[0, 1], 0) -class TestFancyIndexingEquivalence(object): +class TestFancyIndexingEquivalence: def test_object_assign(self): # Check that the field and object special case using copyto is active. # The right hand side cannot be converted to an array here. @@ -769,7 +753,7 @@ class TestFancyIndexingEquivalence(object): assert_array_equal(a, b[0]) -class TestMultiIndexingAutomated(object): +class TestMultiIndexingAutomated: """ These tests use code to mimic the C-Code indexing for selection. @@ -1191,7 +1175,7 @@ class TestMultiIndexingAutomated(object): for index in self.complex_indices: self._check_single_index(a, index) -class TestFloatNonIntegerArgument(object): +class TestFloatNonIntegerArgument: """ These test that ``TypeError`` is raised when you try to use non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]`` @@ -1246,7 +1230,7 @@ class TestFloatNonIntegerArgument(object): assert_raises(TypeError, np.min, d, (.2, 1.2)) -class TestBooleanIndexing(object): +class TestBooleanIndexing: # Using a boolean as integer argument/indexing is an error. def test_bool_as_int_argument_errors(self): a = np.array([[[1]]]) @@ -1267,7 +1251,7 @@ class TestBooleanIndexing(object): assert_raises(IndexError, lambda: a[False, [0, 1], ...]) -class TestArrayToIndexDeprecation(object): +class TestArrayToIndexDeprecation: """Creating an an index from array not 0-D is an error. """ @@ -1280,7 +1264,7 @@ class TestArrayToIndexDeprecation(object): assert_raises(TypeError, np.take, a, [0], a) -class TestNonIntegerArrayLike(object): +class TestNonIntegerArrayLike: """Tests that array_likes only valid if can safely cast to integer. For instance, lists give IndexError when they cannot be safely cast to @@ -1297,7 +1281,7 @@ class TestNonIntegerArrayLike(object): a.__getitem__([]) -class TestMultipleEllipsisError(object): +class TestMultipleEllipsisError: """An index can only have a single ellipsis. """ @@ -1308,7 +1292,7 @@ class TestMultipleEllipsisError(object): assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,)) -class TestCApiAccess(object): +class TestCApiAccess: def test_getitem(self): subscript = functools.partial(array_indexing, 0) diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py index 9bd246866..cadd0d513 100644 --- a/numpy/core/tests/test_item_selection.py +++ b/numpy/core/tests/test_item_selection.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import numpy as np @@ -8,7 +6,7 @@ from numpy.testing import ( ) -class TestTake(object): +class TestTake: def test_simple(self): a = [[1, 2], [3, 4]] a_str = [[b'1', b'2'], [b'3', b'4']] diff --git a/numpy/core/tests/test_longdouble.py b/numpy/core/tests/test_longdouble.py index 2b6e1c5a2..bf12f0e1b 100644 --- a/numpy/core/tests/test_longdouble.py +++ b/numpy/core/tests/test_longdouble.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import warnings import pytest @@ -121,7 +119,7 @@ def test_fromstring_missing(): np.array([1])) -class TestFileBased(object): +class TestFileBased: ldbl = 1 + LD_INFO.eps tgt = np.array([ldbl]*5) diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py index 64a0ffa3d..673f309f1 100644 --- a/numpy/core/tests/test_machar.py +++ b/numpy/core/tests/test_machar.py @@ -3,14 +3,12 @@ Test machar. Given recent changes to hardcode type data, we might want to get rid of both MachAr and this test at some point. """ -from __future__ import division, absolute_import, print_function - from numpy.core.machar import MachAr import numpy.core.numerictypes as ntypes from numpy import errstate, array -class TestMachAr(object): +class TestMachAr: def _run_machar_highprec(self): # Instantiate MachAr instance with high enough precision to cause # underflow diff --git a/numpy/core/tests/test_mem_overlap.py b/numpy/core/tests/test_mem_overlap.py index 3c8e0e722..c5115fa7e 100644 --- a/numpy/core/tests/test_mem_overlap.py +++ b/numpy/core/tests/test_mem_overlap.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import itertools import pytest @@ -564,7 +562,7 @@ def test_internal_overlap_fuzz(): def test_non_ndarray_inputs(): # Regression check for gh-5604 - class MyArray(object): + class MyArray: def __init__(self, data): self.data = data @@ -572,7 +570,7 @@ def test_non_ndarray_inputs(): def __array_interface__(self): return self.data.__array_interface__ - class MyArray2(object): + class MyArray2: def __init__(self, data): self.data = data @@ -619,7 +617,7 @@ def assert_copy_equivalent(operation, args, out, **kwargs): assert_equal(got, expected) -class TestUFunc(object): +class TestUFunc: """ Test ufunc call memory overlap handling """ diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index d2ae564b2..bae7a318a 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import os import shutil @@ -16,7 +14,7 @@ from numpy.testing import ( assert_, assert_equal, assert_array_equal, suppress_warnings ) -class TestMemmap(object): +class TestMemmap: def setup(self): self.tmpfp = NamedTemporaryFile(prefix='mmap') self.tempdir = mkdtemp() diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index d801dbf91..bf1fcc76e 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - try: # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 @@ -20,7 +18,6 @@ import gc import weakref import pytest from contextlib import contextmanager -from test.support import no_tracing from numpy.compat import pickle @@ -97,8 +94,28 @@ def _aligned_zeros(shape, dtype=float, order="C", align=None): data.fill(0) return data +def _no_tracing(func): + """ + Decorator to temporarily turn off tracing for the duration of a test. + Needed in tests that check refcounting, otherwise the tracing itself + influences the refcounts + """ + if not hasattr(sys, 'gettrace'): + return func + else: + @functools.wraps(func) + def wrapper(*args, **kwargs): + original_trace = sys.gettrace() + try: + sys.settrace(None) + return func(*args, **kwargs) + finally: + sys.settrace(original_trace) + return wrapper + + -class TestFlags(object): +class TestFlags: def setup(self): self.a = np.arange(10) @@ -266,7 +283,7 @@ class TestFlags(object): assert_(a.flags.aligned) -class TestHash(object): +class TestHash: # see #3793 def test_int(self): for st, ut, s in [(np.int8, np.uint8, 8), @@ -288,7 +305,7 @@ class TestHash(object): err_msg="%r: 2**%d - 1" % (ut, i)) -class TestAttributes(object): +class TestAttributes: def setup(self): self.one = np.arange(10) self.two = np.arange(20).reshape(4, 5) @@ -421,7 +438,7 @@ class TestAttributes(object): assert_array_equal(x['b'], [-2, -2]) -class TestArrayConstruction(object): +class TestArrayConstruction: def test_array(self): d = np.ones(6) r = np.array([d, d]) @@ -499,7 +516,7 @@ class TestArrayConstruction(object): assert_(np.asfortranarray(d).flags.f_contiguous) -class TestAssignment(object): +class TestAssignment: def test_assignment_broadcasting(self): a = np.arange(6).reshape(2, 3) @@ -565,7 +582,7 @@ class TestAssignment(object): u = np.array([u'done']) b = np.array([b'done']) - class bad_sequence(object): + class bad_sequence: def __getitem__(self): pass def __len__(self): raise RuntimeError @@ -616,7 +633,7 @@ class TestAssignment(object): assert_equal(a[0], b"1.1234567890123457") -class TestDtypedescr(object): +class TestDtypedescr: def test_construction(self): d1 = np.dtype('i4') assert_equal(d1, np.dtype(np.int32)) @@ -638,7 +655,7 @@ class TestDtypedescr(object): "array([0, 0, 0, 0], dtype=(numpy.int32, [('a', '<i2'), ('b', '<i2')]))") -class TestZeroRank(object): +class TestZeroRank: def setup(self): self.d = np.array(0), np.array('x', object) @@ -736,7 +753,7 @@ class TestZeroRank(object): assert_equal(xi.flags.f_contiguous, True) -class TestScalarIndexing(object): +class TestScalarIndexing: def setup(self): self.d = np.array([0, 1])[0] @@ -832,12 +849,12 @@ class TestScalarIndexing(object): assert_equal(a, [0, 1, 0, 1, 2]) -class TestCreation(object): +class TestCreation: """ Test the np.array constructor """ def test_from_attribute(self): - class x(object): + class x: def __array__(self, dtype=None): pass @@ -979,14 +996,14 @@ class TestCreation(object): of an error in the Fail case. """ - class Fail(object): + class Fail: def __len__(self): return 1 def __getitem__(self, index): raise ValueError() - class Map(object): + class Map: def __len__(self): return 1 @@ -1024,7 +1041,7 @@ class TestCreation(object): def test_failed_len_sequence(self): # gh-7393 - class A(object): + class A: def __init__(self, data): self._data = data def __getitem__(self, item): @@ -1080,7 +1097,7 @@ class TestCreation(object): assert_equal(a.dtype, object) -class TestStructured(object): +class TestStructured: def test_subarray_field_access(self): a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))]) a['a'] = np.arange(60).reshape(3, 5, 2, 2) @@ -1368,7 +1385,7 @@ class TestStructured(object): a[['b','c']] # no exception -class TestBool(object): +class TestBool: def test_test_interning(self): a0 = np.bool_(0) b0 = np.bool_(False) @@ -1458,7 +1475,7 @@ class TestBool(object): self._test_cast_from_flexible(np.bytes_) -class TestZeroSizeFlexible(object): +class TestZeroSizeFlexible: @staticmethod def _zeros(shape, dtype=str): dtype = np.dtype(dtype) @@ -1545,7 +1562,7 @@ class TestZeroSizeFlexible(object): assert array_from_buffer[0] == -1, array_from_buffer[0] -class TestMethods(object): +class TestMethods: sort_kinds = ['quicksort', 'heapsort', 'stable'] @@ -1872,7 +1889,7 @@ class TestMethods(object): # test generic class with bogus ordering, # should not segfault. - class Boom(object): + class Boom: def __lt__(self, other): return True @@ -1900,7 +1917,7 @@ class TestMethods(object): for kind in self.sort_kinds: assert_raises(TypeError, arr.sort, kind=kind) #gh-3879 - class Raiser(object): + class Raiser: def raises_anything(*args, **kwargs): raise TypeError("SOMETHING ERRORED") __eq__ = __ne__ = __lt__ = __gt__ = __ge__ = __le__ = raises_anything @@ -2144,6 +2161,8 @@ class TestMethods(object): msg = "Test real searchsorted with nans, side='r'" b = a.searchsorted(a, side='r') assert_equal(b, np.arange(1, 4), msg) + # check keyword arguments + a.searchsorted(v=1) # check double complex a = np.zeros(9, dtype=np.complex128) a.real += [0, 0, 1, 1, 0, 1, np.nan, np.nan, np.nan] @@ -2942,7 +2961,7 @@ class TestMethods(object): def test_dot_matmul_inner_array_casting_fails(self): - class A(object): + class A: def __array__(self, *args, **kwargs): raise NotImplementedError @@ -3303,12 +3322,12 @@ class TestMethods(object): e = np.array(['1+1j'], 'U') assert_raises(TypeError, complex, e) -class TestCequenceMethods(object): +class TestCequenceMethods: def test_array_contains(self): assert_(4.0 in np.arange(16.).reshape(4,4)) assert_(20.0 not in np.arange(16.).reshape(4,4)) -class TestBinop(object): +class TestBinop: def test_inplace(self): # test refcount 1 inplace conversion assert_array_almost_equal(np.array([0.5]) * np.array([1.0, 2.0]), @@ -3533,7 +3552,7 @@ class TestBinop(object): def test_ufunc_override_normalize_signature(self): # gh-5674 - class SomeClass(object): + class SomeClass: def __array_ufunc__(self, ufunc, method, *inputs, **kw): return kw @@ -3551,7 +3570,7 @@ class TestBinop(object): # Check that index is set appropriately, also if only an output # is passed on (latter is another regression tests for github bug 4753) # This also checks implicitly that 'out' is always a tuple. - class CheckIndex(object): + class CheckIndex: def __array_ufunc__(self, ufunc, method, *inputs, **kw): for i, a in enumerate(inputs): if a is self: @@ -3639,7 +3658,7 @@ class TestBinop(object): def test_pow_array_object_dtype(self): # test pow on arrays of object dtype - class SomeClass(object): + class SomeClass: def __init__(self, num=None): self.num = num @@ -3680,7 +3699,7 @@ class TestBinop(object): +tst -class TestTemporaryElide(object): +class TestTemporaryElide: # elision is only triggered on relatively large arrays def test_extension_incref_elide(self): @@ -3782,7 +3801,7 @@ class TestTemporaryElide(object): assert_equal(a, 1) -class TestCAPI(object): +class TestCAPI: def test_IsPythonScalar(self): from numpy.core._multiarray_tests import IsPythonScalar assert_(IsPythonScalar(b'foobar')) @@ -3792,7 +3811,7 @@ class TestCAPI(object): assert_(IsPythonScalar("a")) -class TestSubscripting(object): +class TestSubscripting: def test_test_zero_rank(self): x = np.array([1, 2, 3]) assert_(isinstance(x[0], np.int_)) @@ -3801,7 +3820,7 @@ class TestSubscripting(object): assert_(type(x[0, ...]) is np.ndarray) -class TestPickling(object): +class TestPickling: @pytest.mark.skipif(pickle.HIGHEST_PROTOCOL >= 5, reason=('this tests the error messages when trying to' 'protocol 5 although it is not available')) @@ -3958,7 +3977,7 @@ class TestPickling(object): assert_equal(original.dtype, new.dtype) -class TestFancyIndexing(object): +class TestFancyIndexing: def test_list(self): x = np.ones((1, 1)) x[:, [0]] = 2.0 @@ -4012,7 +4031,7 @@ class TestFancyIndexing(object): assert_array_equal(x, np.array([[1, 10, 3, 4], [5, 6, 7, 8]])) -class TestStringCompare(object): +class TestStringCompare: def test_string(self): g1 = np.array(["This", "is", "example"]) g2 = np.array(["This", "was", "example"]) @@ -4044,7 +4063,7 @@ class TestStringCompare(object): assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) -class TestArgmax(object): +class TestArgmax: nan_arr = [ ([0, 1, 2, 3, np.nan], 4), @@ -4179,7 +4198,7 @@ class TestArgmax(object): assert_equal(a.argmax(), 1) -class TestArgmin(object): +class TestArgmin: nan_arr = [ ([0, 1, 2, 3, np.nan], 4), @@ -4328,7 +4347,7 @@ class TestArgmin(object): assert_equal(a.argmin(), 1) -class TestMinMax(object): +class TestMinMax: def test_scalar(self): assert_raises(np.AxisError, np.amax, 1, 1) @@ -4354,14 +4373,14 @@ class TestMinMax(object): assert_equal(np.amax(a), a[3]) -class TestNewaxis(object): +class TestNewaxis: def test_basic(self): sk = np.array([0, -0.1, 0.1]) res = 250*sk[:, np.newaxis] assert_almost_equal(res.ravel(), 250*sk) -class TestClip(object): +class TestClip: def _check_range(self, x, cmin, cmax): assert_(np.all(x >= cmin)) assert_(np.all(x <= cmax)) @@ -4439,7 +4458,7 @@ class TestClip(object): assert_array_equal(result, expected) -class TestCompress(object): +class TestCompress: def test_axis(self): tgt = [[5, 6, 7, 8, 9]] arr = np.arange(10).reshape(2, 5) @@ -4462,7 +4481,7 @@ class TestCompress(object): assert_equal(out, 1) -class TestPutmask(object): +class TestPutmask: def tst_basic(self, x, T, mask, val): np.putmask(x, mask, val) assert_equal(x[mask], T(val)) @@ -4513,7 +4532,7 @@ class TestPutmask(object): assert_equal(x, np.array([True, True, True, True])) -class TestTake(object): +class TestTake: def tst_basic(self, x): ind = list(range(x.shape[0])) assert_array_equal(x.take(ind, axis=0), x) @@ -4566,7 +4585,7 @@ class TestTake(object): y = np.take(x, [1, 2, 3], out=x[2:5], mode='wrap') assert_equal(y, np.array([1, 2, 3])) -class TestLexsort(object): +class TestLexsort: @pytest.mark.parametrize('dtype',[ np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64, @@ -4621,7 +4640,7 @@ class TestLexsort(object): x = np.linspace(0., 1., 42*3).reshape(42, 3) assert_raises(np.AxisError, np.lexsort, x, axis=2) -class TestIO(object): +class TestIO: """Test tofile, fromfile, tobytes, and fromstring""" def setup(self): @@ -5011,7 +5030,7 @@ class TestIO(object): assert_array_equal(x, res) -class TestFromBuffer(object): +class TestFromBuffer: @pytest.mark.parametrize('byteorder', ['<', '>']) @pytest.mark.parametrize('dtype', [float, int, complex]) def test_basic(self, byteorder, dtype): @@ -5024,7 +5043,7 @@ class TestFromBuffer(object): assert_array_equal(np.frombuffer(b''), np.array([])) -class TestFlat(object): +class TestFlat: def setup(self): a0 = np.arange(20.0) a = a0.reshape(4, 5) @@ -5096,9 +5115,9 @@ class TestFlat(object): assert_(abs(sys.getrefcount(indtype) - rc_indtype) < 50) -class TestResize(object): +class TestResize: - @no_tracing + @_no_tracing def test_basic(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) if IS_PYPY: @@ -5115,7 +5134,7 @@ class TestResize(object): assert_raises(ValueError, x.resize, (5, 1)) del y # avoid pyflakes unused variable warning. - @no_tracing + @_no_tracing def test_int_shape(self): x = np.eye(3) if IS_PYPY: @@ -5149,7 +5168,7 @@ class TestResize(object): assert_raises(TypeError, np.eye(3).resize, order=1) assert_raises(TypeError, np.eye(3).resize, refcheck='hi') - @no_tracing + @_no_tracing def test_freeform_shape(self): x = np.eye(3) if IS_PYPY: @@ -5158,7 +5177,7 @@ class TestResize(object): x.resize(3, 2, 1) assert_(x.shape == (3, 2, 1)) - @no_tracing + @_no_tracing def test_zeros_appended(self): x = np.eye(3) if IS_PYPY: @@ -5168,7 +5187,7 @@ class TestResize(object): assert_array_equal(x[0], np.eye(3)) assert_array_equal(x[1], np.zeros((3, 3))) - @no_tracing + @_no_tracing def test_obj_obj(self): # check memory is initialized on resize, gh-4857 a = np.ones(10, dtype=[('k', object, 2)]) @@ -5195,7 +5214,7 @@ class TestResize(object): del xref # avoid pyflakes unused variable warning. -class TestRecord(object): +class TestRecord: def test_field_rename(self): dt = np.dtype([('f', float), ('i', int)]) dt.names = ['p', 'q'] @@ -5357,7 +5376,7 @@ class TestRecord(object): v[:] = (4,5) assert_equal(a[0].item(), (4, 1, 5)) -class TestView(object): +class TestView: def test_basic(self): x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype=[('r', np.int8), ('g', np.int8), @@ -5382,7 +5401,7 @@ def _std(a, **args): return a.std(**args) -class TestStats(object): +class TestStats: funcs = [_mean, _var, _std] @@ -5589,7 +5608,7 @@ class TestStats(object): res = dat.var(1) assert_(res.info == dat.info) -class TestVdot(object): +class TestVdot: def test_basic(self): dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger'] dt_complex = np.typecodes['Complex'] @@ -5649,7 +5668,7 @@ class TestVdot(object): np.vdot(a.flatten(), b.flatten())) -class TestDot(object): +class TestDot: def setup(self): np.random.seed(128) self.A = np.random.rand(4, 2) @@ -5751,7 +5770,7 @@ class TestDot(object): assert_almost_equal(res, tgt, decimal=self.N) def test_vecobject(self): - class Vec(object): + class Vec: def __init__(self, sequence=None): if sequence is None: sequence = [] @@ -5920,7 +5939,7 @@ class TestDot(object): assert_dot_close(A_f_12, X_f_2, desired) -class MatmulCommon(object): +class MatmulCommon: """Common tests for '@' operator and numpy.matmul. """ @@ -6302,7 +6321,7 @@ if sys.version_info[:2] >= (3, 5): def test_array_priority_override(self): - class A(object): + class A: __array_priority__ = 1000 def __matmul__(self, other): @@ -6347,7 +6366,7 @@ if sys.version_info[:2] >= (3, 5): assert f.shape == (4, 5) -class TestInner(object): +class TestInner: def test_inner_type_mismatch(self): c = 1. @@ -6425,7 +6444,7 @@ class TestInner(object): assert_equal(np.inner(b, a).transpose(2,3,0,1), desired) -class TestAlen(object): +class TestAlen: def test_basic(self): with pytest.warns(DeprecationWarning): m = np.array([1, 2, 3]) @@ -6445,7 +6464,7 @@ class TestAlen(object): assert_equal(np.alen(5), 1) -class TestChoose(object): +class TestChoose: def setup(self): self.x = 2*np.ones((3,), dtype=int) self.y = 3*np.ones((3,), dtype=int) @@ -6475,7 +6494,7 @@ class TestChoose(object): assert(np.choose([0], ops).dtype == expected_dt) -class TestRepeat(object): +class TestRepeat: def setup(self): self.m = np.array([1, 2, 3, 4, 5, 6]) self.m_rect = self.m.reshape((2, 3)) @@ -6517,7 +6536,7 @@ NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} @pytest.mark.parametrize('dt', [float, Decimal], ids=['float', 'object']) -class TestNeighborhoodIter(object): +class TestNeighborhoodIter: # Simple, 2d tests def test_simple2d(self, dt): # Test zero and one padding for simple data type @@ -6596,7 +6615,7 @@ class TestNeighborhoodIter(object): # Test stacking neighborhood iterators -class TestStackedNeighborhoodIter(object): +class TestStackedNeighborhoodIter: # Simple, 1d test: stacking 2 constant-padded neigh iterators def test_simple_const(self): dt = np.float64 @@ -6746,7 +6765,7 @@ class TestStackedNeighborhoodIter(object): x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) -class TestWarnings(object): +class TestWarnings: def test_complex_warning(self): x = np.array([1, 2]) @@ -6758,7 +6777,7 @@ class TestWarnings(object): assert_equal(x, [1, 2]) -class TestMinScalarType(object): +class TestMinScalarType: def test_usigned_shortshort(self): dt = np.min_scalar_type(2**8-1) @@ -6789,7 +6808,7 @@ class TestMinScalarType(object): from numpy.core._internal import _dtype_from_pep3118 -class TestPEP3118Dtype(object): +class TestPEP3118Dtype: def _check(self, spec, wanted): dt = np.dtype(wanted) actual = _dtype_from_pep3118(spec) @@ -6896,7 +6915,7 @@ class TestPEP3118Dtype(object): self._check('i:f0:', [('f0', 'i')]) -class TestNewBufferProtocol(object): +class TestNewBufferProtocol: """ Test PEP3118 buffers """ def _check_roundtrip(self, obj): @@ -7293,7 +7312,7 @@ class TestNewBufferProtocol(object): assert_equal(arr['a'], 3) -class TestArrayAttributeDeletion(object): +class TestArrayAttributeDeletion: def test_multiarray_writable_attributes_deletion(self): # ticket #2046, should not seqfault, raise AttributeError @@ -7328,7 +7347,7 @@ class TestArrayAttributeDeletion(object): class TestArrayInterface(): - class Foo(object): + class Foo: def __init__(self, value): self.value = value self.iface = {'typestr': 'f8'} @@ -7373,7 +7392,7 @@ class TestArrayInterface(): assert_equal(pre_cnt, post_cnt) def test_interface_no_shape(): - class ArrayLike(object): + class ArrayLike: array = np.array(1) __array_interface__ = array.__array_interface__ assert_equal(np.array(ArrayLike()), 1) @@ -7395,7 +7414,7 @@ def test_array_interface_empty_shape(): interface1 = dict(arr.__array_interface__) interface1['shape'] = () - class DummyArray1(object): + class DummyArray1: __array_interface__ = interface1 # NOTE: Because Py2 str/Py3 bytes supports the buffer interface, setting @@ -7405,7 +7424,7 @@ def test_array_interface_empty_shape(): interface2 = dict(interface1) interface2['data'] = arr[0].tobytes() - class DummyArray2(object): + class DummyArray2: __array_interface__ = interface2 arr1 = np.asarray(DummyArray1()) @@ -7422,7 +7441,7 @@ def test_array_interface_offset(): interface['offset'] = 4 - class DummyArray(object): + class DummyArray: __array_interface__ = interface arr1 = np.asarray(DummyArray()) @@ -7444,7 +7463,7 @@ def test_scalar_element_deletion(): assert_raises(ValueError, a[0].__delitem__, 'x') -class TestMemEventHook(object): +class TestMemEventHook: def test_mem_seteventhook(self): # The actual tests are within the C code in # multiarray/_multiarray_tests.c.src @@ -7456,7 +7475,7 @@ class TestMemEventHook(object): break_cycles() _multiarray_tests.test_pydatamem_seteventhook_end() -class TestMapIter(object): +class TestMapIter: def test_mapiter(self): # The actual tests are within the C code in # multiarray/_multiarray_tests.c.src @@ -7478,7 +7497,7 @@ class TestMapIter(object): assert_equal(b, [100.1, 51., 6., 3., 4., 5.]) -class TestAsCArray(object): +class TestAsCArray: def test_1darray(self): array = np.arange(24, dtype=np.double) from_c = _multiarray_tests.test_as_c_array(array, 3) @@ -7495,7 +7514,7 @@ class TestAsCArray(object): assert_equal(array[1, 2, 3], from_c) -class TestConversion(object): +class TestConversion: def test_array_scalar_relational_operation(self): # All integer for dt1 in np.typecodes['AllInteger']: @@ -7543,7 +7562,7 @@ class TestConversion(object): assert_equal(bool(np.array([[42]])), True) assert_raises(ValueError, bool, np.array([1, 2])) - class NotConvertible(object): + class NotConvertible: def __bool__(self): raise NotImplementedError __nonzero__ = __bool__ # python 2 @@ -7580,7 +7599,7 @@ class TestConversion(object): assert_equal(3, int_func(np.array(HasTrunc()))) assert_equal(3, int_func(np.array([HasTrunc()]))) - class NotConvertible(object): + class NotConvertible: def __int__(self): raise NotImplementedError assert_raises(NotImplementedError, @@ -7589,7 +7608,7 @@ class TestConversion(object): int_func, np.array([NotConvertible()])) -class TestWhere(object): +class TestWhere: def test_basic(self): dts = [bool, np.int16, np.int32, np.int64, np.double, np.complex128, np.longdouble, np.clongdouble] @@ -7756,7 +7775,7 @@ class TestWhere(object): if not IS_PYPY: # sys.getsizeof() is not valid on PyPy - class TestSizeOf(object): + class TestSizeOf: def test_empty_array(self): x = np.array([]) @@ -7789,7 +7808,7 @@ if not IS_PYPY: d = np.ones(100) assert_(sys.getsizeof(d) < sys.getsizeof(d.reshape(100, 1, 1).copy())) - @no_tracing + @_no_tracing def test_resize(self): d = np.ones(100) old = sys.getsizeof(d) @@ -7803,7 +7822,7 @@ if not IS_PYPY: assert_raises(TypeError, d.__sizeof__, "a") -class TestHashing(object): +class TestHashing: def test_arrays_not_hashable(self): x = np.ones(3) @@ -7814,7 +7833,7 @@ class TestHashing(object): assert_(not isinstance(x, collections_abc.Hashable)) -class TestArrayPriority(object): +class TestArrayPriority: # This will go away when __array_priority__ is settled, meanwhile # it serves to check unintended changes. op = operator @@ -7841,7 +7860,7 @@ class TestArrayPriority(object): def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) - class Other(object): + class Other: __array_priority__ = 1000. def _all(self, other): @@ -7900,7 +7919,7 @@ class TestArrayPriority(object): assert_(isinstance(f(b, a), self.Other), msg) -class TestBytestringArrayNonzero(object): +class TestBytestringArrayNonzero: def test_empty_bstring_array_is_falsey(self): assert_(not np.array([''], dtype=str)) @@ -7921,7 +7940,7 @@ class TestBytestringArrayNonzero(object): assert_(a) -class TestUnicodeArrayNonzero(object): +class TestUnicodeArrayNonzero: def test_empty_ustring_array_is_falsey(self): assert_(not np.array([''], dtype=np.unicode_)) @@ -7942,7 +7961,7 @@ class TestUnicodeArrayNonzero(object): assert_(a) -class TestFormat(object): +class TestFormat: def test_0d(self): a = np.array(np.pi) @@ -7967,7 +7986,7 @@ class TestFormat(object): from numpy.testing import IS_PYPY -class TestCTypes(object): +class TestCTypes: def test_ctypes_is_available(self): test_arr = np.array([[1, 2, 3], [4, 5, 6]]) @@ -8059,7 +8078,7 @@ class TestCTypes(object): assert_(arr_ref() is None, "unknowable whether ctypes pointer holds a reference") -class TestWritebackIfCopy(object): +class TestWritebackIfCopy: # all these tests use the WRITEBACKIFCOPY mechanism def test_argmax_with_out(self): mat = np.eye(5) @@ -8172,7 +8191,7 @@ class TestWritebackIfCopy(object): assert_equal(arr, orig) -class TestArange(object): +class TestArange: def test_infinite(self): assert_raises_regex( ValueError, "size exceeded", @@ -8194,7 +8213,7 @@ class TestArange(object): assert_raises(ZeroDivisionError, np.arange, 0.0, 0.0, 0.0) -class TestArrayFinalize(object): +class TestArrayFinalize: """ Tests __array_finalize__ """ def test_receives_base(self): @@ -8214,7 +8233,7 @@ class TestArrayFinalize(object): raise Exception(self) # a plain object can't be weakref'd - class Dummy(object): pass + class Dummy: pass # get a weak reference to an object within an array obj_arr = np.array(Dummy()) @@ -8223,9 +8242,6 @@ class TestArrayFinalize(object): # get an array that crashed in __array_finalize__ with assert_raises(Exception) as e: obj_arr.view(RaisesInFinalize) - if sys.version_info.major == 2: - # prevent an extra reference being kept - sys.exc_clear() obj_subarray = e.exception.args[0] del e @@ -8254,7 +8270,7 @@ def test_equal_override(): # gh-9153: ndarray.__eq__ uses special logic for structured arrays, which # did not respect overrides with __array_priority__ or __array_ufunc__. # The PR fixed this for __array_priority__ and __array_ufunc__ = None. - class MyAlwaysEqual(object): + class MyAlwaysEqual: def __eq__(self, other): return "eq" @@ -8352,7 +8368,7 @@ def test_uintalignment_and_alignment(): dst = np.zeros((2,2), dtype='c8') dst[:,1] = src[:,1] # assert in lowlevel_strided_loops fails? -class TestAlignment(object): +class TestAlignment: # adapted from scipy._lib.tests.test__util.test__aligned_zeros # Checks that unusual memory alignments don't trip up numpy. # In particular, check RELAXED_STRIDES don't trip alignment assertions in diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index daec9ce6d..24272bb0d 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import pytest @@ -2188,7 +2186,7 @@ def test_iter_no_broadcast(): [['readonly'], ['readonly'], ['readonly', 'no_broadcast']]) -class TestIterNested(object): +class TestIterNested: def test_basic(self): # Test nested iteration basic usage diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index ffebdf648..934f0a2fd 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import warnings import itertools @@ -17,7 +15,7 @@ from numpy.testing import ( ) -class TestResize(object): +class TestResize: def test_copies(self): A = np.array([[1, 2], [3, 4]]) Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) @@ -49,7 +47,7 @@ class TestResize(object): assert_equal(A.dtype, Ar.dtype) -class TestNonarrayArgs(object): +class TestNonarrayArgs: # check that non-array arguments to functions wrap them in arrays def test_choose(self): choices = [[0, 1, 2], @@ -220,7 +218,7 @@ class TestNonarrayArgs(object): B[0] = 1j assert_almost_equal(np.var(B), 0.25) -class TestIsscalar(object): +class TestIsscalar: def test_isscalar(self): assert_(np.isscalar(3.1)) assert_(np.isscalar(np.int16(12345))) @@ -236,7 +234,7 @@ class TestIsscalar(object): assert_(np.isscalar(Number())) -class TestBoolScalar(object): +class TestBoolScalar: def test_logical(self): f = np.False_ t = np.True_ @@ -269,7 +267,7 @@ class TestBoolScalar(object): assert_((f ^ f) is f) -class TestBoolArray(object): +class TestBoolArray: def setup(self): # offset for simd tests self.t = np.array([True] * 41, dtype=bool)[1::] @@ -356,7 +354,7 @@ class TestBoolArray(object): assert_array_equal(self.im ^ False, self.im) -class TestBoolCmp(object): +class TestBoolCmp: def setup(self): self.f = np.ones(256, dtype=np.float32) self.ef = np.ones(self.f.size, dtype=bool) @@ -456,7 +454,7 @@ class TestBoolCmp(object): assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:]) -class TestSeterr(object): +class TestSeterr: def test_default(self): err = np.geterr() assert_equal(err, @@ -537,7 +535,7 @@ class TestSeterr(object): np.seterrobj(olderrobj) -class TestFloatExceptions(object): +class TestFloatExceptions: def assert_raises_fpe(self, fpeerr, flop, x, y): ftype = type(x) try: @@ -633,7 +631,7 @@ class TestFloatExceptions(object): assert_("underflow" in str(w[-1].message)) -class TestTypes(object): +class TestTypes: def check_promotion_cases(self, promote_func): # tests that the scalars get coerced correctly. b = np.bool_(0) @@ -954,7 +952,7 @@ class NIterError(Exception): pass -class TestFromiter(object): +class TestFromiter: def makegen(self): for x in range(24): yield x**2 @@ -1005,7 +1003,7 @@ class TestFromiter(object): self.load_data(count, eindex), dtype=int, count=count) -class TestNonzero(object): +class TestNonzero: def test_nonzero_trivial(self): assert_equal(np.count_nonzero(np.array([])), 0) assert_equal(np.count_nonzero(np.array([], dtype='?')), 0) @@ -1288,7 +1286,7 @@ class TestNonzero(object): assert_raises(ValueError, np.nonzero, a) -class TestIndex(object): +class TestIndex: def test_boolean(self): a = rand(3, 5, 8) V = rand(5, 8) @@ -1305,7 +1303,7 @@ class TestIndex(object): assert_equal(c.dtype, np.dtype('int32')) -class TestBinaryRepr(object): +class TestBinaryRepr: def test_zero(self): assert_equal(np.binary_repr(0), '0') @@ -1347,7 +1345,7 @@ class TestBinaryRepr(object): '11' + '0'*62) -class TestBaseRepr(object): +class TestBaseRepr: def test_base3(self): assert_equal(np.base_repr(3**5, 3), '100000') @@ -1369,7 +1367,7 @@ class TestBaseRepr(object): np.base_repr(1, 37) -class TestArrayComparisons(object): +class TestArrayComparisons: def test_array_equal(self): res = np.array_equal(np.array([1, 2]), np.array([1, 2])) assert_(res) @@ -1448,7 +1446,7 @@ def assert_array_strict_equal(x, y): assert_(x.dtype.isnative == y.dtype.isnative) -class TestClip(object): +class TestClip: def setup(self): self.nr = 5 self.nc = 3 @@ -2022,7 +2020,7 @@ class TestClip(object): assert_equal(actual, expected) -class TestAllclose(object): +class TestAllclose: rtol = 1e-5 atol = 1e-8 @@ -2107,7 +2105,7 @@ class TestAllclose(object): assert_(type(np.allclose(a, a)) is bool) -class TestIsclose(object): +class TestIsclose: rtol = 1e-5 atol = 1e-8 @@ -2245,7 +2243,7 @@ class TestIsclose(object): assert_(type(np.isclose(0, np.inf)) is np.bool_) -class TestStdVar(object): +class TestStdVar: def setup(self): self.A = np.array([1, -1, 1, -1]) self.real_var = 1 @@ -2284,7 +2282,7 @@ class TestStdVar(object): assert_array_equal(r, out) -class TestStdVarComplex(object): +class TestStdVarComplex: def test_basic(self): A = np.array([1, 1.j, -1, -1.j]) real_var = 1 @@ -2296,7 +2294,7 @@ class TestStdVarComplex(object): assert_equal(np.std(1j), 0) -class TestCreationFuncs(object): +class TestCreationFuncs: # Test ones, zeros, empty and full. def setup(self): @@ -2367,7 +2365,7 @@ class TestCreationFuncs(object): assert_(sys.getrefcount(dim) == beg) -class TestLikeFuncs(object): +class TestLikeFuncs: '''Test ones_like, zeros_like, empty_like and full_like''' def setup(self): @@ -2517,7 +2515,7 @@ class TestLikeFuncs(object): self.check_like_function(np.full_like, np.inf, True) -class TestCorrelate(object): +class TestCorrelate: def _setup(self, dt): self.x = np.array([1, 2, 3, 4, 5], dtype=dt) self.xs = np.arange(1, 20)[::3] @@ -2573,7 +2571,7 @@ class TestCorrelate(object): with pytest.raises(ValueError): np.correlate(np.ones(1000), np.array([]), mode='full') -class TestConvolve(object): +class TestConvolve: def test_object(self): d = [1.] * 100 k = [1.] * 3 @@ -2587,7 +2585,7 @@ class TestConvolve(object): assert_array_equal(k, np.ones(3)) -class TestArgwhere(object): +class TestArgwhere: @pytest.mark.parametrize('nd', [0, 1, 2]) def test_nd(self, nd): @@ -2624,7 +2622,7 @@ class TestArgwhere(object): assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]]) -class TestStringFunction(object): +class TestStringFunction: def test_set_string_function(self): a = np.array([1]) @@ -2639,7 +2637,7 @@ class TestStringFunction(object): assert_equal(str(a), "[1]") -class TestRoll(object): +class TestRoll: def test_roll1d(self): x = np.arange(10) xr = np.roll(x, 2) @@ -2697,7 +2695,7 @@ class TestRoll(object): assert_equal(np.roll(x, 1), np.array([])) -class TestRollaxis(object): +class TestRollaxis: # expected shape indexed by (axis, start) for array of # shape (1, 2, 3, 4) @@ -2759,7 +2757,7 @@ class TestRollaxis(object): assert_(not res.flags['OWNDATA']) -class TestMoveaxis(object): +class TestMoveaxis: def test_move_to_end(self): x = np.random.randn(5, 6, 7) for source, expected in [(0, (6, 7, 5)), @@ -2833,7 +2831,7 @@ class TestMoveaxis(object): assert_(isinstance(result, np.ndarray)) -class TestCross(object): +class TestCross: def test_2x2(self): u = [1, 2] v = [3, 4] @@ -2922,7 +2920,7 @@ def test_outer_out_param(): assert_equal(np.outer(arr2, arr3, out2), out2) -class TestIndices(object): +class TestIndices: def test_simple(self): [x, y] = np.indices((4, 3)) @@ -2963,7 +2961,7 @@ class TestIndices(object): assert_(arr.dtype == dtype) -class TestRequire(object): +class TestRequire: flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS', 'F', 'F_CONTIGUOUS', 'FORTRAN', 'A', 'ALIGNED', @@ -3037,7 +3035,7 @@ class TestRequire(object): self.set_and_check_flag(flag, None, a) -class TestBroadcast(object): +class TestBroadcast: def test_broadcast_in_args(self): # gh-5881 arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)), @@ -3088,7 +3086,7 @@ class TestBroadcast(object): assert_raises(ValueError, np.broadcast, 1, **{'x': 1}) -class TestKeepdims(object): +class TestKeepdims: class sub_array(np.ndarray): def sum(self, axis=None, dtype=None, out=None): @@ -3100,7 +3098,7 @@ class TestKeepdims(object): assert_raises(TypeError, np.sum, x, keepdims=True) -class TestTensordot(object): +class TestTensordot: def test_zero_dimension(self): # Test resolution to issue #5663 diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index 387740e35..7105154ed 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import itertools @@ -100,7 +98,7 @@ def normalize_descr(descr): # Creation tests ############################################################ -class CreateZeros(object): +class CreateZeros: """Check the creation of heterogeneous arrays zero-valued""" def test_zeros0D(self): @@ -143,7 +141,7 @@ class TestCreateZerosNested(CreateZeros): _descr = Ndescr -class CreateValues(object): +class CreateValues: """Check the creation of heterogeneous arrays with values""" def test_tuple(self): @@ -203,7 +201,7 @@ class TestCreateValuesNestedMultiple(CreateValues): # Reading tests ############################################################ -class ReadValuesPlain(object): +class ReadValuesPlain: """Check the reading of values in heterogeneous arrays (plain)""" def test_access_fields(self): @@ -235,7 +233,7 @@ class TestReadValuesPlainMultiple(ReadValuesPlain): multiple_rows = 1 _buffer = PbufferT -class ReadValuesNested(object): +class ReadValuesNested: """Check the reading of values in heterogeneous arrays (nested)""" def test_access_top_fields(self): @@ -333,14 +331,14 @@ class TestReadValuesNestedMultiple(ReadValuesNested): multiple_rows = True _buffer = NbufferT -class TestEmptyField(object): +class TestEmptyField: def test_assign(self): a = np.arange(10, dtype=np.float32) a.dtype = [("int", "<0i4"), ("float", "<2f4")] assert_(a['int'].shape == (5, 0)) assert_(a['float'].shape == (5, 2)) -class TestCommonType(object): +class TestCommonType: def test_scalar_loses1(self): res = np.find_common_type(['f4', 'f4', 'i2'], ['f8']) assert_(res == 'f4') @@ -361,7 +359,7 @@ class TestCommonType(object): res = np.find_common_type(['u8', 'i8', 'i8'], ['f8']) assert_(res == 'f8') -class TestMultipleFields(object): +class TestMultipleFields: def setup(self): self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8') @@ -376,7 +374,7 @@ class TestMultipleFields(object): assert_(res == [(1, 3), (5, 7)]) -class TestIsSubDType(object): +class TestIsSubDType: # scalar types can be promoted into dtypes wrappers = [np.dtype, lambda x: x] @@ -407,18 +405,18 @@ class TestIsSubDType(object): assert_(not np.issubdtype(w1(np.float64), w2(np.float32))) -class TestSctypeDict(object): +class TestSctypeDict: def test_longdouble(self): assert_(np.sctypeDict['f8'] is not np.longdouble) assert_(np.sctypeDict['c16'] is not np.clongdouble) -class TestBitName(object): +class TestBitName: def test_abstract(self): assert_raises(ValueError, np.core.numerictypes.bitname, np.floating) -class TestMaximumSctype(object): +class TestMaximumSctype: # note that parametrizing with sctype['int'] and similar would skip types # with the same size (gh-11923) @@ -444,7 +442,7 @@ class TestMaximumSctype(object): assert_equal(np.maximum_sctype(t), t) -class Test_sctype2char(object): +class Test_sctype2char: # This function is old enough that we're really just documenting the quirks # at this point. @@ -492,7 +490,7 @@ def test_issctype(rep, expected): @pytest.mark.skipif(sys.flags.optimize > 1, reason="no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1") @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc") -class TestDocStrings(object): +class TestDocStrings: def test_platform_dependent_aliases(self): if np.int64 is np.int_: assert_('int64' in np.int_.__doc__) diff --git a/numpy/core/tests/test_overrides.py b/numpy/core/tests/test_overrides.py index 63b0e4539..7e73d8c03 100644 --- a/numpy/core/tests/test_overrides.py +++ b/numpy/core/tests/test_overrides.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import inspect import sys from unittest import mock @@ -36,7 +34,7 @@ def dispatched_two_arg(array1, array2): return 'original' -class TestGetImplementingArgs(object): +class TestGetImplementingArgs: def test_ndarray(self): array = np.array(1) @@ -77,7 +75,7 @@ class TestGetImplementingArgs(object): def test_ndarray_and_duck_array(self): - class Other(object): + class Other: __array_function__ = _return_not_implemented array = np.array(1) @@ -94,7 +92,7 @@ class TestGetImplementingArgs(object): class OverrideSub(np.ndarray): __array_function__ = _return_not_implemented - class Other(object): + class Other: __array_function__ = _return_not_implemented array = np.array(1) @@ -108,7 +106,7 @@ class TestGetImplementingArgs(object): def test_many_duck_arrays(self): - class A(object): + class A: __array_function__ = _return_not_implemented class B(A): @@ -117,7 +115,7 @@ class TestGetImplementingArgs(object): class C(A): __array_function__ = _return_not_implemented - class D(object): + class D: __array_function__ = _return_not_implemented a = A() @@ -147,12 +145,12 @@ class TestGetImplementingArgs(object): _get_implementing_args(relevant_args) -class TestNDArrayArrayFunction(object): +class TestNDArrayArrayFunction: @requires_array_function def test_method(self): - class Other(object): + class Other: __array_function__ = _return_not_implemented class NoOverrideSub(np.ndarray): @@ -209,7 +207,7 @@ class TestNDArrayArrayFunction(object): @requires_array_function -class TestArrayFunctionDispatch(object): +class TestArrayFunctionDispatch: def test_pickle(self): for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): @@ -224,7 +222,7 @@ class TestArrayFunctionDispatch(object): def test_interface(self): - class MyArray(object): + class MyArray: def __array_function__(self, func, types, args, kwargs): return (self, func, types, args, kwargs) @@ -239,7 +237,7 @@ class TestArrayFunctionDispatch(object): def test_not_implemented(self): - class MyArray(object): + class MyArray: def __array_function__(self, func, types, args, kwargs): return NotImplemented @@ -249,7 +247,7 @@ class TestArrayFunctionDispatch(object): @requires_array_function -class TestVerifyMatchingSignatures(object): +class TestVerifyMatchingSignatures: def test_verify_matching_signatures(self): @@ -283,7 +281,7 @@ def _new_duck_type_and_implements(): """Create a duck array type and implements functions.""" HANDLED_FUNCTIONS = {} - class MyArray(object): + class MyArray: def __array_function__(self, func, types, args, kwargs): if func not in HANDLED_FUNCTIONS: return NotImplemented @@ -302,7 +300,7 @@ def _new_duck_type_and_implements(): @requires_array_function -class TestArrayFunctionImplementation(object): +class TestArrayFunctionImplementation: def test_one_arg(self): MyArray, implements = _new_duck_type_and_implements() @@ -355,7 +353,7 @@ class TestArrayFunctionImplementation(object): func(MyArray()) -class TestNDArrayMethods(object): +class TestNDArrayMethods: def test_repr(self): # gh-12162: should still be defined even if __array_function__ doesn't @@ -370,7 +368,7 @@ class TestNDArrayMethods(object): assert_equal(str(array), '1') -class TestNumPyFunctions(object): +class TestNumPyFunctions: def test_set_module(self): assert_equal(np.sum.__module__, 'numpy') diff --git a/numpy/core/tests/test_print.py b/numpy/core/tests/test_print.py index c5c091e13..36d652a41 100644 --- a/numpy/core/tests/test_print.py +++ b/numpy/core/tests/test_print.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import pytest diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index 0f88f99e0..4b4bd2729 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys try: # Accessing collections abstract classes from collections @@ -20,7 +18,7 @@ from numpy.testing import ( from numpy.compat import pickle -class TestFromrecords(object): +class TestFromrecords: def test_fromrecords(self): r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], names='col1,col2,col3') @@ -326,7 +324,7 @@ class TestFromrecords(object): @pytest.mark.skipif(Path is None, reason="No pathlib.Path") -class TestPathUsage(object): +class TestPathUsage: # Test that pathlib.Path can be used def test_tofile_fromfile(self): with temppath(suffix='.bin') as path: @@ -342,7 +340,7 @@ class TestPathUsage(object): assert_array_equal(x, a) -class TestRecord(object): +class TestRecord: def setup(self): self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)], dtype=[("col1", "<i4"), diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index f2f9c1457..c77c11d41 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import copy import sys import gc @@ -24,7 +22,7 @@ try: except NameError: RecursionError = RuntimeError # python < 3.5 -class TestRegression(object): +class TestRegression: def test_invalid_round(self): # Ticket #3 v = 4.7599999999999998 @@ -428,7 +426,7 @@ class TestRegression(object): def test_lexsort_invalid_sequence(self): # Issue gh-4123 - class BuggySequence(object): + class BuggySequence: def __len__(self): return 4 @@ -1041,7 +1039,7 @@ class TestRegression(object): def test_mem_custom_float_to_array(self): # Ticket 702 - class MyFloat(object): + class MyFloat: def __float__(self): return 1.0 @@ -1050,7 +1048,7 @@ class TestRegression(object): def test_object_array_refcount_self_assign(self): # Ticket #711 - class VictimObject(object): + class VictimObject: deleted = False def __del__(self): @@ -2233,7 +2231,7 @@ class TestRegression(object): import operator as op # dummy class where __array__ throws exception - class Foo(object): + class Foo: __array_priority__ = 1002 def __array__(self, *args, **kwargs): @@ -2482,7 +2480,7 @@ class TestRegression(object): assert_equal(pickle.loads(dumped), arr) def test_bad_array_interface(self): - class T(object): + class T: __array_interface__ = {} np.array([T()]) diff --git a/numpy/core/tests/test_scalar_ctors.py b/numpy/core/tests/test_scalar_ctors.py index b21bc9dad..ae29d0605 100644 --- a/numpy/core/tests/test_scalar_ctors.py +++ b/numpy/core/tests/test_scalar_ctors.py @@ -1,8 +1,6 @@ """ Test the scalar constructors, which also do type-coercion """ -from __future__ import division, absolute_import, print_function - import sys import platform import pytest @@ -12,7 +10,7 @@ from numpy.testing import ( assert_equal, assert_almost_equal, assert_raises, assert_warns, ) -class TestFromString(object): +class TestFromString: def test_floating(self): # Ticket #640, floats from string fsingle = np.single('1.234') @@ -56,7 +54,7 @@ class TestFromString(object): assert_equal(255, np.intp('0xFF', 16)) -class TestFromInt(object): +class TestFromInt: def test_intp(self): # Ticket #99 assert_equal(1024, np.intp(1024)) diff --git a/numpy/core/tests/test_scalar_methods.py b/numpy/core/tests/test_scalar_methods.py index 93434dd1b..c9de3e402 100644 --- a/numpy/core/tests/test_scalar_methods.py +++ b/numpy/core/tests/test_scalar_methods.py @@ -1,8 +1,6 @@ """ Test the scalar constructors, which also do type-coercion """ -from __future__ import division, absolute_import, print_function - import os import fractions import platform @@ -16,7 +14,7 @@ from numpy.testing import ( dec ) -class TestAsIntegerRatio(object): +class TestAsIntegerRatio: # derived in part from the cpython test "test_floatasratio" @pytest.mark.parametrize("ftype", [ diff --git a/numpy/core/tests/test_scalarbuffer.py b/numpy/core/tests/test_scalarbuffer.py index 3ded7eecd..85673e3ab 100644 --- a/numpy/core/tests/test_scalarbuffer.py +++ b/numpy/core/tests/test_scalarbuffer.py @@ -33,7 +33,7 @@ scalars_only, codes_only = zip(*scalars_and_codes) @pytest.mark.skipif(sys.version_info.major < 3, reason="Python 2 scalars lack a buffer interface") -class TestScalarPEP3118(object): +class TestScalarPEP3118: @pytest.mark.parametrize('scalar', scalars_only, ids=codes_only) def test_scalar_match_array(self, scalar): diff --git a/numpy/core/tests/test_scalarinherit.py b/numpy/core/tests/test_scalarinherit.py index 6a5c4fde9..af3669d73 100644 --- a/numpy/core/tests/test_scalarinherit.py +++ b/numpy/core/tests/test_scalarinherit.py @@ -2,13 +2,11 @@ """ Test printing of scalar types. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_ -class A(object): +class A: pass class B(A, np.float64): pass @@ -23,7 +21,7 @@ class B0(np.float64, A): class C0(B0): pass -class TestInherit(object): +class TestInherit: def test_init(self): x = B(1.0) assert_(str(x) == '1.0') @@ -39,7 +37,7 @@ class TestInherit(object): assert_(str(y) == '2.0') -class TestCharacter(object): +class TestCharacter: def test_char_radd(self): # GH issue 9620, reached gentype_add and raise TypeError np_s = np.string_('abc') diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index c84380cd9..789ef4acd 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import warnings import itertools @@ -25,7 +23,7 @@ complex_floating_types = np.complexfloating.__subclasses__() # This compares scalarmath against ufuncs. -class TestTypes(object): +class TestTypes: def test_types(self): for atype in types: a = atype(1) @@ -64,7 +62,7 @@ class TestTypes(object): np.add(1, 1) -class TestBaseMath(object): +class TestBaseMath: def test_blocked(self): # test alignments offsets for simd instructions # alignments for vz + 2 * (vs - 1) + 1 @@ -110,7 +108,7 @@ class TestBaseMath(object): np.add(d, np.ones_like(d)) -class TestPower(object): +class TestPower: def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) @@ -202,7 +200,7 @@ def _signs(dt): return (+1, -1) -class TestModulus(object): +class TestModulus: def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] @@ -304,7 +302,7 @@ class TestModulus(object): a //= b -class TestComplexDivision(object): +class TestComplexDivision: def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: @@ -376,7 +374,7 @@ class TestComplexDivision(object): assert_equal(result.imag, ex[1]) -class TestConversion(object): +class TestConversion: def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] @@ -512,7 +510,7 @@ class TestConversion(object): assert_(np.equal(np.datetime64('NaT'), None)) -#class TestRepr(object): +#class TestRepr: # def test_repr(self): # for t in types: # val = t(1197346475.0137341) @@ -521,7 +519,7 @@ class TestConversion(object): # assert_equal( val, val2 ) -class TestRepr(object): +class TestRepr: def _test_type_repr(self, t): finfo = np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant @@ -556,7 +554,7 @@ class TestRepr(object): if not IS_PYPY: # sys.getsizeof() is not valid on PyPy - class TestSizeOf(object): + class TestSizeOf: def test_equal_nbytes(self): for type in types: @@ -568,7 +566,7 @@ if not IS_PYPY: assert_raises(TypeError, d.__sizeof__, "a") -class TestMultiply(object): +class TestMultiply: def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. @@ -605,7 +603,7 @@ class TestMultiply(object): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. - class ArrayLike(object): + class ArrayLike: def __init__(self, arr): self.arr = arr def __array__(self): @@ -619,7 +617,7 @@ class TestMultiply(object): assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) -class TestNegative(object): +class TestNegative: def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.neg, a) @@ -633,7 +631,7 @@ class TestNegative(object): assert_equal(operator.neg(a) + a, 0) -class TestSubtract(object): +class TestSubtract: def test_exceptions(self): a = np.ones((), dtype=np.bool_)[()] assert_raises(TypeError, operator.sub, a, a) @@ -647,7 +645,7 @@ class TestSubtract(object): assert_equal(operator.sub(a, a), 0) -class TestAbs(object): +class TestAbs: def _test_abs_func(self, absfunc): for tp in floating_types + complex_floating_types: x = tp(-1.5) @@ -676,7 +674,7 @@ class TestAbs(object): self._test_abs_func(np.abs) -class TestBitShifts(object): +class TestBitShifts: @pytest.mark.parametrize('type_code', np.typecodes['AllInteger']) @pytest.mark.parametrize('op', diff --git a/numpy/core/tests/test_scalarprint.py b/numpy/core/tests/test_scalarprint.py index 86b0ca199..225b8295f 100644 --- a/numpy/core/tests/test_scalarprint.py +++ b/numpy/core/tests/test_scalarprint.py @@ -2,8 +2,6 @@ """ Test printing of scalar types. """ -from __future__ import division, absolute_import, print_function - import code, sys import platform import pytest @@ -12,7 +10,7 @@ from tempfile import TemporaryFile import numpy as np from numpy.testing import assert_, assert_equal, suppress_warnings -class TestRealScalars(object): +class TestRealScalars: def test_str(self): svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan] styps = [np.float16, np.float32, np.float64, np.longdouble] diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py index 53d272fc5..d2f5287a6 100644 --- a/numpy/core/tests/test_shape_base.py +++ b/numpy/core/tests/test_shape_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest import sys import numpy as np @@ -16,7 +14,7 @@ from numpy.testing import ( from numpy.compat import long -class TestAtleast1d(object): +class TestAtleast1d: def test_0D_array(self): a = array(1) b = array(2) @@ -57,7 +55,7 @@ class TestAtleast1d(object): assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2)) -class TestAtleast2d(object): +class TestAtleast2d: def test_0D_array(self): a = array(1) b = array(2) @@ -96,7 +94,7 @@ class TestAtleast2d(object): assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2)) -class TestAtleast3d(object): +class TestAtleast3d: def test_0D_array(self): a = array(1) b = array(2) @@ -128,7 +126,7 @@ class TestAtleast3d(object): assert_array_equal(res, desired) -class TestHstack(object): +class TestHstack: def test_non_iterable(self): assert_raises(TypeError, hstack, 1) @@ -165,7 +163,7 @@ class TestHstack(object): hstack(map(lambda x: x, np.ones((3, 2)))) -class TestVstack(object): +class TestVstack: def test_non_iterable(self): assert_raises(TypeError, vstack, 1) @@ -205,7 +203,7 @@ class TestVstack(object): vstack((np.arange(3) for _ in range(2))) -class TestConcatenate(object): +class TestConcatenate: def test_returns_copy(self): a = np.eye(3) b = np.concatenate([a]) @@ -409,7 +407,7 @@ def test_stack(): assert_array_equal(result, np.array([0, 1, 2])) -class TestBlock(object): +class TestBlock: @pytest.fixture(params=['block', 'force_concatenate', 'force_slicing']) def block(self, request): # blocking small arrays and large arrays go through different paths. @@ -707,7 +705,7 @@ class TestBlock(object): def test_block_dispatcher(): - class ArrayLike(object): + class ArrayLike: pass a = ArrayLike() b = ArrayLike() diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index 7109de776..507ac87b9 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import warnings import itertools @@ -23,7 +21,7 @@ UNARY_UFUNCS = [obj for obj in np.core.umath.__dict__.values() UNARY_OBJECT_UFUNCS = [uf for uf in UNARY_UFUNCS if "O->O" in uf.types] -class TestUfuncKwargs(object): +class TestUfuncKwargs: def test_kwarg_exact(self): assert_raises(TypeError, np.add, 1, 2, castingx='safe') assert_raises(TypeError, np.add, 1, 2, dtypex=int) @@ -49,7 +47,7 @@ class TestUfuncKwargs(object): assert_raises(TypeError, np.add, 1, 2, extobj=[4096], parrot=True) -class TestUfuncGenericLoops(object): +class TestUfuncGenericLoops: """Test generic loops. The loops to be tested are: @@ -118,7 +116,7 @@ class TestUfuncGenericLoops(object): assert_equal(ys.dtype, output_dtype) # class to use in testing object method loops - class foo(object): + class foo: def conjugate(self): return np.bool_(1) @@ -179,7 +177,7 @@ class TestUfuncGenericLoops(object): assert_array_equal(res_num.astype("O"), res_obj) -class TestUfunc(object): +class TestUfunc: def test_pickle(self): for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): assert_(pickle.loads(pickle.dumps(np.sin, @@ -1123,7 +1121,7 @@ class TestUfunc(object): assert_equal(np.logical_and.reduce(a), None) def test_object_comparison(self): - class HasComparisons(object): + class HasComparisons: def __eq__(self, other): return '==' @@ -1592,7 +1590,7 @@ class TestUfunc(object): def test_custom_array_like(self): - class MyThing(object): + class MyThing: __array_priority__ = 1000 rmul_count = 0 diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index ae1090c23..2913b1c4d 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import platform import warnings import fnmatch @@ -23,7 +21,7 @@ def on_powerpc(): platform.machine().startswith('ppc') -class _FilterInvalids(object): +class _FilterInvalids: def setup(self): self.olderr = np.seterr(invalid='ignore') @@ -31,7 +29,7 @@ class _FilterInvalids(object): np.seterr(**self.olderr) -class TestConstants(object): +class TestConstants: def test_pi(self): assert_allclose(ncu.pi, 3.141592653589793, 1e-15) @@ -42,7 +40,7 @@ class TestConstants(object): assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15) -class TestOut(object): +class TestOut: def test_out_subok(self): for subok in (True, False): a = np.array(0.5) @@ -168,7 +166,7 @@ class TestOut(object): r1, r2 = np.frexp(d, out=o1, subok=subok) -class TestComparisons(object): +class TestComparisons: def test_ignore_object_identity_in_equal(self): # Check comparing identical objects whose comparison # is not a simple boolean, e.g., arrays that are compared elementwise. @@ -176,7 +174,7 @@ class TestComparisons(object): assert_raises(ValueError, np.equal, a, a) # Check error raised when comparing identical non-comparable objects. - class FunkyType(object): + class FunkyType: def __eq__(self, other): raise TypeError("I won't compare") @@ -194,7 +192,7 @@ class TestComparisons(object): assert_raises(ValueError, np.not_equal, a, a) # Check error raised when comparing identical non-comparable objects. - class FunkyType(object): + class FunkyType: def __ne__(self, other): raise TypeError("I won't compare") @@ -206,7 +204,7 @@ class TestComparisons(object): assert_equal(np.not_equal(a, a), [True]) -class TestAdd(object): +class TestAdd: def test_reduce_alignment(self): # gh-9876 # make sure arrays with weird strides work with the optimizations in @@ -217,7 +215,7 @@ class TestAdd(object): assert_equal(a['b'].sum(), 0) -class TestDivision(object): +class TestDivision: def test_division_int(self): # int division should follow Python x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120]) @@ -284,7 +282,7 @@ def _signs(dt): return (+1, -1) -class TestRemainder(object): +class TestRemainder: def test_remainder_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] @@ -375,7 +373,7 @@ class TestRemainder(object): assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) -class TestCbrt(object): +class TestCbrt: def test_cbrt_scalar(self): assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) @@ -388,7 +386,7 @@ class TestCbrt(object): assert_equal(np.cbrt(-np.inf), -np.inf) -class TestPower(object): +class TestPower: def test_power_float(self): x = np.array([1., 2., 3.]) assert_equal(x**0, [1., 1., 1.]) @@ -527,7 +525,7 @@ class TestPower(object): assert_raises(ValueError, np.power, one, minusone) -class TestFloat_power(object): +class TestFloat_power: def test_type_conversion(self): arg_type = '?bhilBHILefdgFDG' res_type = 'ddddddddddddgDDG' @@ -538,7 +536,7 @@ class TestFloat_power(object): assert_(res.dtype.name == np.dtype(dtout).name, msg) -class TestLog2(object): +class TestLog2: def test_log2_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @@ -569,7 +567,7 @@ class TestLog2(object): assert_(w[2].category is RuntimeWarning) -class TestExp2(object): +class TestExp2: def test_exp2_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @@ -621,7 +619,7 @@ class TestLogAddExp2(_FilterInvalids): assert_(np.isnan(np.logaddexp2(np.nan, np.nan))) -class TestLog(object): +class TestLog: def test_log_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @@ -632,7 +630,7 @@ class TestLog(object): assert_almost_equal(np.log(xf), yf) -class TestExp(object): +class TestExp: def test_exp_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] @@ -642,7 +640,7 @@ class TestExp(object): yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.exp(yf), xf) -class TestSpecialFloats(object): +class TestSpecialFloats: def test_exp_values(self): x = [np.nan, np.nan, np.inf, 0.] y = [np.nan, -np.nan, np.inf, -np.inf] @@ -744,7 +742,7 @@ avx_ufuncs = {'sqrt' :[1, 0., 100.], 'ceil' :[0, -100., 100.], 'trunc' :[0, -100., 100.]} -class TestAVXUfuncs(object): +class TestAVXUfuncs: def test_avx_based_ufunc(self): strides = np.array([-4,-3,-2,-1,1,2,3,4]) np.random.seed(42) @@ -776,7 +774,7 @@ class TestAVXUfuncs(object): assert_equal(myfunc(x_f64[::jj]), y_true64[::jj]) assert_equal(myfunc(x_f32[::jj]), y_true32[::jj]) -class TestAVXFloat32Transcendental(object): +class TestAVXFloat32Transcendental: def test_exp_float32(self): np.random.seed(42) x_f32 = np.float32(np.random.uniform(low=0.0,high=88.1,size=1000000)) @@ -862,7 +860,7 @@ class TestLogAddExp(_FilterInvalids): assert_equal(np.logaddexp.reduce([]), -np.inf) -class TestLog1p(object): +class TestLog1p: def test_log1p(self): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6)) @@ -876,7 +874,7 @@ class TestLog1p(object): assert_equal(ncu.log1p(-np.inf), np.nan) -class TestExpm1(object): +class TestExpm1: def test_expm1(self): assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1) assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1) @@ -895,7 +893,7 @@ class TestExpm1(object): assert_allclose(x, ncu.expm1(x)) -class TestHypot(object): +class TestHypot: def test_simple(self): assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) assert_almost_equal(ncu.hypot(0, 0), 0) @@ -919,7 +917,7 @@ def assert_hypot_isinf(x, y): "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) -class TestHypotSpecialValues(object): +class TestHypotSpecialValues: def test_nan_outputs(self): assert_hypot_isnan(np.nan, np.nan) assert_hypot_isnan(np.nan, 1) @@ -956,7 +954,7 @@ def assert_arctan2_isnzero(x, y): assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y))) -class TestArctan2SpecialValues(object): +class TestArctan2SpecialValues: def test_one_one(self): # atan2(1, 1) returns pi/4. assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi) @@ -1025,7 +1023,7 @@ class TestArctan2SpecialValues(object): assert_arctan2_isnan(np.nan, np.nan) -class TestLdexp(object): +class TestLdexp: def _check_ldexp(self, tp): assert_almost_equal(ncu.ldexp(np.array(2., np.float32), np.array(3, tp)), 16.) @@ -1253,7 +1251,7 @@ class TestFmin(_FilterInvalids): assert_equal(np.fmin(arg1, arg2), out) -class TestBool(object): +class TestBool: def test_exceptions(self): a = np.ones(1, dtype=np.bool_) assert_raises(TypeError, np.negative, a) @@ -1316,7 +1314,7 @@ class TestBool(object): assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) -class TestBitwiseUFuncs(object): +class TestBitwiseUFuncs: bitwise_types = [np.dtype(c) for c in '?' + 'bBhHiIlLqQ' + 'O'] @@ -1400,7 +1398,7 @@ class TestBitwiseUFuncs(object): assert_(type(f.reduce(btype)) is bool, msg) -class TestInt(object): +class TestInt: def test_logical_not(self): x = np.ones(10, dtype=np.int16) o = np.ones(10 * 2, dtype=bool) @@ -1411,24 +1409,24 @@ class TestInt(object): assert_array_equal(o, tgt) -class TestFloatingPoint(object): +class TestFloatingPoint: def test_floating_point(self): assert_equal(ncu.FLOATING_POINT_SUPPORT, 1) -class TestDegrees(object): +class TestDegrees: def test_degrees(self): assert_almost_equal(ncu.degrees(np.pi), 180.0) assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0) -class TestRadians(object): +class TestRadians: def test_radians(self): assert_almost_equal(ncu.radians(180.0), np.pi) assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi) -class TestHeavside(object): +class TestHeavside: def test_heaviside(self): x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]]) expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]]) @@ -1450,7 +1448,7 @@ class TestHeavside(object): assert_equal(h, expected1.astype(np.float32)) -class TestSign(object): +class TestSign: def test_sign(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape) @@ -1481,7 +1479,7 @@ class TestSign(object): assert_raises(TypeError, test_nan) -class TestMinMax(object): +class TestMinMax: def test_minmax_blocked(self): # simd tests on max/min, test all alignments, slow but important # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once) @@ -1524,7 +1522,7 @@ class TestMinMax(object): assert_equal(a, np.nan) -class TestAbsoluteNegative(object): +class TestAbsoluteNegative: def test_abs_neg_blocked(self): # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 5)]: @@ -1566,7 +1564,7 @@ class TestAbsoluteNegative(object): np.abs(np.ones_like(d), out=d) -class TestPositive(object): +class TestPositive: def test_valid(self): valid_dtypes = [int, float, complex, object] for dtype in valid_dtypes: @@ -1585,10 +1583,10 @@ class TestPositive(object): np.positive(np.array(['bar'], dtype=object)) -class TestSpecialMethods(object): +class TestSpecialMethods: def test_wrap(self): - class with_wrap(object): + class with_wrap: def __array__(self): return np.zeros(1) @@ -1692,7 +1690,7 @@ class TestSpecialMethods(object): def test_old_wrap(self): - class with_wrap(object): + class with_wrap: def __array__(self): return np.zeros(1) @@ -1707,7 +1705,7 @@ class TestSpecialMethods(object): def test_priority(self): - class A(object): + class A: def __array__(self): return np.zeros(1) @@ -1750,7 +1748,7 @@ class TestSpecialMethods(object): def test_failing_wrap(self): - class A(object): + class A: def __array__(self): return np.zeros(2) @@ -1782,7 +1780,7 @@ class TestSpecialMethods(object): def test_none_wrap(self): # Tests that issue #8507 is resolved. Previously, this would segfault - class A(object): + class A: def __array__(self): return np.zeros(1) @@ -1794,7 +1792,7 @@ class TestSpecialMethods(object): def test_default_prepare(self): - class with_wrap(object): + class with_wrap: __array_priority__ = 10 def __array__(self): @@ -1840,7 +1838,7 @@ class TestSpecialMethods(object): def test_failing_prepare(self): - class A(object): + class A: def __array__(self): return np.zeros(1) @@ -1852,7 +1850,7 @@ class TestSpecialMethods(object): def test_array_with_context(self): - class A(object): + class A: def __array__(self, dtype=None, context=None): func, args, i = context self.func = func @@ -1860,11 +1858,11 @@ class TestSpecialMethods(object): self.i = i return np.zeros(1) - class B(object): + class B: def __array__(self, dtype=None): return np.zeros(1, dtype) - class C(object): + class C: def __array__(self): return np.zeros(1) @@ -1879,7 +1877,7 @@ class TestSpecialMethods(object): def test_ufunc_override(self): # check override works even with instance with high priority. - class A(object): + class A: def __array_ufunc__(self, func, method, *inputs, **kwargs): return self, func, method, inputs, kwargs @@ -1916,7 +1914,7 @@ class TestSpecialMethods(object): three_mul_ufunc = np.frompyfunc(tres_mul, 3, 1) four_mul_ufunc = np.frompyfunc(quatro_mul, 4, 1) - class A(object): + class A: def __array_ufunc__(self, func, method, *inputs, **kwargs): return "A" @@ -1924,11 +1922,11 @@ class TestSpecialMethods(object): def __array_ufunc__(self, func, method, *inputs, **kwargs): return "ASub" - class B(object): + class B: def __array_ufunc__(self, func, method, *inputs, **kwargs): return "B" - class C(object): + class C: def __init__(self): self.count = 0 @@ -2040,7 +2038,7 @@ class TestSpecialMethods(object): def test_ufunc_override_methods(self): - class A(object): + class A: def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return self, ufunc, method, inputs, kwargs @@ -2209,11 +2207,11 @@ class TestSpecialMethods(object): def test_ufunc_override_out(self): - class A(object): + class A: def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return kwargs - class B(object): + class B: def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return kwargs @@ -2265,7 +2263,7 @@ class TestSpecialMethods(object): def test_ufunc_override_exception(self): - class A(object): + class A: def __array_ufunc__(self, *a, **kwargs): raise ValueError("oops") @@ -2276,7 +2274,7 @@ class TestSpecialMethods(object): def test_ufunc_override_not_implemented(self): - class A(object): + class A: def __array_ufunc__(self, *args, **kwargs): return NotImplemented @@ -2293,7 +2291,7 @@ class TestSpecialMethods(object): def test_ufunc_override_disabled(self): - class OptOut(object): + class OptOut: __array_ufunc__ = None opt_out = OptOut() @@ -2310,7 +2308,7 @@ class TestSpecialMethods(object): # opt-outs still hold even when other arguments have pathological # __array_ufunc__ implementations - class GreedyArray(object): + class GreedyArray: def __array_ufunc__(self, *args, **kwargs): return self @@ -2324,7 +2322,7 @@ class TestSpecialMethods(object): def test_gufunc_override(self): # gufunc are just ufunc instances, but follow a different path, # so check __array_ufunc__ overrides them properly. - class A(object): + class A: def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return self, ufunc, method, inputs, kwargs @@ -2406,7 +2404,7 @@ class TestSpecialMethods(object): return results[0] if len(results) == 1 else results - class B(object): + class B: def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): if any(isinstance(input_, A) for input_ in inputs): return "A!" @@ -2525,14 +2523,14 @@ class TestSpecialMethods(object): assert_(a.info, {'inputs': [0, 2]}) -class TestChoose(object): +class TestChoose: def test_mixed(self): c = np.array([True, True]) a = np.array([True, True]) assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) -class TestRationalFunctions(object): +class TestRationalFunctions: def test_lcm(self): self._test_lcm_inner(np.int16) self._test_lcm_inner(np.uint16) @@ -2631,7 +2629,7 @@ class TestRationalFunctions(object): assert_equal(np.gcd(2**100, 3**100), 1) -class TestRoundingFunctions(object): +class TestRoundingFunctions: def test_object_direct(self): """ test direct implementation of these magic methods """ @@ -2667,7 +2665,7 @@ class TestRoundingFunctions(object): assert_equal(np.trunc(f), -1) -class TestComplexFunctions(object): +class TestComplexFunctions: funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh, np.arctanh, np.sin, np.cos, np.tan, np.exp, np.exp2, np.log, np.sqrt, np.log10, np.log2, @@ -2850,7 +2848,7 @@ class TestComplexFunctions(object): check(func, pts, 1+1j) -class TestAttributes(object): +class TestAttributes: def test_attributes(self): add = ncu.add assert_equal(add.__name__, 'add') @@ -2869,7 +2867,7 @@ class TestAttributes(object): "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) -class TestSubclass(object): +class TestSubclass: def test_subclass_op(self): diff --git a/numpy/core/tests/test_umath_accuracy.py b/numpy/core/tests/test_umath_accuracy.py index fec180786..677d9af60 100644 --- a/numpy/core/tests/test_umath_accuracy.py +++ b/numpy/core/tests/test_umath_accuracy.py @@ -28,7 +28,7 @@ files = ['umath-validation-set-exp', 'umath-validation-set-sin', 'umath-validation-set-cos'] -class TestAccuracy(object): +class TestAccuracy: @pytest.mark.xfail(reason="Fails for MacPython/numpy-wheels builds") def test_validate_transcendentals(self): with np.errstate(all='ignore'): diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py index 1f5b4077f..5e5ced85c 100644 --- a/numpy/core/tests/test_umath_complex.py +++ b/numpy/core/tests/test_umath_complex.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import platform import pytest @@ -31,7 +29,7 @@ platform_skip = pytest.mark.skipif(xfail_complex_tests, -class TestCexp(object): +class TestCexp: def test_simple(self): check = check_complex_value f = np.exp @@ -131,7 +129,7 @@ class TestCexp(object): check(f, np.nan, 0, np.nan, 0) -class TestClog(object): +class TestClog: def test_simple(self): x = np.array([1+0j, 1+2j]) y_r = np.log(np.abs(x)) + 1j * np.angle(x) @@ -276,7 +274,7 @@ class TestClog(object): assert_almost_equal(np.log(xa[i].conj()), ya[i].conj()) -class TestCsqrt(object): +class TestCsqrt: def test_simple(self): # sqrt(1) @@ -356,7 +354,7 @@ class TestCsqrt(object): # XXX: check for conj(csqrt(z)) == csqrt(conj(z)) (need to fix branch # cuts first) -class TestCpow(object): +class TestCpow: def setup(self): self.olderr = np.seterr(invalid='ignore') @@ -396,7 +394,7 @@ class TestCpow(object): for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i) -class TestCabs(object): +class TestCabs: def setup(self): self.olderr = np.seterr(invalid='ignore') @@ -458,7 +456,7 @@ class TestCabs(object): ref = g(x[i], y[i]) check_real_value(f, x[i], y[i], ref) -class TestCarg(object): +class TestCarg: def test_simple(self): check_real_value(ncu._arg, 1, 0, 0, False) check_real_value(ncu._arg, 0, 1, 0.5*np.pi, False) diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py index 2ffd8801b..b8ec56116 100644 --- a/numpy/core/tests/test_unicode.py +++ b/numpy/core/tests/test_unicode.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import numpy as np @@ -67,7 +65,7 @@ def test_string_cast(): # Creation tests ############################################################ -class CreateZeros(object): +class CreateZeros: """Check the creation of zero-valued arrays""" def content_check(self, ua, ua_scalar, nbytes): @@ -119,7 +117,7 @@ class TestCreateZeros_1009(CreateZeros): ulen = 1009 -class CreateValues(object): +class CreateValues: """Check the creation of unicode arrays with values""" def content_check(self, ua, ua_scalar, nbytes): @@ -204,7 +202,7 @@ class TestCreateValues_1009_UCS4(CreateValues): # Assignment tests ############################################################ -class AssignValues(object): +class AssignValues: """Check the assignment of unicode arrays with values""" def content_check(self, ua, ua_scalar, nbytes): @@ -294,7 +292,7 @@ class TestAssignValues_1009_UCS4(AssignValues): # Byteorder tests ############################################################ -class ByteorderValues(object): +class ByteorderValues: """Check the byteorder of unicode arrays in round-trip conversions""" def test_values0D(self): diff --git a/numpy/core/umath_tests.py b/numpy/core/umath_tests.py index 28e325b98..90ab17e67 100644 --- a/numpy/core/umath_tests.py +++ b/numpy/core/umath_tests.py @@ -2,8 +2,6 @@ Shim for _umath_tests to allow a deprecation period for the new name. """ -from __future__ import division, absolute_import, print_function - import warnings # 2018-04-04, numpy 1.15.0 diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index 58f3ef9d3..ec3cdc33d 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -49,8 +49,6 @@ Then, we're ready to call ``foo_func``: >>> _lib.foo_func(out, len(out)) #doctest: +SKIP """ -from __future__ import division, absolute_import, print_function - __all__ = ['load_library', 'ndpointer', 'ctypes_load_library', 'c_intp', 'as_ctypes', 'as_array'] diff --git a/numpy/distutils/__init__.py b/numpy/distutils/__init__.py index 8dbb63b28..79974d1c2 100644 --- a/numpy/distutils/__init__.py +++ b/numpy/distutils/__init__.py @@ -19,8 +19,6 @@ LAPACK, and for setting include paths and similar build options, please see """ -from __future__ import division, absolute_import, print_function - # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. from . import ccompiler diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index 45d3f8b34..5e3cd0e74 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import re import sys @@ -531,11 +529,6 @@ def CCompiler_customize(self, dist, need_cxx=0): 'g++' in self.compiler[0] or 'clang' in self.compiler[0]): self._auto_depends = True - if 'gcc' in self.compiler[0] and not need_cxx: - # add std=c99 flag for gcc - # TODO: does this need to be more specific? - self.compiler.append('-std=c99') - self.compiler_so.append('-std=c99') elif os.name == 'posix': import tempfile import shutil diff --git a/numpy/distutils/command/__init__.py b/numpy/distutils/command/__init__.py index 76a260072..3ba501de0 100644 --- a/numpy/distutils/command/__init__.py +++ b/numpy/distutils/command/__init__.py @@ -4,8 +4,6 @@ Package containing implementation of all the standard Distutils commands. """ -from __future__ import division, absolute_import, print_function - def test_na_writable_attributes_deletion(): a = np.NA(2) attr = ['payload', 'dtype'] diff --git a/numpy/distutils/command/autodist.py b/numpy/distutils/command/autodist.py index 9c98b84d8..1475a5e24 100644 --- a/numpy/distutils/command/autodist.py +++ b/numpy/distutils/command/autodist.py @@ -1,8 +1,6 @@ """This module implements additional tests ala autoconf which can be useful. """ -from __future__ import division, absolute_import, print_function - import textwrap # We put them here since they could be easily reused outside numpy.distutils diff --git a/numpy/distutils/command/bdist_rpm.py b/numpy/distutils/command/bdist_rpm.py index 3e52a503b..682e7a8eb 100644 --- a/numpy/distutils/command/bdist_rpm.py +++ b/numpy/distutils/command/bdist_rpm.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys if 'setuptools' in sys.modules: diff --git a/numpy/distutils/command/build.py b/numpy/distutils/command/build.py index 5a9da1217..a156a7c6e 100644 --- a/numpy/distutils/command/build.py +++ b/numpy/distutils/command/build.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys from distutils.command.build import build as old_build diff --git a/numpy/distutils/command/build_clib.py b/numpy/distutils/command/build_clib.py index 13edf0717..1b4666888 100644 --- a/numpy/distutils/command/build_clib.py +++ b/numpy/distutils/command/build_clib.py @@ -1,7 +1,5 @@ """ Modified version of build_clib that handles fortran source files. """ -from __future__ import division, absolute_import, print_function - import os from glob import glob import shutil diff --git a/numpy/distutils/command/build_ext.py b/numpy/distutils/command/build_ext.py index cd9b1c6f1..a0da83ff4 100644 --- a/numpy/distutils/command/build_ext.py +++ b/numpy/distutils/command/build_ext.py @@ -1,8 +1,6 @@ """ Modified version of build_ext that handles fortran source files. """ -from __future__ import division, absolute_import, print_function - import os import subprocess from glob import glob diff --git a/numpy/distutils/command/build_py.py b/numpy/distutils/command/build_py.py index 54dcde435..d30dc5bf4 100644 --- a/numpy/distutils/command/build_py.py +++ b/numpy/distutils/command/build_py.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from distutils.command.build_py import build_py as old_build_py from numpy.distutils.misc_util import is_string diff --git a/numpy/distutils/command/build_scripts.py b/numpy/distutils/command/build_scripts.py index c8b25fc71..d5cadb274 100644 --- a/numpy/distutils/command/build_scripts.py +++ b/numpy/distutils/command/build_scripts.py @@ -1,8 +1,6 @@ """ Modified version of build_scripts that handles building scripts from functions. """ -from __future__ import division, absolute_import, print_function - from distutils.command.build_scripts import build_scripts as old_build_scripts from numpy.distutils import log from numpy.distutils.misc_util import is_string diff --git a/numpy/distutils/command/build_src.py b/numpy/distutils/command/build_src.py index 3e0522c5f..303d6197c 100644 --- a/numpy/distutils/command/build_src.py +++ b/numpy/distutils/command/build_src.py @@ -1,7 +1,5 @@ """ Build swig and f2py sources. """ -from __future__ import division, absolute_import, print_function - import os import re import sys diff --git a/numpy/distutils/command/config.py b/numpy/distutils/command/config.py index cd9c0ca44..2c833aad7 100644 --- a/numpy/distutils/command/config.py +++ b/numpy/distutils/command/config.py @@ -2,8 +2,6 @@ # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson -from __future__ import division, absolute_import, print_function - import os, signal import warnings import sys @@ -493,7 +491,7 @@ class config(old_config): self._clean() return exitcode, output -class GrabStdout(object): +class GrabStdout: def __init__(self): self.sys_stdout = sys.stdout diff --git a/numpy/distutils/command/config_compiler.py b/numpy/distutils/command/config_compiler.py index bf170063e..44265bfcc 100644 --- a/numpy/distutils/command/config_compiler.py +++ b/numpy/distutils/command/config_compiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from distutils.core import Command from numpy.distutils import log diff --git a/numpy/distutils/command/develop.py b/numpy/distutils/command/develop.py index 1410ab2a0..af24baf2e 100644 --- a/numpy/distutils/command/develop.py +++ b/numpy/distutils/command/develop.py @@ -3,8 +3,6 @@ generated files (from build_src or build_scripts) are properly converted to real files with filenames. """ -from __future__ import division, absolute_import, print_function - from setuptools.command.develop import develop as old_develop class develop(old_develop): diff --git a/numpy/distutils/command/egg_info.py b/numpy/distutils/command/egg_info.py index 18673ece7..14c62b4d1 100644 --- a/numpy/distutils/command/egg_info.py +++ b/numpy/distutils/command/egg_info.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys from setuptools.command.egg_info import egg_info as _egg_info diff --git a/numpy/distutils/command/install.py b/numpy/distutils/command/install.py index c74ae9446..2eff2d145 100644 --- a/numpy/distutils/command/install.py +++ b/numpy/distutils/command/install.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod diff --git a/numpy/distutils/command/install_clib.py b/numpy/distutils/command/install_clib.py index 6a73f7e33..aa2e5594c 100644 --- a/numpy/distutils/command/install_clib.py +++ b/numpy/distutils/command/install_clib.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from distutils.core import Command from distutils.ccompiler import new_compiler diff --git a/numpy/distutils/command/install_data.py b/numpy/distutils/command/install_data.py index 996cf7e40..0a2e68ae1 100644 --- a/numpy/distutils/command/install_data.py +++ b/numpy/distutils/command/install_data.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys have_setuptools = ('setuptools' in sys.modules) diff --git a/numpy/distutils/command/install_headers.py b/numpy/distutils/command/install_headers.py index f3f58aa28..bb4ad563b 100644 --- a/numpy/distutils/command/install_headers.py +++ b/numpy/distutils/command/install_headers.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from distutils.command.install_headers import install_headers as old_install_headers diff --git a/numpy/distutils/command/sdist.py b/numpy/distutils/command/sdist.py index bfaab1c8f..e34193883 100644 --- a/numpy/distutils/command/sdist.py +++ b/numpy/distutils/command/sdist.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys if 'setuptools' in sys.modules: from setuptools.command.sdist import sdist as old_sdist diff --git a/numpy/distutils/conv_template.py b/numpy/distutils/conv_template.py index f3f6cf5ce..ec5a84a68 100644 --- a/numpy/distutils/conv_template.py +++ b/numpy/distutils/conv_template.py @@ -78,8 +78,6 @@ Example: 3, 3, jim """ -from __future__ import division, absolute_import, print_function - __all__ = ['process_str', 'process_file'] diff --git a/numpy/distutils/core.py b/numpy/distutils/core.py index 70cc37caa..a78bbf484 100644 --- a/numpy/distutils/core.py +++ b/numpy/distutils/core.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys from distutils.core import * diff --git a/numpy/distutils/cpuinfo.py b/numpy/distutils/cpuinfo.py index 14b15a289..efea90113 100644 --- a/numpy/distutils/cpuinfo.py +++ b/numpy/distutils/cpuinfo.py @@ -12,8 +12,6 @@ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __all__ = ['cpu'] import sys, re, types @@ -64,7 +62,7 @@ def key_value_from_command(cmd, sep, successful_status=(0,), d[l[0]] = l[1] return d -class CPUInfoBase(object): +class CPUInfoBase: """Holds CPU information and provides methods for requiring the availability of various CPU features. """ diff --git a/numpy/distutils/exec_command.py b/numpy/distutils/exec_command.py index 712f22666..d35b4f898 100644 --- a/numpy/distutils/exec_command.py +++ b/numpy/distutils/exec_command.py @@ -49,8 +49,6 @@ Known bugs: because the messages are lost at some point. """ -from __future__ import division, absolute_import, print_function - __all__ = ['exec_command', 'find_executable'] import os diff --git a/numpy/distutils/extension.py b/numpy/distutils/extension.py index 872bd5362..3b5c3db35 100644 --- a/numpy/distutils/extension.py +++ b/numpy/distutils/extension.py @@ -6,8 +6,6 @@ modules in setup scripts. Overridden to support f2py. """ -from __future__ import division, absolute_import, print_function - import sys import re from distutils.extension import Extension as old_Extension diff --git a/numpy/distutils/fcompiler/__init__.py b/numpy/distutils/fcompiler/__init__.py index 81a3b96c9..a88b0d713 100644 --- a/numpy/distutils/fcompiler/__init__.py +++ b/numpy/distutils/fcompiler/__init__.py @@ -13,8 +13,6 @@ should be a list. But note that FCompiler.executables is actually a dictionary of commands. """ -from __future__ import division, absolute_import, print_function - __all__ = ['FCompiler', 'new_fcompiler', 'show_fcompilers', 'dummy_fortran_file'] diff --git a/numpy/distutils/fcompiler/absoft.py b/numpy/distutils/fcompiler/absoft.py index d14fee0e1..efe3a4cb5 100644 --- a/numpy/distutils/fcompiler/absoft.py +++ b/numpy/distutils/fcompiler/absoft.py @@ -5,8 +5,6 @@ # Notes: # - when using -g77 then use -DUNDERSCORE_G77 to compile f2py # generated extension modules (works for f2py v2.45.241_1936 and up) -from __future__ import division, absolute_import, print_function - import os from numpy.distutils.cpuinfo import cpu diff --git a/numpy/distutils/fcompiler/compaq.py b/numpy/distutils/fcompiler/compaq.py index 51ad20d01..6ce590c7c 100644 --- a/numpy/distutils/fcompiler/compaq.py +++ b/numpy/distutils/fcompiler/compaq.py @@ -1,7 +1,5 @@ #http://www.compaq.com/fortran/docs/ -from __future__ import division, absolute_import, print_function - import os import sys diff --git a/numpy/distutils/fcompiler/environment.py b/numpy/distutils/fcompiler/environment.py index bb362d483..ae5fc404a 100644 --- a/numpy/distutils/fcompiler/environment.py +++ b/numpy/distutils/fcompiler/environment.py @@ -1,12 +1,10 @@ -from __future__ import division, absolute_import, print_function - import os import warnings from distutils.dist import Distribution __metaclass__ = type -class EnvironmentConfig(object): +class EnvironmentConfig: def __init__(self, distutils_section='ALL', **kw): self._distutils_section = distutils_section self._conf_keys = kw diff --git a/numpy/distutils/fcompiler/g95.py b/numpy/distutils/fcompiler/g95.py index e7c659b33..e109a972a 100644 --- a/numpy/distutils/fcompiler/g95.py +++ b/numpy/distutils/fcompiler/g95.py @@ -1,6 +1,4 @@ # http://g95.sourceforge.net/ -from __future__ import division, absolute_import, print_function - from numpy.distutils.fcompiler import FCompiler compilers = ['G95FCompiler'] diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index 1c71dd2bd..4fc9f33ff 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import re import os import sys diff --git a/numpy/distutils/fcompiler/hpux.py b/numpy/distutils/fcompiler/hpux.py index 51bad548a..09e6483bf 100644 --- a/numpy/distutils/fcompiler/hpux.py +++ b/numpy/distutils/fcompiler/hpux.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.distutils.fcompiler import FCompiler compilers = ['HPUXFCompiler'] diff --git a/numpy/distutils/fcompiler/ibm.py b/numpy/distutils/fcompiler/ibm.py index 70d2132e1..4a83682e5 100644 --- a/numpy/distutils/fcompiler/ibm.py +++ b/numpy/distutils/fcompiler/ibm.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import re import sys diff --git a/numpy/distutils/fcompiler/intel.py b/numpy/distutils/fcompiler/intel.py index 51f681274..d84f38c76 100644 --- a/numpy/distutils/fcompiler/intel.py +++ b/numpy/distutils/fcompiler/intel.py @@ -1,6 +1,4 @@ # http://developer.intel.com/software/products/compilers/flin/ -from __future__ import division, absolute_import, print_function - import sys from numpy.distutils.ccompiler import simple_version_match diff --git a/numpy/distutils/fcompiler/lahey.py b/numpy/distutils/fcompiler/lahey.py index 1beb662f4..e92583826 100644 --- a/numpy/distutils/fcompiler/lahey.py +++ b/numpy/distutils/fcompiler/lahey.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/mips.py b/numpy/distutils/fcompiler/mips.py index da337b24a..a09738045 100644 --- a/numpy/distutils/fcompiler/mips.py +++ b/numpy/distutils/fcompiler/mips.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/nag.py b/numpy/distutils/fcompiler/nag.py index cb71d548c..908e724e6 100644 --- a/numpy/distutils/fcompiler/nag.py +++ b/numpy/distutils/fcompiler/nag.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import re from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/none.py b/numpy/distutils/fcompiler/none.py index bdeea1560..ef411fffc 100644 --- a/numpy/distutils/fcompiler/none.py +++ b/numpy/distutils/fcompiler/none.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.distutils.fcompiler import FCompiler from numpy.distutils import customized_fcompiler diff --git a/numpy/distutils/fcompiler/pathf95.py b/numpy/distutils/fcompiler/pathf95.py index 5de86f63a..0768cb12e 100644 --- a/numpy/distutils/fcompiler/pathf95.py +++ b/numpy/distutils/fcompiler/pathf95.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.distutils.fcompiler import FCompiler compilers = ['PathScaleFCompiler'] diff --git a/numpy/distutils/fcompiler/pg.py b/numpy/distutils/fcompiler/pg.py index 9c51947fd..77bc4f08e 100644 --- a/numpy/distutils/fcompiler/pg.py +++ b/numpy/distutils/fcompiler/pg.py @@ -1,6 +1,4 @@ # http://www.pgroup.com -from __future__ import division, absolute_import, print_function - import sys from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file diff --git a/numpy/distutils/fcompiler/sun.py b/numpy/distutils/fcompiler/sun.py index 561ea854f..d039f0b25 100644 --- a/numpy/distutils/fcompiler/sun.py +++ b/numpy/distutils/fcompiler/sun.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/vast.py b/numpy/distutils/fcompiler/vast.py index adc1591bd..92a1647ba 100644 --- a/numpy/distutils/fcompiler/vast.py +++ b/numpy/distutils/fcompiler/vast.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from numpy.distutils.fcompiler.gnu import GnuFCompiler diff --git a/numpy/distutils/from_template.py b/numpy/distutils/from_template.py index c5c1163c6..b4dd05b5e 100644 --- a/numpy/distutils/from_template.py +++ b/numpy/distutils/from_template.py @@ -45,8 +45,6 @@ process_file(filename) <ctypereal=float,double,\\0,\\1> """ -from __future__ import division, absolute_import, print_function - __all__ = ['process_str', 'process_file'] import os diff --git a/numpy/distutils/intelccompiler.py b/numpy/distutils/intelccompiler.py index 3386775ee..0388ad577 100644 --- a/numpy/distutils/intelccompiler.py +++ b/numpy/distutils/intelccompiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import platform from distutils.unixccompiler import UnixCCompiler diff --git a/numpy/distutils/lib2def.py b/numpy/distutils/lib2def.py index 2d013a1e3..c6d445d09 100644 --- a/numpy/distutils/lib2def.py +++ b/numpy/distutils/lib2def.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import re import sys import subprocess diff --git a/numpy/distutils/line_endings.py b/numpy/distutils/line_endings.py index fe8fd1b0f..92a84e56a 100644 --- a/numpy/distutils/line_endings.py +++ b/numpy/distutils/line_endings.py @@ -1,8 +1,6 @@ """ Functions for converting from DOS to UNIX line endings """ -from __future__ import division, absolute_import, print_function - import sys, re, os def dos2unix(file): diff --git a/numpy/distutils/log.py b/numpy/distutils/log.py index ff7de86b1..ec1100b1b 100644 --- a/numpy/distutils/log.py +++ b/numpy/distutils/log.py @@ -1,6 +1,4 @@ # Colored log, requires Python 2.3 or up. -from __future__ import division, absolute_import, print_function - import sys from distutils.log import * from distutils.log import Log as old_Log diff --git a/numpy/distutils/mingw32ccompiler.py b/numpy/distutils/mingw32ccompiler.py index 075858cfe..e2cd1c19b 100644 --- a/numpy/distutils/mingw32ccompiler.py +++ b/numpy/distutils/mingw32ccompiler.py @@ -7,8 +7,6 @@ Support code for building Python extensions on Windows. # 3. Force windows to use g77 """ -from __future__ import division, absolute_import, print_function - import os import sys import subprocess diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index ac2103a6b..eec8d56a3 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import re import sys @@ -50,7 +48,7 @@ __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info', 'get_num_build_jobs'] -class InstallableLib(object): +class InstallableLib: """ Container to hold information on an installable library. @@ -727,7 +725,7 @@ def get_frame(level=0): ###################### -class Configuration(object): +class Configuration: _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', 'libraries', 'headers', 'scripts', 'py_modules', diff --git a/numpy/distutils/msvc9compiler.py b/numpy/distutils/msvc9compiler.py index e9cc334a5..68239495d 100644 --- a/numpy/distutils/msvc9compiler.py +++ b/numpy/distutils/msvc9compiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler diff --git a/numpy/distutils/msvccompiler.py b/numpy/distutils/msvccompiler.py index 0cb4bf979..681a254b8 100644 --- a/numpy/distutils/msvccompiler.py +++ b/numpy/distutils/msvccompiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler diff --git a/numpy/distutils/npy_pkg_config.py b/numpy/distutils/npy_pkg_config.py index 48584b4c4..47965b4ae 100644 --- a/numpy/distutils/npy_pkg_config.py +++ b/numpy/distutils/npy_pkg_config.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import re import os @@ -78,7 +76,7 @@ def parse_flags(line): def _escape_backslash(val): return val.replace('\\', '\\\\') -class LibraryInfo(object): +class LibraryInfo: """ Object containing build information about a library. @@ -150,7 +148,7 @@ class LibraryInfo(object): return "\n".join(m) -class VariableSet(object): +class VariableSet: """ Container object for the variables defined in a config file. diff --git a/numpy/distutils/numpy_distribution.py b/numpy/distutils/numpy_distribution.py index 6ae19d16b..ea8182659 100644 --- a/numpy/distutils/numpy_distribution.py +++ b/numpy/distutils/numpy_distribution.py @@ -1,6 +1,4 @@ # XXX: Handle setuptools ? -from __future__ import division, absolute_import, print_function - from distutils.core import Distribution # This class is used because we add new files (sconscripts, and so on) with the diff --git a/numpy/distutils/pathccompiler.py b/numpy/distutils/pathccompiler.py index fc9872db3..48051810e 100644 --- a/numpy/distutils/pathccompiler.py +++ b/numpy/distutils/pathccompiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from distutils.unixccompiler import UnixCCompiler class PathScaleCCompiler(UnixCCompiler): diff --git a/numpy/distutils/setup.py b/numpy/distutils/setup.py index 82a53bd08..415d2adeb 100644 --- a/numpy/distutils/setup.py +++ b/numpy/distutils/setup.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('distutils', parent_package, top_path) diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index bc311f55a..508aeefc5 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -128,8 +128,6 @@ this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. """ -from __future__ import division, absolute_import, print_function - import sys import os import re @@ -581,7 +579,7 @@ class UmfpackNotFoundError(NotFoundError): the UMFPACK environment variable.""" -class system_info(object): +class system_info: """ get_info() is the only public method. Don't use others. """ diff --git a/numpy/distutils/tests/test_ccompiler.py b/numpy/distutils/tests/test_ccompiler.py deleted file mode 100644 index 8b4a56b79..000000000 --- a/numpy/distutils/tests/test_ccompiler.py +++ /dev/null @@ -1,24 +0,0 @@ -from __future__ import division, absolute_import, print_function - -from distutils.ccompiler import new_compiler - -from numpy.distutils.numpy_distribution import NumpyDistribution - -def test_ccompiler(): - ''' - scikit-image/scikit-image issue 4369 - We unconditionally add ``-std-c99`` to the gcc compiler in order - to support c99 with very old gcc compilers. However the same call - is used to get the flags for the c++ compiler, just with a kwarg. - Make sure in this case, where it would not be legal, the option is **not** added - ''' - dist = NumpyDistribution() - compiler = new_compiler() - compiler.customize(dist) - if hasattr(compiler, 'compiler') and 'gcc' in compiler.compiler[0]: - assert 'c99' in ' '.join(compiler.compiler) - - compiler = new_compiler() - compiler.customize(dist, need_cxx=True) - if hasattr(compiler, 'compiler') and 'gcc' in compiler.compiler[0]: - assert 'c99' not in ' '.join(compiler.compiler) diff --git a/numpy/distutils/tests/test_exec_command.py b/numpy/distutils/tests/test_exec_command.py index 37912f5ba..2ac0a6308 100644 --- a/numpy/distutils/tests/test_exec_command.py +++ b/numpy/distutils/tests/test_exec_command.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys from tempfile import TemporaryFile @@ -15,7 +13,7 @@ if sys.version_info[0] >= 3: else: from StringIO import StringIO -class redirect_stdout(object): +class redirect_stdout: """Context manager to redirect stdout for exec_command test.""" def __init__(self, stdout=None): self._stdout = stdout or sys.stdout @@ -30,7 +28,7 @@ class redirect_stdout(object): # note: closing sys.stdout won't close it. self._stdout.close() -class redirect_stderr(object): +class redirect_stderr: """Context manager to redirect stderr for exec_command test.""" def __init__(self, stderr=None): self._stderr = stderr or sys.stderr @@ -45,7 +43,7 @@ class redirect_stderr(object): # note: closing sys.stderr won't close it. self._stderr.close() -class emulate_nonposix(object): +class emulate_nonposix: """Context manager to emulate os.name != 'posix' """ def __init__(self, osname='non-posix'): self._new_name = osname @@ -98,7 +96,7 @@ def test_exec_command_stderr(): exec_command.exec_command("cd '.'") -class TestExecCommand(object): +class TestExecCommand: def setup(self): self.pyexe = get_pythonexe() diff --git a/numpy/distutils/tests/test_fcompiler.py b/numpy/distutils/tests/test_fcompiler.py index 6d245fbd4..c559becf8 100644 --- a/numpy/distutils/tests/test_fcompiler.py +++ b/numpy/distutils/tests/test_fcompiler.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest from numpy.testing import assert_, suppress_warnings diff --git a/numpy/distutils/tests/test_fcompiler_gnu.py b/numpy/distutils/tests/test_fcompiler_gnu.py index 49208aace..0817ae58c 100644 --- a/numpy/distutils/tests/test_fcompiler_gnu.py +++ b/numpy/distutils/tests/test_fcompiler_gnu.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.testing import assert_ import numpy.distutils.fcompiler @@ -30,7 +28,7 @@ gfortran_version_strings = [ ('GNU Fortran (crosstool-NG 8a21ab48) 7.2.0', '7.2.0') ] -class TestG77Versions(object): +class TestG77Versions: def test_g77_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu') for vs, version in g77_version_strings: @@ -43,7 +41,7 @@ class TestG77Versions(object): v = fc.version_match(vs) assert_(v is None, (vs, v)) -class TestGFortranVersions(object): +class TestGFortranVersions: def test_gfortran_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95') for vs, version in gfortran_version_strings: diff --git a/numpy/distutils/tests/test_fcompiler_intel.py b/numpy/distutils/tests/test_fcompiler_intel.py index 5e014bada..45c9cdac1 100644 --- a/numpy/distutils/tests/test_fcompiler_intel.py +++ b/numpy/distutils/tests/test_fcompiler_intel.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy.distutils.fcompiler from numpy.testing import assert_ @@ -16,7 +14,7 @@ intel_64bit_version_strings = [ "running on Intel(R) 64, Version 11.1", '11.1') ] -class TestIntelFCompilerVersions(object): +class TestIntelFCompilerVersions: def test_32bit_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intel') for vs, version in intel_32bit_version_strings: @@ -24,7 +22,7 @@ class TestIntelFCompilerVersions(object): assert_(v == version) -class TestIntelEM64TFCompilerVersions(object): +class TestIntelEM64TFCompilerVersions: def test_64bit_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intelem') for vs, version in intel_64bit_version_strings: diff --git a/numpy/distutils/tests/test_fcompiler_nagfor.py b/numpy/distutils/tests/test_fcompiler_nagfor.py index 1c936056a..2e04f5266 100644 --- a/numpy/distutils/tests/test_fcompiler_nagfor.py +++ b/numpy/distutils/tests/test_fcompiler_nagfor.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from numpy.testing import assert_ import numpy.distutils.fcompiler @@ -16,7 +14,7 @@ nag_version_strings = [('nagfor', 'NAG Fortran Compiler Release ' '431,435,437,446,459-460,463,472,494,496,503,508,' '511,517,529,555,557,565)', '5.1')] -class TestNagFCompilerVersions(object): +class TestNagFCompilerVersions: def test_version_match(self): for comp, vs, version in nag_version_strings: fc = numpy.distutils.fcompiler.new_fcompiler(compiler=comp) diff --git a/numpy/distutils/tests/test_misc_util.py b/numpy/distutils/tests/test_misc_util.py index 3e239cf48..605c80483 100644 --- a/numpy/distutils/tests/test_misc_util.py +++ b/numpy/distutils/tests/test_misc_util.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from os.path import join, sep, dirname from numpy.distutils.misc_util import ( @@ -11,7 +9,7 @@ from numpy.testing import ( ajoin = lambda *paths: join(*((sep,)+paths)) -class TestAppendpath(object): +class TestAppendpath: def test_1(self): assert_equal(appendpath('prefix', 'name'), join('prefix', 'name')) @@ -35,7 +33,7 @@ class TestAppendpath(object): assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sub/sup/name'), ajoin('prefix', 'sub', 'sub2', 'sup', 'name')) -class TestMinrelpath(object): +class TestMinrelpath: def test_1(self): n = lambda path: path.replace('/', sep) @@ -49,7 +47,7 @@ class TestMinrelpath(object): assert_equal(minrelpath(n('.././..')), n('../..')) assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd')) -class TestGpaths(object): +class TestGpaths: def test_gpaths(self): local_path = minrelpath(join(dirname(__file__), '..')) @@ -58,7 +56,7 @@ class TestGpaths(object): f = gpaths('system_info.py', local_path) assert_(join(local_path, 'system_info.py') == f[0], repr(f)) -class TestSharedExtension(object): +class TestSharedExtension: def test_get_shared_lib_extension(self): import sys diff --git a/numpy/distutils/tests/test_npy_pkg_config.py b/numpy/distutils/tests/test_npy_pkg_config.py index 537e16e90..b287ebe2e 100644 --- a/numpy/distutils/tests/test_npy_pkg_config.py +++ b/numpy/distutils/tests/test_npy_pkg_config.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os from numpy.distutils.npy_pkg_config import read_config, parse_flags @@ -36,7 +34,7 @@ libs = -L${libdir} simple_variable_d = {'cflags': '-I/foo/bar/include', 'libflags': '-L/foo/bar/lib', 'version': '0.1', 'name': 'foo'} -class TestLibraryInfo(object): +class TestLibraryInfo: def test_simple(self): with temppath('foo.ini') as path: with open(path, 'w') as f: @@ -63,7 +61,7 @@ class TestLibraryInfo(object): out.vars['prefix'] = '/Users/david' assert_(out.cflags() == '-I/Users/david/include') -class TestParseFlags(object): +class TestParseFlags: def test_simple_cflags(self): d = parse_flags("-I/usr/include") assert_(d['include_dirs'] == ['/usr/include']) diff --git a/numpy/distutils/tests/test_shell_utils.py b/numpy/distutils/tests/test_shell_utils.py index a0344244f..754609a5d 100644 --- a/numpy/distutils/tests/test_shell_utils.py +++ b/numpy/distutils/tests/test_shell_utils.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest import subprocess import os diff --git a/numpy/distutils/tests/test_system_info.py b/numpy/distutils/tests/test_system_info.py index 3c7638960..c40cdb7db 100644 --- a/numpy/distutils/tests/test_system_info.py +++ b/numpy/distutils/tests/test_system_info.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - import os import shutil import pytest @@ -130,7 +128,7 @@ class DuplicateOptionInfo(_system_info): section = 'duplicate_options' -class TestSystemInfoReading(object): +class TestSystemInfoReading: def setup(self): """ Create the libraries """ diff --git a/numpy/distutils/unixccompiler.py b/numpy/distutils/unixccompiler.py index 0174f0d05..9a4d3ba52 100644 --- a/numpy/distutils/unixccompiler.py +++ b/numpy/distutils/unixccompiler.py @@ -2,8 +2,6 @@ unixccompiler - can handle very long argument lists for ar. """ -from __future__ import division, absolute_import, print_function - import os from distutils.errors import DistutilsExecError, CompileError diff --git a/numpy/doc/__init__.py b/numpy/doc/__init__.py index b6f1fa71c..8a944fecd 100644 --- a/numpy/doc/__init__.py +++ b/numpy/doc/__init__.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os ref_dir = os.path.join(os.path.dirname(__file__)) diff --git a/numpy/doc/basics.py b/numpy/doc/basics.py index c05f347a1..635c1b1b8 100644 --- a/numpy/doc/basics.py +++ b/numpy/doc/basics.py @@ -339,4 +339,3 @@ be useful to test your code with the value ``1 + np.finfo(np.longdouble).eps``. """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/broadcasting.py b/numpy/doc/broadcasting.py index cb548a0d0..63975e6a9 100644 --- a/numpy/doc/broadcasting.py +++ b/numpy/doc/broadcasting.py @@ -178,4 +178,3 @@ making it a two-dimensional ``4x1`` array. Combining the ``4x1`` array with ``b``, which has shape ``(3,)``, yields a ``4x3`` array. """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/byteswapping.py b/numpy/doc/byteswapping.py index 7a749c8d5..fe9461977 100644 --- a/numpy/doc/byteswapping.py +++ b/numpy/doc/byteswapping.py @@ -153,4 +153,3 @@ can be achieved with the ndarray astype method: False """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/constants.py b/numpy/doc/constants.py index 72793e44d..96813b66c 100644 --- a/numpy/doc/constants.py +++ b/numpy/doc/constants.py @@ -13,8 +13,6 @@ NumPy includes several constants: # # Note: the docstring is autogenerated. # -from __future__ import division, absolute_import, print_function - import textwrap, re # Maintain same format as in numpy.add_newdocs diff --git a/numpy/doc/creation.py b/numpy/doc/creation.py index 9ebe938be..067f8bb33 100644 --- a/numpy/doc/creation.py +++ b/numpy/doc/creation.py @@ -141,4 +141,3 @@ random values, and some utility functions to generate special matrices (e.g. diagonal). """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/glossary.py b/numpy/doc/glossary.py index 7d1c9a1d5..6d2e0010f 100644 --- a/numpy/doc/glossary.py +++ b/numpy/doc/glossary.py @@ -182,7 +182,7 @@ Glossary instance A class definition gives the blueprint for constructing an object:: - >>> class House(object): + >>> class House: ... wall_colour = 'white' Yet, we have to *build* a house before it exists:: @@ -336,7 +336,7 @@ Glossary Often seen in method signatures, ``self`` refers to the instance of the associated class. For example: - >>> class Paintbrush(object): + >>> class Paintbrush: ... color = 'blue' ... ... def paint(self): @@ -473,4 +473,3 @@ Glossary and f2py (which wraps Fortran). """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/indexing.py b/numpy/doc/indexing.py index 676015668..aa84e2b11 100644 --- a/numpy/doc/indexing.py +++ b/numpy/doc/indexing.py @@ -446,4 +446,3 @@ converted to an array as a list would be. As an example: :: 40 """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/internals.py b/numpy/doc/internals.py index a14fee7c2..6718f1108 100644 --- a/numpy/doc/internals.py +++ b/numpy/doc/internals.py @@ -160,4 +160,3 @@ when accessing elements of an array. Granted, it goes against the grain, but it is more in line with Python semantics and the natural order of the data. """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py index a76abe164..fc1c4cd01 100644 --- a/numpy/doc/misc.py +++ b/numpy/doc/misc.py @@ -224,4 +224,3 @@ Interfacing to C++: 5) SIP (used mainly in PyQT) """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/structured_arrays.py b/numpy/doc/structured_arrays.py index 1343d2adc..72990cf89 100644 --- a/numpy/doc/structured_arrays.py +++ b/numpy/doc/structured_arrays.py @@ -644,4 +644,3 @@ attribute takes precedence. Such fields will be inaccessible by attribute but will still be accessible by index. """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/subclassing.py b/numpy/doc/subclassing.py index d0685328e..bfc01bdc6 100644 --- a/numpy/doc/subclassing.py +++ b/numpy/doc/subclassing.py @@ -114,7 +114,7 @@ For example, consider the following Python code: .. testcode:: - class C(object): + class C: def __new__(cls, *args): print('Cls in __new__:', cls) print('Args in __new__:', args) @@ -750,4 +750,3 @@ This object is now compatible with ``np.sum`` again because any extraneous argum ``**unused_kwargs`` parameter. """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/doc/ufuncs.py b/numpy/doc/ufuncs.py index df2c455ec..eecc15083 100644 --- a/numpy/doc/ufuncs.py +++ b/numpy/doc/ufuncs.py @@ -135,4 +135,3 @@ results in an error. There are two alternatives: a convenient way to apply these operators. """ -from __future__ import division, absolute_import, print_function diff --git a/numpy/dual.py b/numpy/dual.py index 651e845bb..92afec52d 100644 --- a/numpy/dual.py +++ b/numpy/dual.py @@ -10,8 +10,6 @@ NumPy. .. _Scipy : https://www.scipy.org """ -from __future__ import division, absolute_import, print_function - # This module should be used for functions both in numpy and scipy if # you want to use the numpy version if available but the scipy version # otherwise. diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py index 42e3632fd..13ffef6fc 100644 --- a/numpy/f2py/__init__.py +++ b/numpy/f2py/__init__.py @@ -2,8 +2,6 @@ """Fortran to Python Interface Generator. """ -from __future__ import division, absolute_import, print_function - __all__ = ['run_main', 'compile', 'f2py_testing'] import sys diff --git a/numpy/f2py/__main__.py b/numpy/f2py/__main__.py index 708f7f362..c6115070e 100644 --- a/numpy/f2py/__main__.py +++ b/numpy/f2py/__main__.py @@ -1,6 +1,4 @@ # See http://cens.ioc.ee/projects/f2py2e/ -from __future__ import division, print_function - from numpy.f2py.f2py2e import main main() diff --git a/numpy/f2py/__version__.py b/numpy/f2py/__version__.py index 49a2199bf..104c2e1a8 100644 --- a/numpy/f2py/__version__.py +++ b/numpy/f2py/__version__.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - major = 2 try: diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py index 404bdbd2d..31802621e 100644 --- a/numpy/f2py/auxfuncs.py +++ b/numpy/f2py/auxfuncs.py @@ -14,8 +14,6 @@ $Date: 2005/07/24 19:01:55 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - import pprint import sys import types @@ -552,7 +550,7 @@ class F2PYError(Exception): pass -class throw_error(object): +class throw_error: def __init__(self, mess): self.mess = mess diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py index 917a4a9a3..6f9ff7bc6 100644 --- a/numpy/f2py/capi_maps.py +++ b/numpy/f2py/capi_maps.py @@ -11,8 +11,6 @@ $Date: 2005/05/06 10:57:33 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __version__ = "$Revision: 1.60 $"[10:-1] from . import __version__ diff --git a/numpy/f2py/cb_rules.py b/numpy/f2py/cb_rules.py index 183d7c2f9..dc178078d 100644 --- a/numpy/f2py/cb_rules.py +++ b/numpy/f2py/cb_rules.py @@ -13,8 +13,6 @@ $Date: 2005/07/20 11:27:58 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - from . import __version__ from .auxfuncs import ( applyrules, debugcapi, dictappend, errmess, getargs, hasnote, isarray, diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py index cede06119..28b2c0670 100644 --- a/numpy/f2py/cfuncs.py +++ b/numpy/f2py/cfuncs.py @@ -14,8 +14,6 @@ $Date: 2005/05/06 11:42:34 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - import sys import copy @@ -646,7 +644,6 @@ fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",(cha tmp = obj; Py_INCREF(tmp); } -#if PY_VERSION_HEX >= 0x03000000 else if (PyUnicode_Check(obj)) { tmp = PyUnicode_AsASCIIString(obj); } @@ -661,11 +658,6 @@ fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",(cha tmp = NULL; } } -#else - else { - tmp = PyObject_Str(obj); - } -#endif if (tmp == NULL) goto capi_fail; if (*len == -1) *len = PyString_GET_SIZE(tmp); @@ -1094,13 +1086,8 @@ if (tmp_fun==NULL) { fprintf(stderr,\"Call-back argument must be function|instance|instance.__call__|f2py-function but got %s.\\n\",(fun==NULL?\"NULL\":Py_TYPE(fun)->tp_name)); goto capi_fail; } -#if PY_VERSION_HEX >= 0x03000000 if (PyObject_HasAttrString(tmp_fun,\"__code__\")) { if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) { -#else - if (PyObject_HasAttrString(tmp_fun,\"func_code\")) { - if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"func_code\"),\"co_argcount\")) { -#endif PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\"); Py_DECREF(tmp); if (tmp_argcount == NULL) { @@ -1111,13 +1098,8 @@ goto capi_fail; } } /* Get the number of optional arguments */ -#if PY_VERSION_HEX >= 0x03000000 if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) { if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\"))) -#else - if (PyObject_HasAttrString(tmp_fun,\"func_defaults\")) { - if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"func_defaults\"))) -#endif opt = PyTuple_Size(tmp); Py_XDECREF(tmp); } diff --git a/numpy/f2py/common_rules.py b/numpy/f2py/common_rules.py index f61d8810a..31aefcda9 100644 --- a/numpy/f2py/common_rules.py +++ b/numpy/f2py/common_rules.py @@ -13,8 +13,6 @@ $Date: 2005/05/06 10:57:33 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __version__ = "$Revision: 1.19 $"[10:-1] from . import __version__ diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 2db4a47e8..910120e00 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -138,8 +138,6 @@ TODO: The above may be solved by creating appropriate preprocessor program, for example. """ -from __future__ import division, absolute_import, print_function - import sys import string import fileinput diff --git a/numpy/f2py/diagnose.py b/numpy/f2py/diagnose.py index 0241fed12..092368c82 100644 --- a/numpy/f2py/diagnose.py +++ b/numpy/f2py/diagnose.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, absolute_import, print_function - import os import sys import tempfile diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py index d03eff9e3..a6751154b 100755 --- a/numpy/f2py/f2py2e.py +++ b/numpy/f2py/f2py2e.py @@ -14,8 +14,6 @@ $Date: 2005/05/06 08:31:19 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - import sys import os import pprint diff --git a/numpy/f2py/f2py_testing.py b/numpy/f2py/f2py_testing.py index f5d5fa63d..1f109e67a 100644 --- a/numpy/f2py/f2py_testing.py +++ b/numpy/f2py/f2py_testing.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import re diff --git a/numpy/f2py/f90mod_rules.py b/numpy/f2py/f90mod_rules.py index 85eae8047..ad96591c0 100644 --- a/numpy/f2py/f90mod_rules.py +++ b/numpy/f2py/f90mod_rules.py @@ -13,8 +13,6 @@ $Date: 2005/02/03 19:30:23 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __version__ = "$Revision: 1.27 $"[10:-1] f2py_version = 'See `f2py -v`' diff --git a/numpy/f2py/func2subr.py b/numpy/f2py/func2subr.py index 6010d5a23..8e18a3236 100644 --- a/numpy/f2py/func2subr.py +++ b/numpy/f2py/func2subr.py @@ -13,8 +13,6 @@ $Date: 2004/11/26 11:13:06 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __version__ = "$Revision: 1.16 $"[10:-1] f2py_version = 'See `f2py -v`' diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py index 28eb9da30..459c87aa3 100755 --- a/numpy/f2py/rules.py +++ b/numpy/f2py/rules.py @@ -50,8 +50,6 @@ $Date: 2005/08/30 08:58:42 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __version__ = "$Revision: 1.129 $"[10:-1] from . import __version__ @@ -180,7 +178,6 @@ static PyMethodDef f2py_module_methods[] = { \t{NULL,NULL} }; -#if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { \tPyModuleDef_HEAD_INIT, \t"#modulename#", @@ -192,35 +189,20 @@ static struct PyModuleDef moduledef = { \tNULL, \tNULL }; -#endif -#if PY_VERSION_HEX >= 0x03000000 -#define RETVAL m PyMODINIT_FUNC PyInit_#modulename#(void) { -#else -#define RETVAL -PyMODINIT_FUNC init#modulename#(void) { -#endif \tint i; \tPyObject *m,*d, *s, *tmp; -#if PY_VERSION_HEX >= 0x03000000 \tm = #modulename#_module = PyModule_Create(&moduledef); -#else -\tm = #modulename#_module = Py_InitModule(\"#modulename#\", f2py_module_methods); -#endif \tPy_TYPE(&PyFortran_Type) = &PyType_Type; \timport_array(); \tif (PyErr_Occurred()) -\t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return RETVAL;} +\t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;} \td = PyModule_GetDict(m); \ts = PyString_FromString(\"$R""" + """evision: $\"); \tPyDict_SetItemString(d, \"__version__\", s); \tPy_DECREF(s); -#if PY_VERSION_HEX >= 0x03000000 \ts = PyUnicode_FromString( -#else -\ts = PyString_FromString( -#endif \t\t\"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\"); \tPyDict_SetItemString(d, \"__doc__\", s); \tPy_DECREF(s); @@ -245,7 +227,7 @@ PyMODINIT_FUNC init#modulename#(void) { \tif (! PyErr_Occurred()) \t\ton_exit(f2py_report_on_exit,(void*)\"#modulename#\"); #endif -\treturn RETVAL; +\treturn m; } #ifdef __cplusplus } @@ -448,11 +430,7 @@ rout_rules = [ tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); PyObject_SetAttrString(o,"_cpointer", tmp); Py_DECREF(tmp); -#if PY_VERSION_HEX >= 0x03000000 s = PyUnicode_FromString("#name#"); -#else - s = PyString_FromString("#name#"); -#endif PyObject_SetAttrString(o,"__name__", s); Py_DECREF(s); } @@ -490,11 +468,7 @@ rout_rules = [ tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL); PyObject_SetAttrString(o,"_cpointer", tmp); Py_DECREF(tmp); -#if PY_VERSION_HEX >= 0x03000000 s = PyUnicode_FromString("#name#"); -#else - s = PyString_FromString("#name#"); -#endif PyObject_SetAttrString(o,"__name__", s); Py_DECREF(s); } diff --git a/numpy/f2py/setup.py b/numpy/f2py/setup.py index a8c1401aa..5e4d7cd56 100644 --- a/numpy/f2py/setup.py +++ b/numpy/f2py/setup.py @@ -16,8 +16,6 @@ $Date: 2005/01/30 17:22:14 $ Pearu Peterson """ -from __future__ import division, print_function - from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration diff --git a/numpy/f2py/src/fortranobject.c b/numpy/f2py/src/fortranobject.c index eb1050dd7..456e64893 100644 --- a/numpy/f2py/src/fortranobject.c +++ b/numpy/f2py/src/fortranobject.c @@ -115,14 +115,6 @@ fortran_dealloc(PyFortranObject *fp) { } -#if PY_VERSION_HEX >= 0x03000000 -#else -static PyMethodDef fortran_methods[] = { - {NULL, NULL} /* sentinel */ -}; -#endif - - /* Returns number of bytes consumed from buf, or -1 on error. */ static Py_ssize_t format_def(char *buf, Py_ssize_t size, FortranDataDef def) @@ -242,11 +234,7 @@ fortran_doc(FortranDataDef def) size--; /* p now points one beyond the last character of the string in buf */ -#if PY_VERSION_HEX >= 0x03000000 s = PyUnicode_FromStringAndSize(buf, p - buf); -#else - s = PyString_FromStringAndSize(buf, p - buf); -#endif PyMem_Free(buf); return s; @@ -306,7 +294,6 @@ fortran_getattr(PyFortranObject *fp, char *name) { return fp->dict; } if (strcmp(name,"__doc__")==0) { -#if PY_VERSION_HEX >= 0x03000000 PyObject *s = PyUnicode_FromString(""), *s2, *s3; for (i=0;i<fp->len;i++) { s2 = fortran_doc(fp->defs[i]); @@ -315,11 +302,6 @@ fortran_getattr(PyFortranObject *fp, char *name) { Py_DECREF(s); s = s3; } -#else - PyObject *s = PyString_FromString(""); - for (i=0;i<fp->len;i++) - PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i])); -#endif if (PyDict_SetItemString(fp->dict, name, s)) return NULL; return s; @@ -330,7 +312,6 @@ fortran_getattr(PyFortranObject *fp, char *name) { return NULL; return cobj; } -#if PY_VERSION_HEX >= 0x03000000 if (1) { PyObject *str, *ret; str = PyUnicode_FromString(name); @@ -338,9 +319,6 @@ fortran_getattr(PyFortranObject *fp, char *name) { Py_DECREF(str); return ret; } -#else - return Py_FindMethod(fortran_methods, (PyObject *)fp, name); -#endif } static int @@ -434,33 +412,19 @@ fortran_repr(PyFortranObject *fp) PyObject *name = NULL, *repr = NULL; name = PyObject_GetAttrString((PyObject *)fp, "__name__"); PyErr_Clear(); -#if PY_VERSION_HEX >= 0x03000000 if (name != NULL && PyUnicode_Check(name)) { repr = PyUnicode_FromFormat("<fortran %U>", name); } else { repr = PyUnicode_FromString("<fortran object>"); } -#else - if (name != NULL && PyString_Check(name)) { - repr = PyString_FromFormat("<fortran %s>", PyString_AsString(name)); - } - else { - repr = PyString_FromString("<fortran object>"); - } -#endif Py_XDECREF(name); return repr; } PyTypeObject PyFortran_Type = { -#if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) -#else - PyObject_HEAD_INIT(0) - 0, /*ob_size*/ -#endif "fortran", /*tp_name*/ sizeof(PyFortranObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -626,7 +590,7 @@ count_negative_dimensions(const int rank, } #ifdef DEBUG_COPY_ND_ARRAY -void dump_dims(int rank, npy_intp* dims) { +void dump_dims(int rank, npy_intp const* dims) { int i; printf("["); for(i=0;i<rank;++i) { diff --git a/numpy/f2py/src/fortranobject.h b/numpy/f2py/src/fortranobject.h index 21f1977eb..5c382ab7b 100644 --- a/numpy/f2py/src/fortranobject.h +++ b/numpy/f2py/src/fortranobject.h @@ -82,20 +82,10 @@ typedef struct { extern PyObject * PyFortranObject_New(FortranDataDef* defs, f2py_void_func init); extern PyObject * PyFortranObject_NewAsAttr(FortranDataDef* defs); -#if PY_VERSION_HEX >= 0x03000000 - PyObject * F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *)); void * F2PyCapsule_AsVoidPtr(PyObject *obj); int F2PyCapsule_Check(PyObject *ptr); -#else - -PyObject * F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(void *)); -void * F2PyCapsule_AsVoidPtr(PyObject *ptr); -int F2PyCapsule_Check(PyObject *ptr); - -#endif - #define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & NPY_ARRAY_C_CONTIGUOUS) #define F2PY_INTENT_IN 1 #define F2PY_INTENT_INOUT 2 diff --git a/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c b/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c index 978db4e69..83c0da2cf 100644 --- a/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +++ b/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c @@ -129,7 +129,6 @@ static PyMethodDef f2py_module_methods[] = { {NULL,NULL} }; -#if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "test_array_from_pyobj_ext", @@ -141,21 +140,10 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif -#if PY_VERSION_HEX >= 0x03000000 -#define RETVAL m PyMODINIT_FUNC PyInit_test_array_from_pyobj_ext(void) { -#else -#define RETVAL -PyMODINIT_FUNC inittest_array_from_pyobj_ext(void) { -#endif PyObject *m,*d, *s; -#if PY_VERSION_HEX >= 0x03000000 m = wrap_module = PyModule_Create(&moduledef); -#else - m = wrap_module = Py_InitModule("test_array_from_pyobj_ext", f2py_module_methods); -#endif Py_TYPE(&PyFortran_Type) = &PyType_Type; import_array(); if (PyErr_Occurred()) @@ -238,7 +226,7 @@ PyMODINIT_FUNC inittest_array_from_pyobj_ext(void) { on_exit(f2py_report_on_exit,(void*)"array_from_pyobj.wrap.call"); #endif - return RETVAL; + return m; } #ifdef __cplusplus } diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index a80090185..b719f2495 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys import copy @@ -57,7 +55,7 @@ def flags2names(flags): return info -class Intent(object): +class Intent: def __init__(self, intent_list=[]): self.intent_list = intent_list[:] @@ -131,7 +129,7 @@ if ((intp().dtype.itemsize != 4 or clongdouble().dtype.alignment <= 8) and _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE'] -class Type(object): +class Type: _type_cache = {} def __new__(cls, name): @@ -192,7 +190,7 @@ class Type(object): return types -class Array(object): +class Array: def __init__(self, typ, dims, intent, obj): self.type = typ @@ -293,7 +291,7 @@ class Array(object): return obj_attr[0] == self.arr_attr[0] -class TestIntent(object): +class TestIntent: def test_in_out(self): assert_equal(str(intent.in_.out), 'intent(in,out)') @@ -304,7 +302,7 @@ class TestIntent(object): assert_(not intent.in_.is_intent('c')) -class TestSharedMemory(object): +class TestSharedMemory: num2seq = [1, 2] num23seq = [[1, 2, 3], [4, 5, 6]] diff --git a/numpy/f2py/tests/test_assumed_shape.py b/numpy/f2py/tests/test_assumed_shape.py index e5695a61c..dfc252660 100644 --- a/numpy/f2py/tests/test_assumed_shape.py +++ b/numpy/f2py/tests/test_assumed_shape.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import pytest import tempfile diff --git a/numpy/f2py/tests/test_block_docstring.py b/numpy/f2py/tests/test_block_docstring.py index 4f1678980..03660f021 100644 --- a/numpy/f2py/tests/test_block_docstring.py +++ b/numpy/f2py/tests/test_block_docstring.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import pytest from . import util diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py index 21c29ba5f..7629df605 100644 --- a/numpy/f2py/tests/test_callback.py +++ b/numpy/f2py/tests/test_callback.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import math import textwrap import sys @@ -118,7 +116,7 @@ cf2py intent(out) a r = t(self.module.func0._cpointer) assert_(r == 11, repr(r)) - class A(object): + class A: def __call__(self): return 7 diff --git a/numpy/f2py/tests/test_common.py b/numpy/f2py/tests/test_common.py index dcb01b0ec..e4bf35504 100644 --- a/numpy/f2py/tests/test_common.py +++ b/numpy/f2py/tests/test_common.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys import pytest diff --git a/numpy/f2py/tests/test_compile_function.py b/numpy/f2py/tests/test_compile_function.py index 40ea7997f..d40ed63cf 100644 --- a/numpy/f2py/tests/test_compile_function.py +++ b/numpy/f2py/tests/test_compile_function.py @@ -1,8 +1,6 @@ """See https://github.com/numpy/numpy/pull/11937. """ -from __future__ import division, absolute_import, print_function - import sys import os import uuid diff --git a/numpy/f2py/tests/test_crackfortran.py b/numpy/f2py/tests/test_crackfortran.py index 941696be3..796965e6f 100644 --- a/numpy/f2py/tests/test_crackfortran.py +++ b/numpy/f2py/tests/test_crackfortran.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest import numpy as np @@ -37,4 +35,3 @@ class TestNoSpace(util.F2PyTest): self.module.subc([w, k]) assert_array_equal(k, w + 1) assert self.module.t0(23) == b'2' - diff --git a/numpy/f2py/tests/test_kind.py b/numpy/f2py/tests/test_kind.py index 1f7762a80..a7e2b28ed 100644 --- a/numpy/f2py/tests/test_kind.py +++ b/numpy/f2py/tests/test_kind.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import pytest diff --git a/numpy/f2py/tests/test_mixed.py b/numpy/f2py/tests/test_mixed.py index 0337538ff..fc00ccc43 100644 --- a/numpy/f2py/tests/test_mixed.py +++ b/numpy/f2py/tests/test_mixed.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import textwrap import pytest diff --git a/numpy/f2py/tests/test_parameter.py b/numpy/f2py/tests/test_parameter.py index 6a378687a..b61827169 100644 --- a/numpy/f2py/tests/test_parameter.py +++ b/numpy/f2py/tests/test_parameter.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import pytest diff --git a/numpy/f2py/tests/test_quoted_character.py b/numpy/f2py/tests/test_quoted_character.py index c9a1c36f5..d89ef1385 100644 --- a/numpy/f2py/tests/test_quoted_character.py +++ b/numpy/f2py/tests/test_quoted_character.py @@ -1,8 +1,6 @@ """See https://github.com/numpy/numpy/pull/10676. """ -from __future__ import division, absolute_import, print_function - import sys from importlib import import_module import pytest diff --git a/numpy/f2py/tests/test_regression.py b/numpy/f2py/tests/test_regression.py index 3adae635d..67e00f1f7 100644 --- a/numpy/f2py/tests/test_regression.py +++ b/numpy/f2py/tests/test_regression.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import pytest diff --git a/numpy/f2py/tests/test_return_character.py b/numpy/f2py/tests/test_return_character.py index fc3a58d36..6cb95a8b6 100644 --- a/numpy/f2py/tests/test_return_character.py +++ b/numpy/f2py/tests/test_return_character.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest from numpy import array diff --git a/numpy/f2py/tests/test_return_complex.py b/numpy/f2py/tests/test_return_complex.py index 43c884dfb..9063695bc 100644 --- a/numpy/f2py/tests/test_return_complex.py +++ b/numpy/f2py/tests/test_return_complex.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest from numpy import array diff --git a/numpy/f2py/tests/test_return_integer.py b/numpy/f2py/tests/test_return_integer.py index 22f4acfdf..35f32e37d 100644 --- a/numpy/f2py/tests/test_return_integer.py +++ b/numpy/f2py/tests/test_return_integer.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest from numpy import array diff --git a/numpy/f2py/tests/test_return_logical.py b/numpy/f2py/tests/test_return_logical.py index 96f215a91..3139e0df7 100644 --- a/numpy/f2py/tests/test_return_logical.py +++ b/numpy/f2py/tests/test_return_logical.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest from numpy import array diff --git a/numpy/f2py/tests/test_return_real.py b/numpy/f2py/tests/test_return_real.py index 315cfe49b..1707aab45 100644 --- a/numpy/f2py/tests/test_return_real.py +++ b/numpy/f2py/tests/test_return_real.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import platform import pytest diff --git a/numpy/f2py/tests/test_semicolon_split.py b/numpy/f2py/tests/test_semicolon_split.py index bcd18c893..d8b4bf222 100644 --- a/numpy/f2py/tests/test_semicolon_split.py +++ b/numpy/f2py/tests/test_semicolon_split.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import platform import pytest diff --git a/numpy/f2py/tests/test_size.py b/numpy/f2py/tests/test_size.py index e2af61804..b609fa77f 100644 --- a/numpy/f2py/tests/test_size.py +++ b/numpy/f2py/tests/test_size.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import pytest diff --git a/numpy/f2py/tests/test_string.py b/numpy/f2py/tests/test_string.py index 0493c99cf..e3ec96af9 100644 --- a/numpy/f2py/tests/test_string.py +++ b/numpy/f2py/tests/test_string.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import pytest diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py index bf005df88..c430a6608 100644 --- a/numpy/f2py/tests/util.py +++ b/numpy/f2py/tests/util.py @@ -5,8 +5,6 @@ Utility functions for - detecting if compilers are present """ -from __future__ import division, absolute_import, print_function - import os import sys import subprocess @@ -315,7 +313,7 @@ def build_module_distutils(source_files, config_code, module_name, **kw): # -class F2PyTest(object): +class F2PyTest: code = None sources = None options = [] diff --git a/numpy/f2py/use_rules.py b/numpy/f2py/use_rules.py index 6f44f1634..268c7e81b 100644 --- a/numpy/f2py/use_rules.py +++ b/numpy/f2py/use_rules.py @@ -15,8 +15,6 @@ $Date: 2000/09/10 12:35:43 $ Pearu Peterson """ -from __future__ import division, absolute_import, print_function - __version__ = "$Revision: 1.3 $"[10:-1] f2py_version = 'See `f2py -v`' diff --git a/numpy/fft/__init__.py b/numpy/fft/__init__.py index 37b3f0da6..36cfe81b3 100644 --- a/numpy/fft/__init__.py +++ b/numpy/fft/__init__.py @@ -191,8 +191,6 @@ For examples, see the various functions. """ -from __future__ import division, absolute_import, print_function - from ._pocketfft import * from .helper import * diff --git a/numpy/fft/_pocketfft.c b/numpy/fft/_pocketfft.c index d75b9983c..de86e36d3 100644 --- a/numpy/fft/_pocketfft.c +++ b/numpy/fft/_pocketfft.c @@ -2359,7 +2359,6 @@ static struct PyMethodDef methods[] = { {NULL, NULL, 0, NULL} /* sentinel */ }; -#if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_pocketfft_internal", @@ -2371,30 +2370,14 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif /* Initialization function for the module */ -#if PY_MAJOR_VERSION >= 3 -#define RETVAL(x) x PyMODINIT_FUNC PyInit__pocketfft_internal(void) -#else -#define RETVAL(x) -PyMODINIT_FUNC -init_pocketfft_internal(void) -#endif { PyObject *m; -#if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); -#else - static const char module_documentation[] = ""; - - m = Py_InitModule4("_pocketfft_internal", methods, - module_documentation, - (PyObject*)NULL,PYTHON_API_VERSION); -#endif if (m == NULL) { - return RETVAL(NULL); + return NULL; } /* Import the array object */ @@ -2402,5 +2385,5 @@ init_pocketfft_internal(void) /* XXXX Add constants here */ - return RETVAL(m); + return m; } diff --git a/numpy/fft/_pocketfft.py b/numpy/fft/_pocketfft.py index 50720cda4..f2510a6c2 100644 --- a/numpy/fft/_pocketfft.py +++ b/numpy/fft/_pocketfft.py @@ -27,8 +27,6 @@ n = n-dimensional transform behavior.) """ -from __future__ import division, absolute_import, print_function - __all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn'] diff --git a/numpy/fft/helper.py b/numpy/fft/helper.py index a920a4ac0..3dacd9ee1 100644 --- a/numpy/fft/helper.py +++ b/numpy/fft/helper.py @@ -2,8 +2,6 @@ Discrete Fourier Transforms - helper.py """ -from __future__ import division, absolute_import, print_function - from numpy.compat import integer_types from numpy.core import integer, empty, arange, asarray, roll from numpy.core.overrides import array_function_dispatch, set_module diff --git a/numpy/fft/setup.py b/numpy/fft/setup.py index 8c3a31557..40d632ec5 100644 --- a/numpy/fft/setup.py +++ b/numpy/fft/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/fft/tests/test_helper.py b/numpy/fft/tests/test_helper.py index 6613c8002..2b457271b 100644 --- a/numpy/fft/tests/test_helper.py +++ b/numpy/fft/tests/test_helper.py @@ -3,13 +3,12 @@ Copied from fftpack.helper by Pearu Peterson, October 2005 """ -from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import assert_array_almost_equal, assert_equal from numpy import fft, pi -class TestFFTShift(object): +class TestFFTShift: def test_definition(self): x = [0, 1, 2, 3, 4, -4, -3, -2, -1] @@ -135,7 +134,7 @@ class TestFFTShift(object): original_ifftshift(inp, axes_keyword)) -class TestFFTFreq(object): +class TestFFTFreq: def test_definition(self): x = [0, 1, 2, 3, 4, -4, -3, -2, -1] @@ -146,7 +145,7 @@ class TestFFTFreq(object): assert_array_almost_equal(10*pi*fft.fftfreq(10, pi), x) -class TestRFFTFreq(object): +class TestRFFTFreq: def test_definition(self): x = [0, 1, 2, 3, 4] @@ -157,7 +156,7 @@ class TestRFFTFreq(object): assert_array_almost_equal(10*pi*fft.rfftfreq(10, pi), x) -class TestIRFFTN(object): +class TestIRFFTN: def test_not_last_axis_success(self): ar, ai = np.random.random((2, 16, 8, 32)) diff --git a/numpy/fft/tests/test_pocketfft.py b/numpy/fft/tests/test_pocketfft.py index 453e964fa..da31ec09e 100644 --- a/numpy/fft/tests/test_pocketfft.py +++ b/numpy/fft/tests/test_pocketfft.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np import pytest from numpy.random import random @@ -21,13 +19,13 @@ def fft1(x): return np.sum(x*np.exp(phase), axis=1) -class TestFFTShift(object): +class TestFFTShift: def test_fft_n(self): assert_raises(ValueError, np.fft.fft, [1, 2, 3], 0) -class TestFFT1D(object): +class TestFFT1D: def test_identity(self): maxlen = 512 @@ -222,7 +220,7 @@ def test_fft_with_order(dtype, order, fft): raise ValueError() -class TestFFTThreadSafe(object): +class TestFFTThreadSafe: threads = 16 input_shape = (800, 200) diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 2db12d9a4..cb0de0d15 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -11,8 +11,6 @@ Most contains basic functions that are used by several submodules and are useful to have in the main name-space. """ -from __future__ import division, absolute_import, print_function - import math from numpy.version import version as __version__ diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index 0d71375c2..aa793958e 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -34,8 +34,6 @@ Example:: >>> fp.close() # doctest: +SKIP """ -from __future__ import division, absolute_import, print_function - import os import sys import warnings @@ -141,7 +139,7 @@ def _python2_gzipopen(fn, mode, encoding, newline): # deferring the import of lzma, bz2 and gzip until needed # TODO: .zip support, .tar support? -class _FileOpeners(object): +class _FileOpeners: """ Container for different methods to open (un-)compressed files. @@ -270,7 +268,7 @@ def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None): @set_module('numpy') -class DataSource(object): +class DataSource: """ DataSource(destpath='.') diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py index 8bc336fdb..dd6e9ec66 100644 --- a/numpy/lib/_iotools.py +++ b/numpy/lib/_iotools.py @@ -1,8 +1,6 @@ """A collection of functions designed to help I/O with ascii files. """ -from __future__ import division, absolute_import, print_function - __docformat__ = "restructuredtext en" import numpy as np @@ -132,7 +130,7 @@ def flatten_dtype(ndtype, flatten_base=False): return types -class LineSplitter(object): +class LineSplitter: """ Object to split a string at a given delimiter or at given places. @@ -233,7 +231,7 @@ class LineSplitter(object): return self._handyman(_decode_line(line, self.encoding)) -class NameValidator(object): +class NameValidator: """ Object to validate a list of strings to use as field names. @@ -456,7 +454,7 @@ class ConversionWarning(UserWarning): pass -class StringConverter(object): +class StringConverter: """ Factory class for function transforming a string into another object (int, float). diff --git a/numpy/lib/_version.py b/numpy/lib/_version.py index 8aa999fc9..6a7c5cba1 100644 --- a/numpy/lib/_version.py +++ b/numpy/lib/_version.py @@ -5,8 +5,6 @@ The LooseVersion and StrictVersion classes that distutils provides don't work; they don't recognize anything like alpha/beta/rc/dev versions. """ -from __future__ import division, absolute_import, print_function - import re from numpy.compat import basestring diff --git a/numpy/lib/arraypad.py b/numpy/lib/arraypad.py index 33e64708d..247eed07c 100644 --- a/numpy/lib/arraypad.py +++ b/numpy/lib/arraypad.py @@ -3,8 +3,6 @@ The arraypad module contains a group of functions to pad values onto the edges of an n-dimensional array. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.core.overrides import array_function_dispatch from numpy.lib.index_tricks import ndindex diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index d65316598..ad508e85d 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -25,8 +25,6 @@ To do: Optionally return indices analogously to unique for all functions. :Author: Robert Cimrman """ -from __future__ import division, absolute_import, print_function - import functools import numpy as np diff --git a/numpy/lib/arrayterator.py b/numpy/lib/arrayterator.py index c16668582..15b0f8aa9 100644 --- a/numpy/lib/arrayterator.py +++ b/numpy/lib/arrayterator.py @@ -7,8 +7,6 @@ an array object, and when iterated it will return sub-arrays with at most a user-specified number of elements. """ -from __future__ import division, absolute_import, print_function - from operator import mul from functools import reduce @@ -17,7 +15,7 @@ from numpy.compat import long __all__ = ['Arrayterator'] -class Arrayterator(object): +class Arrayterator: """ Buffered iterator for big arrays. diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index a011e52a9..b055bb1ec 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -10,8 +10,6 @@ or arrays (or other sequences). Functions support the :class:`decimal.Decimal` type unless otherwise stated. """ -from __future__ import division, absolute_import, print_function - import warnings from decimal import Decimal import functools diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 20e2e9c72..2ee43637c 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -161,8 +161,6 @@ alternatives, is described in the `"npy-format" NEP evolved with time and this document is more current. """ -from __future__ import division, absolute_import, print_function - import numpy import sys import io diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index c2680b016..6c7dfbfd3 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - try: # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 @@ -974,13 +972,18 @@ def gradient(f, *varargs, **kwargs): # scalar or 1d array for each axis dx = list(varargs) for i, distances in enumerate(dx): - if np.ndim(distances) == 0: + distances = np.asanyarray(distances) + if distances.ndim == 0: continue - elif np.ndim(distances) != 1: + elif distances.ndim != 1: raise ValueError("distances must be either scalars or 1d") if len(distances) != f.shape[axes[i]]: raise ValueError("when 1d, distances must match " "the length of the corresponding dimension") + if np.issubdtype(distances.dtype, np.integer): + # Convert numpy integer types to float64 to avoid modular + # arithmetic in np.diff(distances). + distances = distances.astype(np.float64) diffx = np.diff(distances) # if distances are constant reduce to the scalar case # since it brings a consistent speedup @@ -1019,8 +1022,12 @@ def gradient(f, *varargs, **kwargs): elif np.issubdtype(otype, np.inexact): pass else: - # all other types convert to floating point - otype = np.double + # All other types convert to floating point. + # First check if f is a numpy integer type; if so, convert f to float64 + # to avoid modular arithmetic when computing the changes in f. + if np.issubdtype(otype, np.integer): + f = f.astype(np.float64) + otype = np.float64 for axis, ax_dx in zip(axes, dx): if f.shape[axis] < edge_order + 1: @@ -1863,7 +1870,7 @@ def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes): @set_module('numpy') -class vectorize(object): +class vectorize: """ vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None) diff --git a/numpy/lib/histograms.py b/numpy/lib/histograms.py index 03c365ab6..0eff73b39 100644 --- a/numpy/lib/histograms.py +++ b/numpy/lib/histograms.py @@ -1,8 +1,6 @@ """ Histogram-related functions """ -from __future__ import division, absolute_import, print_function - import contextlib import functools import operator diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 04384854c..0560bd36d 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import functools import sys import math @@ -107,7 +105,7 @@ def ix_(*args): out.append(new) return tuple(out) -class nd_grid(object): +class nd_grid: """ Construct a multi-dimensional "meshgrid". @@ -299,7 +297,7 @@ class OGridClass(nd_grid): ogrid = OGridClass() -class AxisConcatenator(object): +class AxisConcatenator: """ Translates slice objects to concatenation along an axis. @@ -552,7 +550,7 @@ c_ = CClass() @set_module('numpy') -class ndenumerate(object): +class ndenumerate: """ Multidimensional index iterator. @@ -603,7 +601,7 @@ class ndenumerate(object): @set_module('numpy') -class ndindex(object): +class ndindex: """ An N-dimensional iterator object to index arrays. @@ -681,7 +679,7 @@ class ndindex(object): # # -class IndexExpression(object): +class IndexExpression: """ A nicer way to build up index tuples for arrays. diff --git a/numpy/lib/mixins.py b/numpy/lib/mixins.py index f974a7724..d4811b94d 100644 --- a/numpy/lib/mixins.py +++ b/numpy/lib/mixins.py @@ -1,6 +1,4 @@ """Mixin classes for custom array types that don't inherit from ndarray.""" -from __future__ import division, absolute_import, print_function - import sys from numpy.core import umath as um @@ -60,7 +58,7 @@ def _unary_method(ufunc, name): return func -class NDArrayOperatorsMixin(object): +class NDArrayOperatorsMixin: """Mixin defining all operator special methods using __array_ufunc__. This class implements the special methods for almost all of Python's diff --git a/numpy/lib/nanfunctions.py b/numpy/lib/nanfunctions.py index 8e2a34e70..003550432 100644 --- a/numpy/lib/nanfunctions.py +++ b/numpy/lib/nanfunctions.py @@ -20,8 +20,6 @@ Functions - `nanpercentile` -- qth percentile of non-NaN values """ -from __future__ import division, absolute_import, print_function - import functools import warnings import numpy as np diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index 3e54ff10c..c47e388c0 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import os import re @@ -55,7 +53,7 @@ array_function_dispatch = functools.partial( overrides.array_function_dispatch, module='numpy') -class BagObj(object): +class BagObj: """ BagObj(obj) @@ -69,7 +67,7 @@ class BagObj(object): Examples -------- >>> from numpy.lib.npyio import BagObj as BO - >>> class BagDemo(object): + >>> class BagDemo: ... def __getitem__(self, key): # An instance of BagObj(BagDemo) ... # will call this method when any ... # attribute look-up is required @@ -1336,7 +1334,7 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', fmt = asstr(fmt) delimiter = asstr(delimiter) - class WriteWrap(object): + class WriteWrap: """Convert to unicode in py2 or to bytes on bytestream inputs. """ diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 3d07a0de4..5a0fa5431 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -2,8 +2,6 @@ Functions to operate on polynomials. """ -from __future__ import division, absolute_import, print_function - __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d', 'polyfit', 'RankWarning'] @@ -1007,7 +1005,7 @@ def _raise_power(astr, wrap=70): @set_module('numpy') -class poly1d(object): +class poly1d: """ A one-dimensional polynomial class. diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index 927161ddb..93aa67a3b 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -5,8 +5,6 @@ Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. """ -from __future__ import division, absolute_import, print_function - import sys import itertools import numpy as np diff --git a/numpy/lib/scimath.py b/numpy/lib/scimath.py index 5ac790ce9..555a3d5a8 100644 --- a/numpy/lib/scimath.py +++ b/numpy/lib/scimath.py @@ -15,8 +15,6 @@ Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. """ -from __future__ import division, absolute_import, print_function - import numpy.core.numeric as nx import numpy.core.numerictypes as nt from numpy.core.numeric import asarray, any diff --git a/numpy/lib/setup.py b/numpy/lib/setup.py index d342410b8..5d0341d86 100644 --- a/numpy/lib/setup.py +++ b/numpy/lib/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index dbb61c225..7634af010 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import functools import numpy.core.numeric as _nx diff --git a/numpy/lib/stride_tricks.py b/numpy/lib/stride_tricks.py index 8aafd094b..9c9da2974 100644 --- a/numpy/lib/stride_tricks.py +++ b/numpy/lib/stride_tricks.py @@ -5,15 +5,13 @@ An explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.core.overrides import array_function_dispatch __all__ = ['broadcast_to', 'broadcast_arrays'] -class DummyArray(object): +class DummyArray: """Dummy object that just exists to hang __array_interface__ dictionaries and possibly keep alive a reference to a base array. """ diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index 8eac16b58..fdd22347d 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys import pytest @@ -96,7 +94,7 @@ def invalid_httpfile(): return http_fakefile -class TestDataSourceOpen(object): +class TestDataSourceOpen: def setup(self): self.tmpdir = mkdtemp() self.ds = datasource.DataSource(self.tmpdir) @@ -183,7 +181,7 @@ class TestDataSourceOpen(object): assert_equal(magic_line, result) -class TestDataSourceExists(object): +class TestDataSourceExists: def setup(self): self.tmpdir = mkdtemp() self.ds = datasource.DataSource(self.tmpdir) @@ -213,7 +211,7 @@ class TestDataSourceExists(object): assert_equal(self.ds.exists(tmpfile), False) -class TestDataSourceAbspath(object): +class TestDataSourceAbspath: def setup(self): self.tmpdir = os.path.abspath(mkdtemp()) self.ds = datasource.DataSource(self.tmpdir) @@ -278,7 +276,7 @@ class TestDataSourceAbspath(object): os.sep = orig_os_sep -class TestRepositoryAbspath(object): +class TestRepositoryAbspath: def setup(self): self.tmpdir = os.path.abspath(mkdtemp()) self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) @@ -311,7 +309,7 @@ class TestRepositoryAbspath(object): os.sep = orig_os_sep -class TestRepositoryExists(object): +class TestRepositoryExists: def setup(self): self.tmpdir = mkdtemp() self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) @@ -344,7 +342,7 @@ class TestRepositoryExists(object): assert_(self.repos.exists(tmpfile)) -class TestOpenFunc(object): +class TestOpenFunc: def setup(self): self.tmpdir = mkdtemp() diff --git a/numpy/lib/tests/test__iotools.py b/numpy/lib/tests/test__iotools.py index 15cd3ad9d..1d69d869e 100644 --- a/numpy/lib/tests/test__iotools.py +++ b/numpy/lib/tests/test__iotools.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import time from datetime import date @@ -14,7 +12,7 @@ from numpy.lib._iotools import ( from numpy.compat import unicode -class TestLineSplitter(object): +class TestLineSplitter: "Tests the LineSplitter class." def test_no_delimiter(self): @@ -83,7 +81,7 @@ class TestLineSplitter(object): # ----------------------------------------------------------------------------- -class TestNameValidator(object): +class TestNameValidator: def test_case_sensitivity(self): "Test case sensitivity" @@ -141,7 +139,7 @@ def _bytes_to_date(s): return date(*time.strptime(s, "%Y-%m-%d")[:3]) -class TestStringConverter(object): +class TestStringConverter: "Test StringConverter" def test_creation(self): @@ -266,7 +264,7 @@ class TestStringConverter(object): assert_(converter(val) == 9223372043271415339) -class TestMiscFunctions(object): +class TestMiscFunctions: def test_has_nested_dtype(self): "Test has_nested_dtype" diff --git a/numpy/lib/tests/test__version.py b/numpy/lib/tests/test__version.py index 8e66a0c03..182504631 100644 --- a/numpy/lib/tests/test__version.py +++ b/numpy/lib/tests/test__version.py @@ -1,8 +1,6 @@ """Tests for the NumpyVersion class. """ -from __future__ import division, absolute_import, print_function - from numpy.testing import assert_, assert_raises from numpy.lib import NumpyVersion diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py index 65593dd29..cd75b4ac4 100644 --- a/numpy/lib/tests/test_arraypad.py +++ b/numpy/lib/tests/test_arraypad.py @@ -1,8 +1,6 @@ """Tests for the array padding functions. """ -from __future__ import division, absolute_import, print_function - import pytest import numpy as np @@ -31,7 +29,7 @@ _all_modes = { } -class TestAsPairs(object): +class TestAsPairs: def test_single_value(self): """Test casting for a single value.""" expected = np.array([[3, 3]] * 10) @@ -114,7 +112,7 @@ class TestAsPairs(object): _as_pairs(np.ones((2, 3)), 3) -class TestConditionalShortcuts(object): +class TestConditionalShortcuts: @pytest.mark.parametrize("mode", _all_modes.keys()) def test_zero_padding_shortcuts(self, mode): test = np.arange(120).reshape(4, 5, 6) @@ -136,7 +134,7 @@ class TestConditionalShortcuts(object): np.pad(test, pad_amt, mode=mode, stat_length=30)) -class TestStatistic(object): +class TestStatistic: def test_check_mean_stat_length(self): a = np.arange(100).astype('f') a = np.pad(a, ((25, 20), ), 'mean', stat_length=((2, 3), )) @@ -498,7 +496,7 @@ class TestStatistic(object): np.pad([1., 2.], 1, mode, stat_length=(1, 0)) -class TestConstant(object): +class TestConstant: def test_check_constant(self): a = np.arange(100) a = np.pad(a, (25, 20), 'constant', constant_values=(10, 20)) @@ -677,7 +675,7 @@ class TestConstant(object): assert result.shape == (3, 4, 4) -class TestLinearRamp(object): +class TestLinearRamp: def test_check_simple(self): a = np.arange(100).astype('f') a = np.pad(a, (25, 20), 'linear_ramp', end_values=(4, 5)) @@ -762,7 +760,7 @@ class TestLinearRamp(object): assert_equal(result, expected) -class TestReflect(object): +class TestReflect: def test_check_simple(self): a = np.arange(100) a = np.pad(a, (25, 20), 'reflect') @@ -872,7 +870,7 @@ class TestReflect(object): assert_array_equal(a, b) -class TestEmptyArray(object): +class TestEmptyArray: """Check how padding behaves on arrays with an empty dimension.""" @pytest.mark.parametrize( @@ -896,7 +894,7 @@ class TestEmptyArray(object): assert result.shape == (8, 0, 4) -class TestSymmetric(object): +class TestSymmetric: def test_check_simple(self): a = np.arange(100) a = np.pad(a, (25, 20), 'symmetric') @@ -1030,7 +1028,7 @@ class TestSymmetric(object): assert_array_equal(a, b) -class TestWrap(object): +class TestWrap: def test_check_simple(self): a = np.arange(100) a = np.pad(a, (25, 20), 'wrap') @@ -1144,7 +1142,7 @@ class TestWrap(object): assert_array_equal(np.r_[a, a, a, a][:-3], b) -class TestEdge(object): +class TestEdge: def test_check_simple(self): a = np.arange(12) a = np.reshape(a, (4, 3)) @@ -1183,7 +1181,7 @@ class TestEdge(object): assert_array_equal(padded, expected) -class TestEmpty(object): +class TestEmpty: def test_simple(self): arr = np.arange(24).reshape(4, 6) result = np.pad(arr, [(2, 3), (3, 1)], mode="empty") @@ -1231,7 +1229,7 @@ def test_object_input(mode): assert_array_equal(np.pad(a, pad_amt, mode=mode), b) -class TestPadWidth(object): +class TestPadWidth: @pytest.mark.parametrize("pad_width", [ (4, 5, 6, 7), ((1,), (2,), (3,)), diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index 1d38d8d27..851fd31ea 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -1,8 +1,6 @@ """Test functions for 1D array set operations. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import (assert_array_equal, assert_equal, @@ -14,7 +12,7 @@ import pytest -class TestSetOps(object): +class TestSetOps: def test_intersect1d(self): # unique inputs @@ -36,7 +34,7 @@ class TestSetOps(object): def test_intersect1d_array_like(self): # See gh-11772 - class Test(object): + class Test: def __array__(self): return np.arange(3) @@ -415,7 +413,7 @@ class TestSetOps(object): assert_array_equal(c1, c2) -class TestUnique(object): +class TestUnique: def test_unique_1d(self): diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py index 2ce4456a5..c00ed13d7 100644 --- a/numpy/lib/tests/test_arrayterator.py +++ b/numpy/lib/tests/test_arrayterator.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from operator import mul from functools import reduce diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py index cb67f7c0f..26e79bc06 100644 --- a/numpy/lib/tests/test_financial.py +++ b/numpy/lib/tests/test_financial.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import warnings from decimal import Decimal @@ -18,7 +16,7 @@ def filter_deprecation(func): return newfunc -class TestFinancial(object): +class TestFinancial: @filter_deprecation def test_npv_irr_congruence(self): # IRR is defined as the rate required for the present value of a diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index 0592e0b12..28ce038ae 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - # doctest r''' Test the .npy file format. diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index f95e0a251..dfce2d55d 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import operator import warnings import sys @@ -44,7 +42,7 @@ def _make_complex(real, imag): return ret -class TestRot90(object): +class TestRot90: def test_basic(self): assert_raises(ValueError, rot90, np.ones(4)) assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(0,1,2)) @@ -112,7 +110,7 @@ class TestRot90(object): rot90(a_rot90_20, k=k-1, axes=(2, 0))) -class TestFlip(object): +class TestFlip: def test_axes(self): assert_raises(np.AxisError, np.flip, np.ones(4), axis=1) @@ -215,7 +213,7 @@ class TestFlip(object): assert_equal(np.flip(a, axis=(1, 2)), c) -class TestAny(object): +class TestAny: def test_basic(self): y1 = [0, 0, 1, 0] @@ -232,7 +230,7 @@ class TestAny(object): assert_array_equal(np.sometrue(y1, axis=1), [0, 1, 1]) -class TestAll(object): +class TestAll: def test_basic(self): y1 = [0, 1, 1, 0] @@ -250,7 +248,7 @@ class TestAll(object): assert_array_equal(np.alltrue(y1, axis=1), [0, 0, 1]) -class TestCopy(object): +class TestCopy: def test_basic(self): a = np.array([[1, 2], [3, 4]]) @@ -278,7 +276,7 @@ class TestCopy(object): assert_(a_fort_copy.flags.f_contiguous) -class TestAverage(object): +class TestAverage: def test_basic(self): y1 = np.array([1, 2, 3]) @@ -379,7 +377,7 @@ class TestAverage(object): w /= w.sum() assert_almost_equal(a.mean(0), average(a, weights=w)) -class TestSelect(object): +class TestSelect: choices = [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])] @@ -441,7 +439,7 @@ class TestSelect(object): select(conditions, choices) -class TestInsert(object): +class TestInsert: def test_basic(self): a = [1, 2, 3] @@ -542,7 +540,7 @@ class TestInsert(object): assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype)) -class TestAmax(object): +class TestAmax: def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] @@ -554,7 +552,7 @@ class TestAmax(object): assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0]) -class TestAmin(object): +class TestAmin: def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] @@ -566,7 +564,7 @@ class TestAmin(object): assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0]) -class TestPtp(object): +class TestPtp: def test_basic(self): a = np.array([3, 4, 5, 10, -3, -5, 6.0]) @@ -581,7 +579,7 @@ class TestPtp(object): assert_equal(b.ptp(axis=(0,1), keepdims=True), [[8.0]]) -class TestCumsum(object): +class TestCumsum: def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] @@ -604,7 +602,7 @@ class TestCumsum(object): assert_array_equal(np.cumsum(a2, axis=1), tgt) -class TestProd(object): +class TestProd: def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] @@ -624,7 +622,7 @@ class TestProd(object): np.array([24, 1890, 600], ctype)) -class TestCumprod(object): +class TestCumprod: def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] @@ -651,7 +649,7 @@ class TestCumprod(object): [10, 30, 120, 600]], ctype)) -class TestDiff(object): +class TestDiff: def test_basic(self): x = [1, 4, 6, 7, 12] @@ -791,7 +789,7 @@ class TestDiff(object): assert_raises(np.AxisError, diff, x, append=0, axis=3) -class TestDelete(object): +class TestDelete: def setup(self): self.a = np.arange(5) @@ -866,7 +864,7 @@ class TestDelete(object): assert_equal(m.flags.f_contiguous, k.flags.f_contiguous) -class TestGradient(object): +class TestGradient: def test_basic(self): v = [[1, 1], [3, 4]] @@ -1083,8 +1081,42 @@ class TestGradient(object): assert_raises(ValueError, gradient, np.arange(1), edge_order=2) assert_raises(ValueError, gradient, np.arange(2), edge_order=2) - -class TestAngle(object): + @pytest.mark.parametrize('f_dtype', [np.uint8, np.uint16, + np.uint32, np.uint64]) + def test_f_decreasing_unsigned_int(self, f_dtype): + f = np.array([5, 4, 3, 2, 1], dtype=f_dtype) + g = gradient(f) + assert_array_equal(g, [-1]*len(f)) + + @pytest.mark.parametrize('f_dtype', [np.int8, np.int16, + np.int32, np.int64]) + def test_f_signed_int_big_jump(self, f_dtype): + maxint = np.iinfo(f_dtype).max + x = np.array([1, 3]) + f = np.array([-1, maxint], dtype=f_dtype) + dfdx = gradient(f, x) + assert_array_equal(dfdx, [(maxint + 1) // 2]*2) + + @pytest.mark.parametrize('x_dtype', [np.uint8, np.uint16, + np.uint32, np.uint64]) + def test_x_decreasing_unsigned(self, x_dtype): + x = np.array([3, 2, 1], dtype=x_dtype) + f = np.array([0, 2, 4]) + dfdx = gradient(f, x) + assert_array_equal(dfdx, [-2]*len(x)) + + @pytest.mark.parametrize('x_dtype', [np.int8, np.int16, + np.int32, np.int64]) + def test_x_signed_int_big_jump(self, x_dtype): + minint = np.iinfo(x_dtype).min + maxint = np.iinfo(x_dtype).max + x = np.array([-1, maxint], dtype=x_dtype) + f = np.array([minint // 2, 0]) + dfdx = gradient(f, x) + assert_array_equal(dfdx, [0.5, 0.5]) + + +class TestAngle: def test_basic(self): x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2, @@ -1110,7 +1142,7 @@ class TestAngle(object): assert_equal(actual, expected) -class TestTrimZeros(object): +class TestTrimZeros: """ Only testing for integer splits. @@ -1133,7 +1165,7 @@ class TestTrimZeros(object): assert_array_equal(res, np.array([1, 0, 2, 3, 0, 4])) -class TestExtins(object): +class TestExtins: def test_basic(self): a = np.array([1, 3, 2, 1, 2, 3, 3]) @@ -1172,7 +1204,7 @@ class TestExtins(object): assert_array_equal(a, ac) -class TestVectorize(object): +class TestVectorize: def test_simple(self): def addsubtract(a, b): @@ -1504,8 +1536,8 @@ class TestVectorize(object): f(x) -class TestLeaks(object): - class A(object): +class TestLeaks: + class A: iters = 20 def bound(self, *args): @@ -1547,7 +1579,7 @@ class TestLeaks(object): finally: gc.enable() -class TestDigitize(object): +class TestDigitize: def test_forward(self): x = np.arange(-6, 5) @@ -1632,7 +1664,7 @@ class TestDigitize(object): assert_equal(np.digitize(x, [x + 1, x - 1]), 1) -class TestUnwrap(object): +class TestUnwrap: def test_simple(self): # check that unwrap removes jumps greater that 2*pi @@ -1641,7 +1673,7 @@ class TestUnwrap(object): assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi)) -class TestFilterwindows(object): +class TestFilterwindows: def test_hanning(self): # check symmetry @@ -1672,7 +1704,7 @@ class TestFilterwindows(object): assert_almost_equal(np.sum(w, axis=0), 3.7800, 4) -class TestTrapz(object): +class TestTrapz: def test_simple(self): x = np.arange(-10, 10, .1) @@ -1734,7 +1766,7 @@ class TestTrapz(object): assert_almost_equal(trapz(y, xm), r) -class TestSinc(object): +class TestSinc: def test_simple(self): assert_(sinc(0) == 1) @@ -1751,7 +1783,7 @@ class TestSinc(object): assert_array_equal(y1, y3) -class TestUnique(object): +class TestUnique: def test_simple(self): x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0]) @@ -1763,7 +1795,7 @@ class TestUnique(object): assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10])) -class TestCheckFinite(object): +class TestCheckFinite: def test_simple(self): a = [1, 2, 3] @@ -1780,7 +1812,7 @@ class TestCheckFinite(object): assert_(a.dtype == np.float64) -class TestCorrCoef(object): +class TestCorrCoef: A = np.array( [[0.15391142, 0.18045767, 0.14197213], [0.70461506, 0.96474128, 0.27906989], @@ -1865,7 +1897,7 @@ class TestCorrCoef(object): assert_(np.all(np.abs(c) <= 1.0)) -class TestCov(object): +class TestCov: x1 = np.array([[0, 2], [1, 1], [2, 0]]).T res1 = np.array([[1., -1.], [-1., 1.]]) x2 = np.array([0.0, 1.0, 2.0], ndmin=2) @@ -1965,7 +1997,7 @@ class TestCov(object): self.res1) -class Test_I0(object): +class Test_I0: def test_simple(self): assert_almost_equal( @@ -2011,7 +2043,7 @@ class Test_I0(object): assert_array_equal(exp, res) -class TestKaiser(object): +class TestKaiser: def test_simple(self): assert_(np.isfinite(kaiser(1, 1.0))) @@ -2030,7 +2062,7 @@ class TestKaiser(object): kaiser(3, 4) -class TestMsort(object): +class TestMsort: def test_simple(self): A = np.array([[0.44567325, 0.79115165, 0.54900530], @@ -2043,7 +2075,7 @@ class TestMsort(object): [0.64864341, 0.79115165, 0.96098397]])) -class TestMeshgrid(object): +class TestMeshgrid: def test_simple(self): [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7]) @@ -2132,7 +2164,7 @@ class TestMeshgrid(object): assert_equal(x[1, :], X) -class TestPiecewise(object): +class TestPiecewise: def test_simple(self): # Condition is single bool list @@ -2224,7 +2256,7 @@ class TestPiecewise(object): [3., 3., 1.]])) -class TestBincount(object): +class TestBincount: def test_simple(self): y = np.bincount(np.arange(4)) @@ -2311,7 +2343,7 @@ class TestBincount(object): assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount) -class TestInterp(object): +class TestInterp: def test_exceptions(self): assert_raises(ValueError, interp, 0, [], []) @@ -2510,7 +2542,7 @@ def compare_results(res, desired): assert_array_equal(res[i], desired[i]) -class TestPercentile(object): +class TestPercentile: def test_basic(self): x = np.arange(8) * 0.5 @@ -2931,7 +2963,7 @@ class TestPercentile(object): a, [0.3, 0.6], (0, 2), interpolation='nearest'), b) -class TestQuantile(object): +class TestQuantile: # most of this is already tested by TestPercentile def test_basic(self): @@ -2973,7 +3005,7 @@ class TestQuantile(object): assert_array_equal(p, p0) -class TestMedian(object): +class TestMedian: def test_basic(self): a0 = np.array(1) @@ -3212,7 +3244,7 @@ class TestMedian(object): (1, 1, 7, 1)) -class TestAdd_newdoc_ufunc(object): +class TestAdd_newdoc_ufunc: def test_ufunc_arg(self): assert_raises(TypeError, add_newdoc_ufunc, 2, "blah") @@ -3222,7 +3254,7 @@ class TestAdd_newdoc_ufunc(object): assert_raises(TypeError, add_newdoc_ufunc, np.add, 3) -class TestAdd_newdoc(object): +class TestAdd_newdoc: @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO") @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc") @@ -3233,7 +3265,7 @@ class TestAdd_newdoc(object): assert_(len(np.core.ufunc.identity.__doc__) > 300) assert_(len(np.lib.index_tricks.mgrid.__doc__) > 300) -class TestSortComplex(object): +class TestSortComplex: @pytest.mark.parametrize("type_in, type_out", [ ('l', 'D'), diff --git a/numpy/lib/tests/test_histograms.py b/numpy/lib/tests/test_histograms.py index dbf189f3e..c21103891 100644 --- a/numpy/lib/tests/test_histograms.py +++ b/numpy/lib/tests/test_histograms.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.lib.histograms import histogram, histogramdd, histogram_bin_edges @@ -11,7 +9,7 @@ from numpy.testing import ( import pytest -class TestHistogram(object): +class TestHistogram: def setup(self): pass @@ -424,7 +422,7 @@ class TestHistogram(object): assert_array_equal(edges, e) -class TestHistogramOptimBinNums(object): +class TestHistogramOptimBinNums: """ Provide test coverage when using provided estimators for optimal number of bins @@ -612,7 +610,7 @@ class TestHistogramOptimBinNums(object): estimator, weights=[1, 2, 3]) -class TestHistogramdd(object): +class TestHistogramdd: def test_simple(self): x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py index dbe445c2c..905165a99 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest import numpy as np @@ -14,7 +12,7 @@ from numpy.lib.index_tricks import ( ) -class TestRavelUnravelIndex(object): +class TestRavelUnravelIndex: def test_basic(self): assert_equal(np.unravel_index(2, (2, 2)), (1, 0)) @@ -194,7 +192,7 @@ class TestRavelUnravelIndex(object): with assert_raises(ValueError): np.unravel_index([1], (2, 1, 0)) -class TestGrid(object): +class TestGrid: def test_basic(self): a = mgrid[-1:1:10j] b = mgrid[-1:1:0.1] @@ -252,7 +250,7 @@ class TestGrid(object): assert_equal(grid_small.size, expected[1]) -class TestConcatenator(object): +class TestConcatenator: def test_1d(self): assert_array_equal(r_[1, 2, 3, 4, 5, 6], np.array([1, 2, 3, 4, 5, 6])) b = np.ones(5) @@ -290,14 +288,14 @@ class TestConcatenator(object): assert_equal(r_[np.array(0), [1, 2, 3]], [0, 1, 2, 3]) -class TestNdenumerate(object): +class TestNdenumerate: def test_basic(self): a = np.array([[1, 2], [3, 4]]) assert_equal(list(ndenumerate(a)), [((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)]) -class TestIndexExpression(object): +class TestIndexExpression: def test_regression_1(self): # ticket #1196 a = np.arange(2) @@ -311,7 +309,7 @@ class TestIndexExpression(object): assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]]) -class TestIx_(object): +class TestIx_: def test_regression_1(self): # Test empty untyped inputs create outputs of indexing type, gh-5804 a, = np.ix_(range(0)) @@ -358,7 +356,7 @@ def test_c_(): assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]]) -class TestFillDiagonal(object): +class TestFillDiagonal: def test_basic(self): a = np.zeros((3, 3), int) fill_diagonal(a, 5) @@ -457,7 +455,7 @@ def test_diag_indices(): ) -class TestDiagIndicesFrom(object): +class TestDiagIndicesFrom: def test_diag_indices_from(self): x = np.random.random((4, 4)) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index a095e250a..ba27eea6c 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import gzip import os @@ -71,7 +69,7 @@ def strptime(s, fmt=None): return datetime(*time.strptime(s, fmt)[:3]) -class RoundtripTest(object): +class RoundtripTest: def roundtrip(self, save_func, *args, **kwargs): """ save_func : callable @@ -318,7 +316,7 @@ class TestSavezLoad(RoundtripTest): assert_(fp.closed) -class TestSaveTxt(object): +class TestSaveTxt: def test_array(self): a = np.array([[1, 2], [3, 4]], float) fmt = "%.18e" @@ -584,7 +582,7 @@ class TestSaveTxt(object): with tempdir() as tmpdir: np.savez(os.path.join(tmpdir, 'test.npz'), test_data=test_data) -class LoadTxtBase(object): +class LoadTxtBase: def check_compressed(self, fopen, suffixes): # Test that we can load data from a compressed file wanted = np.arange(6).reshape((2, 3)) @@ -826,7 +824,7 @@ class TestLoadTxt(LoadTxtBase): assert_array_equal(x, a[:, 1]) # Testing with some crazy custom integer type - class CrazyInt(object): + class CrazyInt: def __index__(self): return 1 @@ -1158,7 +1156,7 @@ class TestLoadTxt(LoadTxtBase): a = np.array([[1, 2, 3, 5], [4, 5, 7, 8], [2, 1, 4, 5]], int) assert_array_equal(x, a) -class Testfromregex(object): +class Testfromregex: def test_record(self): c = TextIO() c.write('1.312 foo\n1.534 bar\n4.444 qux') @@ -2349,7 +2347,7 @@ M 33 21.99 @pytest.mark.skipif(Path is None, reason="No pathlib.Path") -class TestPathUsage(object): +class TestPathUsage: # Test that pathlib.Path can be used def test_loadtxt(self): with temppath(suffix='.txt') as path: @@ -2482,7 +2480,7 @@ def test_gzip_load(): # These next two classes encode the minimal API needed to save()/load() arrays. # The `test_ducktyping` ensures they work correctly -class JustWriter(object): +class JustWriter: def __init__(self, base): self.base = base @@ -2492,7 +2490,7 @@ class JustWriter(object): def flush(self): return self.base.flush() -class JustReader(object): +class JustReader: def __init__(self, base): self.base = base diff --git a/numpy/lib/tests/test_mixins.py b/numpy/lib/tests/test_mixins.py index 3dd5346b6..7c22dae94 100644 --- a/numpy/lib/tests/test_mixins.py +++ b/numpy/lib/tests/test_mixins.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numbers import operator import sys @@ -98,7 +96,7 @@ _ALL_BINARY_OPERATORS = [ ] -class TestNDArrayOperatorsMixin(object): +class TestNDArrayOperatorsMixin: def test_array_like_add(self): @@ -128,7 +126,7 @@ class TestNDArrayOperatorsMixin(object): def test_opt_out(self): - class OptOut(object): + class OptOut: """Object that opts out of __array_ufunc__.""" __array_ufunc__ = None diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py index da2d0cc52..db563e30c 100644 --- a/numpy/lib/tests/test_nanfunctions.py +++ b/numpy/lib/tests/test_nanfunctions.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import warnings import pytest @@ -37,7 +35,7 @@ _ndat_zeros = np.array([[0.6244, 0.0, 0.2692, 0.0116, 0.0, 0.1170], [0.1610, 0.0, 0.0, 0.1859, 0.3146, 0.0]]) -class TestNanFunctions_MinMax(object): +class TestNanFunctions_MinMax: nanfuncs = [np.nanmin, np.nanmax] stdfuncs = [np.min, np.max] @@ -171,7 +169,7 @@ class TestNanFunctions_MinMax(object): assert_(issubclass(w[0].category, RuntimeWarning)) -class TestNanFunctions_ArgminArgmax(object): +class TestNanFunctions_ArgminArgmax: nanfuncs = [np.nanargmin, np.nanargmax] @@ -233,7 +231,7 @@ class TestNanFunctions_ArgminArgmax(object): assert_(res.shape == ()) -class TestNanFunctions_IntTypes(object): +class TestNanFunctions_IntTypes: int_types = (np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64) @@ -308,7 +306,7 @@ class TestNanFunctions_IntTypes(object): assert_equal(np.nanstd(mat, ddof=1), tgt) -class SharedNanFunctionsTestsMixin(object): +class SharedNanFunctionsTestsMixin: def test_mutation(self): # Check that passed array is not modified. ndat = _ndat.copy() @@ -590,7 +588,7 @@ class TestNanFunctions_MeanVarStd(SharedNanFunctionsTestsMixin): assert_(len(w) == 0) -class TestNanFunctions_Median(object): +class TestNanFunctions_Median: def test_mutation(self): # Check that passed array is not modified. @@ -754,7 +752,7 @@ class TestNanFunctions_Median(object): ([np.nan] * i) + [-inf] * j) -class TestNanFunctions_Percentile(object): +class TestNanFunctions_Percentile: def test_mutation(self): # Check that passed array is not modified. @@ -893,7 +891,7 @@ class TestNanFunctions_Percentile(object): assert_equal(np.nanpercentile(megamat, perc, axis=(1, 2)).shape, (2, 3, 6)) -class TestNanFunctions_Quantile(object): +class TestNanFunctions_Quantile: # most of this is already tested by TestPercentile def test_regression(self): diff --git a/numpy/lib/tests/test_packbits.py b/numpy/lib/tests/test_packbits.py index 95a465c36..5b07f41c6 100644 --- a/numpy/lib/tests/test_packbits.py +++ b/numpy/lib/tests/test_packbits.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_array_equal, assert_equal, assert_raises import pytest diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py index 89759bd83..cd0b90dc4 100644 --- a/numpy/lib/tests/test_polynomial.py +++ b/numpy/lib/tests/test_polynomial.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import ( assert_, assert_equal, assert_array_equal, assert_almost_equal, @@ -7,7 +5,7 @@ from numpy.testing import ( ) -class TestPolynomial(object): +class TestPolynomial: def test_poly1d_str_and_repr(self): p = np.poly1d([1., 2, 3]) assert_equal(repr(p), 'poly1d([1., 2., 3.])') diff --git a/numpy/lib/tests/test_recfunctions.py b/numpy/lib/tests/test_recfunctions.py index 53229e31a..2f3c14df3 100644 --- a/numpy/lib/tests/test_recfunctions.py +++ b/numpy/lib/tests/test_recfunctions.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import pytest import numpy as np @@ -19,7 +17,7 @@ zip_descr = np.lib.recfunctions._zip_descr zip_dtype = np.lib.recfunctions._zip_dtype -class TestRecFunctions(object): +class TestRecFunctions: # Misc tests def setup(self): @@ -348,7 +346,7 @@ class TestRecFunctions(object): assert_equal(b[()], 3) -class TestRecursiveFillFields(object): +class TestRecursiveFillFields: # Test recursive_fill_fields. def test_simple_flexible(self): # Test recursive_fill_fields on flexible-array @@ -371,7 +369,7 @@ class TestRecursiveFillFields(object): assert_equal(test, control) -class TestMergeArrays(object): +class TestMergeArrays: # Test merge_arrays def setup(self): @@ -504,7 +502,7 @@ class TestMergeArrays(object): assert_equal(test, control) -class TestAppendFields(object): +class TestAppendFields: # Test append_fields def setup(self): @@ -558,7 +556,7 @@ class TestAppendFields(object): assert_equal(test, control) -class TestStackArrays(object): +class TestStackArrays: # Test stack_arrays def setup(self): x = np.array([1, 2, ]) @@ -729,7 +727,7 @@ class TestStackArrays(object): assert_equal(res.mask, expected.mask) -class TestJoinBy(object): +class TestJoinBy: def setup(self): self.a = np.array(list(zip(np.arange(10), np.arange(50, 60), np.arange(100, 110))), @@ -894,7 +892,7 @@ class TestJoinBy(object): assert_equal(res.dtype, expected_dtype) -class TestJoinBy2(object): +class TestJoinBy2: @classmethod def setup(cls): cls.a = np.array(list(zip(np.arange(10), np.arange(50, 60), @@ -959,7 +957,7 @@ class TestJoinBy2(object): assert_equal(test.dtype, control.dtype) assert_equal(test, control) -class TestAppendFieldsObj(object): +class TestAppendFieldsObj: """ Test append_fields with arrays containing objects """ diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index 4cd812f5d..019b7595e 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys @@ -11,7 +9,7 @@ from numpy.testing import ( from numpy.compat import unicode -class TestRegression(object): +class TestRegression: def test_poly1d(self): # Ticket #28 assert_equal(np.poly1d([1]) - np.poly1d([1, 0]), diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py index ff9019e3d..fb7ba7874 100644 --- a/numpy/lib/tests/test_shape_base.py +++ b/numpy/lib/tests/test_shape_base.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np import functools import sys @@ -29,7 +27,7 @@ def _add_keepdims(func): return wrapped -class TestTakeAlongAxis(object): +class TestTakeAlongAxis: def test_argequivalent(self): """ Test it translates from arg<func> to <func> """ from numpy.random import rand @@ -81,7 +79,7 @@ class TestTakeAlongAxis(object): assert_equal(actual.shape, (3, 2, 5)) -class TestPutAlongAxis(object): +class TestPutAlongAxis: def test_replace_max(self): a_base = np.array([[10, 30, 20], [60, 40, 50]]) @@ -106,7 +104,7 @@ class TestPutAlongAxis(object): assert_equal(take_along_axis(a, ai, axis=1), 20) -class TestApplyAlongAxis(object): +class TestApplyAlongAxis: def test_simple(self): a = np.ones((20, 10), 'd') assert_array_equal( @@ -272,14 +270,14 @@ class TestApplyAlongAxis(object): assert_equal(type(actual[i]), type(expected[i])) -class TestApplyOverAxes(object): +class TestApplyOverAxes: def test_simple(self): a = np.arange(24).reshape(2, 3, 4) aoa_a = apply_over_axes(np.sum, a, [0, 2]) assert_array_equal(aoa_a, np.array([[[60], [92], [124]]])) -class TestExpandDims(object): +class TestExpandDims: def test_functionality(self): s = (2, 3, 4, 5) a = np.empty(s) @@ -319,7 +317,7 @@ class TestExpandDims(object): assert_equal(expanded.mask.shape, (2, 1, 5)) -class TestArraySplit(object): +class TestArraySplit: def test_integer_0_split(self): a = np.arange(10) assert_raises(ValueError, array_split, a, 0) @@ -453,7 +451,7 @@ class TestArraySplit(object): compare_results(res, desired) -class TestSplit(object): +class TestSplit: # The split function is essentially the same as array_split, # except that it test if splitting will result in an # equal split. Only test for this case. @@ -469,7 +467,7 @@ class TestSplit(object): assert_raises(ValueError, split, a, 3) -class TestColumnStack(object): +class TestColumnStack: def test_non_iterable(self): assert_raises(TypeError, column_stack, 1) @@ -498,7 +496,7 @@ class TestColumnStack(object): column_stack((np.arange(3) for _ in range(2))) -class TestDstack(object): +class TestDstack: def test_non_iterable(self): assert_raises(TypeError, dstack, 1) @@ -537,7 +535,7 @@ class TestDstack(object): # array_split has more comprehensive test of splitting. # only do simple test on hsplit, vsplit, and dsplit -class TestHsplit(object): +class TestHsplit: """Only testing for integer splits. """ @@ -566,7 +564,7 @@ class TestHsplit(object): compare_results(res, desired) -class TestVsplit(object): +class TestVsplit: """Only testing for integer splits. """ @@ -593,7 +591,7 @@ class TestVsplit(object): compare_results(res, desired) -class TestDsplit(object): +class TestDsplit: # Only testing for integer splits. def test_non_iterable(self): assert_raises(ValueError, dsplit, 1, 1) @@ -626,7 +624,7 @@ class TestDsplit(object): compare_results(res, desired) -class TestSqueeze(object): +class TestSqueeze: def test_basic(self): from numpy.random import rand @@ -645,7 +643,7 @@ class TestSqueeze(object): assert_equal(type(res), np.ndarray) -class TestKron(object): +class TestKron: def test_return_type(self): class myarray(np.ndarray): __array_priority__ = 0.0 @@ -658,7 +656,7 @@ class TestKron(object): assert_equal(type(kron(ma, a)), myarray) -class TestTile(object): +class TestTile: def test_basic(self): a = np.array([0, 1, 2]) b = [[1, 2], [3, 4]] @@ -698,7 +696,7 @@ class TestTile(object): assert_equal(large, klarge) -class TestMayShareMemory(object): +class TestMayShareMemory: def test_basic(self): d = np.ones((50, 60)) d2 = np.ones((30, 60, 6)) diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py index 85fcceedc..6131ba5e1 100644 --- a/numpy/lib/tests/test_stride_tricks.py +++ b/numpy/lib/tests/test_stride_tricks.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.core._rational_tests import rational from numpy.testing import ( diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py index bb844e4bd..cce683bfe 100644 --- a/numpy/lib/tests/test_twodim_base.py +++ b/numpy/lib/tests/test_twodim_base.py @@ -1,8 +1,6 @@ """Test functions for matrix module """ -from __future__ import division, absolute_import, print_function - from numpy.testing import ( assert_equal, assert_array_equal, assert_array_max_ulp, assert_array_almost_equal, assert_raises, assert_ @@ -26,7 +24,7 @@ def get_mat(n): return data -class TestEye(object): +class TestEye: def test_basic(self): assert_equal(eye(4), array([[1, 0, 0, 0], @@ -108,7 +106,7 @@ class TestEye(object): assert mat_f.flags.f_contiguous -class TestDiag(object): +class TestDiag: def test_vector(self): vals = (100 * arange(5)).astype('l') b = zeros((5, 5)) @@ -155,7 +153,7 @@ class TestDiag(object): assert_raises(ValueError, diag, [[[1]]]) -class TestFliplr(object): +class TestFliplr: def test_basic(self): assert_raises(ValueError, fliplr, ones(4)) a = get_mat(4) @@ -168,7 +166,7 @@ class TestFliplr(object): assert_equal(fliplr(a), b) -class TestFlipud(object): +class TestFlipud: def test_basic(self): a = get_mat(4) b = a[::-1, :] @@ -180,7 +178,7 @@ class TestFlipud(object): assert_equal(flipud(a), b) -class TestHistogram2d(object): +class TestHistogram2d: def test_simple(self): x = array( [0.41702200, 0.72032449, 1.1437481e-4, 0.302332573, 0.146755891]) @@ -298,7 +296,7 @@ class TestHistogram2d(object): assert_(r, ((ShouldDispatch,), (xy, xy), dict(weights=s_d))) -class TestTri(object): +class TestTri: def test_dtype(self): out = array([[1, 0, 0], [1, 1, 0], @@ -436,7 +434,7 @@ def test_tril_indices(): [-10, -10, -10, -10, -10]])) -class TestTriuIndices(object): +class TestTriuIndices: def test_triu_indices(self): iu1 = triu_indices(4) iu2 = triu_indices(4, k=2) @@ -486,21 +484,21 @@ class TestTriuIndices(object): [16, 17, 18, -1, -1]])) -class TestTrilIndicesFrom(object): +class TestTrilIndicesFrom: def test_exceptions(self): assert_raises(ValueError, tril_indices_from, np.ones((2,))) assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2))) # assert_raises(ValueError, tril_indices_from, np.ones((2, 3))) -class TestTriuIndicesFrom(object): +class TestTriuIndicesFrom: def test_exceptions(self): assert_raises(ValueError, triu_indices_from, np.ones((2,))) assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2))) # assert_raises(ValueError, triu_indices_from, np.ones((2, 3))) -class TestVander(object): +class TestVander: def test_basic(self): c = np.array([0, 1, -2, 3]) v = vander(c) diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py index b3f114b92..47685550a 100644 --- a/numpy/lib/tests/test_type_check.py +++ b/numpy/lib/tests/test_type_check.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.compat import long from numpy.testing import ( @@ -15,7 +13,7 @@ def assert_all(x): assert_(np.all(x), x) -class TestCommonType(object): +class TestCommonType: def test_basic(self): ai32 = np.array([[1, 2], [3, 4]], dtype=np.int32) af16 = np.array([[1, 2], [3, 4]], dtype=np.float16) @@ -31,7 +29,7 @@ class TestCommonType(object): assert_(common_type(acd) == np.cdouble) -class TestMintypecode(object): +class TestMintypecode: def test_default_1(self): for itype in '1bcsuwil': @@ -81,7 +79,7 @@ class TestMintypecode(object): assert_equal(mintypecode('idD'), 'D') -class TestIsscalar(object): +class TestIsscalar: def test_basic(self): assert_(np.isscalar(3)) @@ -92,7 +90,7 @@ class TestIsscalar(object): assert_(np.isscalar(4.0)) -class TestReal(object): +class TestReal: def test_real(self): y = np.random.rand(10,) @@ -123,7 +121,7 @@ class TestReal(object): assert_(not isinstance(out, np.ndarray)) -class TestImag(object): +class TestImag: def test_real(self): y = np.random.rand(10,) @@ -154,7 +152,7 @@ class TestImag(object): assert_(not isinstance(out, np.ndarray)) -class TestIscomplex(object): +class TestIscomplex: def test_fail(self): z = np.array([-1, 0, 1]) @@ -167,7 +165,7 @@ class TestIscomplex(object): assert_array_equal(res, [1, 0, 0]) -class TestIsreal(object): +class TestIsreal: def test_pass(self): z = np.array([-1, 0, 1j]) @@ -180,7 +178,7 @@ class TestIsreal(object): assert_array_equal(res, [0, 1, 1]) -class TestIscomplexobj(object): +class TestIscomplexobj: def test_basic(self): z = np.array([-1, 0, 1]) @@ -209,7 +207,7 @@ class TestIscomplexobj(object): # (pandas.core.dtypes) class PdComplex(np.complex128): pass - class PdDtype(object): + class PdDtype: name = 'category' names = None type = PdComplex @@ -233,7 +231,7 @@ class TestIscomplexobj(object): assert_(iscomplexobj(a)) -class TestIsrealobj(object): +class TestIsrealobj: def test_basic(self): z = np.array([-1, 0, 1]) assert_(isrealobj(z)) @@ -241,7 +239,7 @@ class TestIsrealobj(object): assert_(not isrealobj(z)) -class TestIsnan(object): +class TestIsnan: def test_goodvalues(self): z = np.array((-1., 0., 1.)) @@ -271,7 +269,7 @@ class TestIsnan(object): assert_all(np.isnan(np.array(0+0j)/0.) == 1) -class TestIsfinite(object): +class TestIsfinite: # Fixme, wrong place, isfinite now ufunc def test_goodvalues(self): @@ -302,7 +300,7 @@ class TestIsfinite(object): assert_all(np.isfinite(np.array(1+1j)/0.) == 0) -class TestIsinf(object): +class TestIsinf: # Fixme, wrong place, isinf now ufunc def test_goodvalues(self): @@ -331,7 +329,7 @@ class TestIsinf(object): assert_all(np.isinf(np.array((0.,))/0.) == 0) -class TestIsposinf(object): +class TestIsposinf: def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): @@ -341,7 +339,7 @@ class TestIsposinf(object): assert_(vals[2] == 1) -class TestIsneginf(object): +class TestIsneginf: def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): @@ -351,7 +349,7 @@ class TestIsneginf(object): assert_(vals[2] == 0) -class TestNanToNum(object): +class TestNanToNum: def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): @@ -456,7 +454,7 @@ class TestNanToNum(object): assert_equal(type(vals), np.ndarray) -class TestRealIfClose(object): +class TestRealIfClose: def test_basic(self): a = np.random.rand(10) @@ -469,7 +467,7 @@ class TestRealIfClose(object): assert_all(isrealobj(b)) -class TestArrayConversion(object): +class TestArrayConversion: def test_asfarray(self): a = asfarray(np.array([1, 2, 3])) diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py index 64280616f..c280b6969 100644 --- a/numpy/lib/tests/test_ufunclike.py +++ b/numpy/lib/tests/test_ufunclike.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np import numpy.core as nx import numpy.lib.ufunclike as ufl @@ -8,7 +6,7 @@ from numpy.testing import ( ) -class TestUfunclike(object): +class TestUfunclike: def test_isposinf(self): a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0]) diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py index 9673a05fa..57c840342 100644 --- a/numpy/lib/tests/test_utils.py +++ b/numpy/lib/tests/test_utils.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import inspect import sys import pytest @@ -102,7 +100,7 @@ def test_safe_eval_nameconstant(): utils.safe_eval('None') -class TestByteBounds(object): +class TestByteBounds: def test_byte_bounds(self): # pointer difference matches size * itemsize diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index 2e6d30a1d..320a24856 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -1,8 +1,6 @@ """ Basic functions for manipulating 2d arrays """ -from __future__ import division, absolute_import, print_function - import functools from numpy.core.numeric import ( diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 977117235..13db9adc3 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -1,7 +1,6 @@ """Automatically adapted for numpy Sep 19, 2005 by convertcode.py """ -from __future__ import division, absolute_import, print_function import functools import warnings diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 9f03b1329..8512669c2 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -3,8 +3,6 @@ Module of functions that are like ufuncs in acting on arrays and optionally storing results in an output array. """ -from __future__ import division, absolute_import, print_function - __all__ = ['fix', 'isneginf', 'isposinf'] import numpy.core.numeric as nx diff --git a/numpy/lib/user_array.py b/numpy/lib/user_array.py index f1510a7b1..9c266fd6b 100644 --- a/numpy/lib/user_array.py +++ b/numpy/lib/user_array.py @@ -5,8 +5,6 @@ Try to inherit from the ndarray instead of using this class as this is not complete. """ -from __future__ import division, absolute_import, print_function - from numpy.core import ( array, asarray, absolute, add, subtract, multiply, divide, remainder, power, left_shift, right_shift, bitwise_and, bitwise_or, @@ -16,7 +14,7 @@ from numpy.core import ( from numpy.compat import long -class container(object): +class container: """ container(data, dtype=None, copy=True) diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 3c71d2a7c..d41a6e541 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import os import sys import types @@ -55,7 +53,7 @@ def _set_function_name(func, name): return func -class _Deprecate(object): +class _Deprecate: """ Decorator class to deprecate old functions. diff --git a/numpy/linalg/__init__.py b/numpy/linalg/__init__.py index 55560815d..3a53ac6ec 100644 --- a/numpy/linalg/__init__.py +++ b/numpy/linalg/__init__.py @@ -69,8 +69,6 @@ Exceptions LinAlgError """ -from __future__ import division, absolute_import, print_function - # To get sub-modules from .linalg import * diff --git a/numpy/linalg/lapack_lite/README.rst b/numpy/linalg/lapack_lite/README.rst index 1343d25f8..ba30aa4ed 100644 --- a/numpy/linalg/lapack_lite/README.rst +++ b/numpy/linalg/lapack_lite/README.rst @@ -18,9 +18,9 @@ and is unlikely to ever be ported to python 3. The routines that ``lapack_litemodule.c`` wraps are listed in ``wrapped_routines``, along with a few exceptions that aren't picked up properly. Assuming that you have an unpacked LAPACK source tree in -``~/LAPACK``, you generate the new routines in a directory ``new-lite/`` with:: +``~/LAPACK``, you generate the new routines in this directory with:: -$ python2 ./make_lite.py wrapped_routines ~/LAPACK new-lite/ +$ python2 ./make_lite.py wrapped_routines ~/LAPACK This will grab the right routines, with dependencies, put them into the appropriate ``f2c_*.f`` files, run ``f2c`` over them, then do some scrubbing diff --git a/numpy/linalg/lapack_lite/clapack_scrub.py b/numpy/linalg/lapack_lite/clapack_scrub.py index 434586113..2ddd083ea 100644 --- a/numpy/linalg/lapack_lite/clapack_scrub.py +++ b/numpy/linalg/lapack_lite/clapack_scrub.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, absolute_import, print_function - import sys, os import re from plex import Scanner, Str, Lexicon, Opt, Bol, State, AnyChar, TEXT, IGNORE @@ -106,7 +104,7 @@ def cleanSource(source): source = re.sub(r'\n\n\n\n+', r'\n\n\n', source) return source -class LineQueue(object): +class LineQueue: def __init__(self): object.__init__(self) self._queue = [] diff --git a/numpy/linalg/lapack_lite/f2c.h b/numpy/linalg/lapack_lite/f2c.h index 80f1a12b1..4462eaa74 100644 --- a/numpy/linalg/lapack_lite/f2c.h +++ b/numpy/linalg/lapack_lite/f2c.h @@ -8,15 +8,17 @@ #define F2C_INCLUDE #include <math.h> +#include "numpy/npy_common.h" +#include "npy_cblas.h" -typedef int integer; +typedef CBLAS_INT integer; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; -typedef int logical; +typedef CBLAS_INT logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; @@ -37,9 +39,9 @@ typedef short flag; typedef short ftnlen; typedef short ftnint; #else -typedef int flag; -typedef int ftnlen; -typedef int ftnint; +typedef CBLAS_INT flag; +typedef CBLAS_INT ftnlen; +typedef CBLAS_INT ftnint; #endif /*external read, write*/ @@ -352,7 +354,7 @@ extern void s_copy(char *, char *, ftnlen, ftnlen); extern int s_paus(char *, ftnlen); extern integer s_rdfe(cilist *); extern integer s_rdue(cilist *); -extern integer s_rnge(char *, integer, char *, integer); +extern int s_rnge(char *, int, char *, int); extern integer s_rsfe(cilist *); extern integer s_rsfi(icilist *); extern integer s_rsle(cilist *); diff --git a/numpy/linalg/lapack_lite/fortran.py b/numpy/linalg/lapack_lite/fortran.py index 671f14d24..388c88daa 100644 --- a/numpy/linalg/lapack_lite/fortran.py +++ b/numpy/linalg/lapack_lite/fortran.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import re import itertools @@ -26,7 +24,7 @@ def lineType(line): else: return STATEMENT -class LineIterator(object): +class LineIterator: """LineIterator(iterable) Return rstrip()'d lines from iterable, while keeping a count of the @@ -49,7 +47,7 @@ class LineIterator(object): next = __next__ -class PushbackIterator(object): +class PushbackIterator: """PushbackIterator(iterable) Return an iterator for which items can be pushed back into. diff --git a/numpy/linalg/lapack_lite/make_lite.py b/numpy/linalg/lapack_lite/make_lite.py index 61102d6ab..4b1a0ad82 100755 --- a/numpy/linalg/lapack_lite/make_lite.py +++ b/numpy/linalg/lapack_lite/make_lite.py @@ -11,8 +11,6 @@ Requires the following to be on the path: * patch """ -from __future__ import division, absolute_import, print_function - import sys import os import subprocess @@ -65,7 +63,7 @@ them. #endif ''' -class FortranRoutine(object): +class FortranRoutine: """Wrapper for a Fortran routine in a file. """ type = 'generic' @@ -97,7 +95,7 @@ class UnknownFortranRoutine(FortranRoutine): def dependencies(self): return [] -class FortranLibrary(object): +class FortranLibrary: """Container for a bunch of Fortran routines. """ def __init__(self, src_dirs): diff --git a/numpy/linalg/lapack_litemodule.c b/numpy/linalg/lapack_litemodule.c index 4c80317f5..362a593a6 100644 --- a/numpy/linalg/lapack_litemodule.c +++ b/numpy/linalg/lapack_litemodule.c @@ -377,7 +377,6 @@ static struct PyMethodDef lapack_lite_module_methods[] = { }; -#if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "lapack_lite", @@ -389,32 +388,25 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif /* Initialization function for the module */ -#if PY_MAJOR_VERSION >= 3 -#define RETVAL(x) x PyMODINIT_FUNC PyInit_lapack_lite(void) -#else -#define RETVAL(x) -PyMODINIT_FUNC -initlapack_lite(void) -#endif { PyObject *m,*d; -#if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); -#else - m = Py_InitModule4("lapack_lite", lapack_lite_module_methods, - "", (PyObject*)NULL,PYTHON_API_VERSION); -#endif if (m == NULL) { - return RETVAL(NULL); + return NULL; } import_array(); d = PyModule_GetDict(m); LapackError = PyErr_NewException("lapack_lite.LapackError", NULL, NULL); PyDict_SetItemString(d, "LapackError", LapackError); - return RETVAL(m); +#ifdef HAVE_BLAS_ILP64 + PyDict_SetItemString(d, "_ilp64", Py_True); +#else + PyDict_SetItemString(d, "_ilp64", Py_False); +#endif + + return m; } diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index 072670d5c..15615e1a3 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -8,8 +8,6 @@ version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ -from __future__ import division, absolute_import, print_function - __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det', diff --git a/numpy/linalg/setup.py b/numpy/linalg/setup.py index 6315a34b4..66eed41b0 100644 --- a/numpy/linalg/setup.py +++ b/numpy/linalg/setup.py @@ -1,11 +1,9 @@ -from __future__ import division, print_function - import os import sys def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration - from numpy.distutils.system_info import get_info + from numpy.distutils.system_info import get_info, system_info config = Configuration('linalg', parent_package, top_path) config.add_data_dir('tests') @@ -31,8 +29,23 @@ def configuration(parent_package='', top_path=None): else: lapack_info = get_info('lapack_opt', 0) # and {} + use_lapack_lite = not lapack_info + + if use_lapack_lite: + # This makes numpy.distutils write the fact that lapack_lite + # is being used to numpy.__config__ + class numpy_linalg_lapack_lite(system_info): + def calc_info(self): + info = {'language': 'c'} + if sys.maxsize > 2**32: + # Build lapack-lite in 64-bit integer mode + info['define_macros'] = [('HAVE_BLAS_ILP64', None)] + self.set_info(**info) + + lapack_info = numpy_linalg_lapack_lite().get_info(2) + def get_lapack_lite_sources(ext, build_dir): - if not lapack_info: + if use_lapack_lite: print("### Warning: Using unoptimized lapack ###") return all_sources else: diff --git a/numpy/linalg/tests/test_build.py b/numpy/linalg/tests/test_build.py index 921390da3..cbf3089bc 100644 --- a/numpy/linalg/tests/test_build.py +++ b/numpy/linalg/tests/test_build.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from subprocess import PIPE, Popen import sys import re @@ -9,7 +7,7 @@ from numpy.linalg import lapack_lite from numpy.testing import assert_ -class FindDependenciesLdd(object): +class FindDependenciesLdd: def __init__(self): self.cmd = ['ldd'] @@ -41,7 +39,7 @@ class FindDependenciesLdd(object): return founds -class TestF77Mismatch(object): +class TestF77Mismatch: @pytest.mark.skipif(not(sys.platform[:5] == 'linux'), reason="no fortran compiler on non-Linux platform") diff --git a/numpy/linalg/tests/test_deprecations.py b/numpy/linalg/tests/test_deprecations.py index e12755e0d..cd4c10832 100644 --- a/numpy/linalg/tests/test_deprecations.py +++ b/numpy/linalg/tests/test_deprecations.py @@ -1,8 +1,6 @@ """Test deprecation and future warnings. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_warns diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py index ef05b595e..59c71d196 100644 --- a/numpy/linalg/tests/test_linalg.py +++ b/numpy/linalg/tests/test_linalg.py @@ -1,8 +1,6 @@ """ Test functions for linalg module """ -from __future__ import division, absolute_import, print_function - import os import sys import itertools @@ -68,7 +66,7 @@ all_tags = { } -class LinalgCase(object): +class LinalgCase: def __init__(self, name, a, b, tags=set()): """ A bundle of arguments to be passed to a test case, with an identifying @@ -333,7 +331,7 @@ CASES += _make_strided_cases() # # Test different routines against the above cases # -class LinalgTestCase(object): +class LinalgTestCase: TEST_CASES = CASES def check_cases(self, require=set(), exclude=set()): @@ -634,7 +632,7 @@ class TestEig(EigCases): assert_(isinstance(a, np.ndarray)) -class SVDBaseTests(object): +class SVDBaseTests: hermitian = False @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) @@ -976,7 +974,7 @@ class TestLstsq(LstsqCases): @pytest.mark.parametrize('dt', [np.dtype(c) for c in '?bBhHiIqQefdgFDGO']) -class TestMatrixPower(object): +class TestMatrixPower: rshft_0 = np.eye(4) rshft_1 = rshft_0[[3, 0, 1, 2]] @@ -1076,7 +1074,7 @@ class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase): assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype)) -class TestEigvalsh(object): +class TestEigvalsh: @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) def test_types(self, dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) @@ -1152,7 +1150,7 @@ class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase): rtol=get_rtol(ev.dtype), err_msg=repr(a)) -class TestEigh(object): +class TestEigh: @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) def test_types(self, dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) @@ -1211,7 +1209,7 @@ class TestEigh(object): assert_(isinstance(a, np.ndarray)) -class _TestNormBase(object): +class _TestNormBase: dt = None dec = None @@ -1497,7 +1495,7 @@ class _TestNorm(_TestNorm2D, _TestNormGeneral): pass -class TestNorm_NonSystematic(object): +class TestNorm_NonSystematic: def test_longdouble_norm(self): # Non-regression test: p-norm of longdouble would previously raise @@ -1552,7 +1550,7 @@ class TestNormInt64(_TestNorm, _TestNormInt64Base): pass -class TestMatrixRank(object): +class TestMatrixRank: def test_matrix_rank(self): # Full rank matrix @@ -1601,7 +1599,7 @@ def test_reduced_rank(): assert_equal(matrix_rank(X), 8) -class TestQR(object): +class TestQR: # Define the array class here, so run this on matrices elsewhere. array = np.array @@ -1701,7 +1699,7 @@ class TestQR(object): self.check_qr(m2.T) -class TestCholesky(object): +class TestCholesky: # TODO: are there no other tests for cholesky? def test_basic_property(self): @@ -1863,7 +1861,7 @@ def test_sdot_bug_8577(): subprocess.check_call([sys.executable, "-c", code]) -class TestMultiDot(object): +class TestMultiDot: def test_basic_function_with_three_arguments(self): # multi_dot with three arguments uses a fast hand coded algorithm to @@ -1957,7 +1955,7 @@ class TestMultiDot(object): assert_raises(ValueError, multi_dot, [np.random.random((3, 3))]) -class TestTensorinv(object): +class TestTensorinv: @pytest.mark.parametrize("arr, ind", [ (np.ones((4, 6, 8, 2)), 2), diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py index bd3a45872..1ae207b49 100644 --- a/numpy/linalg/tests/test_regression.py +++ b/numpy/linalg/tests/test_regression.py @@ -1,7 +1,5 @@ """ Test functions for linalg module """ -from __future__ import division, absolute_import, print_function - import warnings import numpy as np @@ -12,7 +10,7 @@ from numpy.testing import ( ) -class TestRegression(object): +class TestRegression: def test_eig_build(self): # Ticket #652 diff --git a/numpy/linalg/umath_linalg.c.src b/numpy/linalg/umath_linalg.c.src index e864c541b..00ff6b7a8 100644 --- a/numpy/linalg/umath_linalg.c.src +++ b/numpy/linalg/umath_linalg.c.src @@ -3626,7 +3626,6 @@ static PyMethodDef UMath_LinAlgMethods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; -#if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, UMATH_LINALG_MODULE_NAME, @@ -3638,29 +3637,17 @@ static struct PyModuleDef moduledef = { NULL, NULL }; -#endif -#if defined(NPY_PY3K) -#define RETVAL(x) x PyObject *PyInit__umath_linalg(void) -#else -#define RETVAL(x) -PyMODINIT_FUNC -init_umath_linalg(void) -#endif { PyObject *m; PyObject *d; PyObject *version; init_constants(); -#if defined(NPY_PY3K) m = PyModule_Create(&moduledef); -#else - m = Py_InitModule(UMATH_LINALG_MODULE_NAME, UMath_LinAlgMethods); -#endif if (m == NULL) { - return RETVAL(NULL); + return NULL; } import_array(); @@ -3678,8 +3665,8 @@ init_umath_linalg(void) if (PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load _umath_linalg module."); - return RETVAL(NULL); + return NULL; } - return RETVAL(m); + return m; } diff --git a/numpy/ma/__init__.py b/numpy/ma/__init__.py index 36ceb1f6e..870cc4ef2 100644 --- a/numpy/ma/__init__.py +++ b/numpy/ma/__init__.py @@ -39,8 +39,6 @@ may now proceed to calculate the mean of the other values: .. moduleauthor:: Jarrod Millman """ -from __future__ import division, absolute_import, print_function - from . import core from .core import * diff --git a/numpy/ma/bench.py b/numpy/ma/bench.py index a9ba42dea..a1363d4d9 100644 --- a/numpy/ma/bench.py +++ b/numpy/ma/bench.py @@ -1,8 +1,6 @@ #! /usr/bin/env python # -*- coding: utf-8 -*- -from __future__ import division, print_function - import timeit import numpy diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 2baf547a4..d51d8e6ec 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -20,8 +20,6 @@ Released for unlimited redistribution. """ # pylint: disable-msg=E1002 -from __future__ import division, absolute_import, print_function - import sys import operator import warnings @@ -800,7 +798,7 @@ ufunc_domain = {} ufunc_fills = {} -class _DomainCheckInterval(object): +class _DomainCheckInterval: """ Define a valid interval, so that : @@ -825,7 +823,7 @@ class _DomainCheckInterval(object): umath.less(x, self.a)) -class _DomainTan(object): +class _DomainTan: """ Define a valid interval for the `tan` function, so that: @@ -843,7 +841,7 @@ class _DomainTan(object): return umath.less(umath.absolute(umath.cos(x)), self.eps) -class _DomainSafeDivide(object): +class _DomainSafeDivide: """ Define a domain for safe division. @@ -864,7 +862,7 @@ class _DomainSafeDivide(object): return umath.absolute(a) * self.tolerance >= umath.absolute(b) -class _DomainGreater(object): +class _DomainGreater: """ DomainGreater(v)(x) is True where x <= v. @@ -880,7 +878,7 @@ class _DomainGreater(object): return umath.less_equal(x, self.critical_value) -class _DomainGreaterEqual(object): +class _DomainGreaterEqual: """ DomainGreaterEqual(v)(x) is True where x < v. @@ -896,7 +894,7 @@ class _DomainGreaterEqual(object): return umath.less(x, self.critical_value) -class _MaskedUFunc(object): +class _MaskedUFunc: def __init__(self, ufunc): self.f = ufunc self.__doc__ = ufunc.__doc__ @@ -2386,7 +2384,7 @@ def masked_invalid(a, copy=True): ############################################################################### -class _MaskedPrintOption(object): +class _MaskedPrintOption: """ Handle the string used to represent missing data in a masked array. @@ -2604,7 +2602,7 @@ def _arraymethod(funcname, onmask=True): return wrapped_method -class MaskedIterator(object): +class MaskedIterator: """ Flat iterator object to iterate over masked arrays. @@ -6646,7 +6644,7 @@ ptp.__doc__ = MaskedArray.ptp.__doc__ ############################################################################## -class _frommethod(object): +class _frommethod: """ Define functions from existing MaskedArray methods. @@ -7980,7 +7978,7 @@ def fromflex(fxarray): return masked_array(fxarray['_data'], mask=fxarray['_mask']) -class _convert2ma(object): +class _convert2ma: """ Convert functions from numpy to numpy.ma. diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index f4a914471..31648fb2e 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -8,8 +8,6 @@ A collection of utilities for `numpy.ma`. :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ -from __future__ import division, absolute_import, print_function - __all__ = [ 'apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', @@ -214,7 +212,7 @@ def masked_all_like(arr): #####-------------------------------------------------------------------------- #---- --- Standard functions --- #####-------------------------------------------------------------------------- -class _fromnxfunction(object): +class _fromnxfunction: """ Defines a wrapper to adapt NumPy functions to masked arrays. diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py index ae1a12c2c..4ff7866ab 100644 --- a/numpy/ma/mrecords.py +++ b/numpy/ma/mrecords.py @@ -8,8 +8,6 @@ and the masking of individual fields. .. moduleauthor:: Pierre Gerard-Marchant """ -from __future__ import division, absolute_import, print_function - # We should make sure that no field is called '_mask','mask','_fieldmask', # or whatever restricted keywords. An idea would be to no bother in the # first place, and then rename the invalid fields with a trailing @@ -87,7 +85,7 @@ def _get_fieldmask(self): return fdmask -class MaskedRecords(MaskedArray, object): +class MaskedRecords(MaskedArray): """ Attributes diff --git a/numpy/ma/setup.py b/numpy/ma/setup.py index d1d6c89b5..af1e419b4 100644 --- a/numpy/ma/setup.py +++ b/numpy/ma/setup.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('ma', parent_package, top_path) diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index b72ce56aa..458b78580 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -4,8 +4,6 @@ :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu """ -from __future__ import division, absolute_import, print_function - __author__ = "Pierre GF Gerard-Marchant" import sys @@ -65,7 +63,7 @@ num_dts = [np.dtype(dt_) for dt_ in '?bhilqBHILQefdgFD'] num_ids = [dt_.char for dt_ in num_dts] -class TestMaskedArray(object): +class TestMaskedArray: # Base test class for MaskedArrays. def setup(self): @@ -946,7 +944,7 @@ class TestMaskedArray(object): assert_(mx2[0] == 0.) -class TestMaskedArrayArithmetic(object): +class TestMaskedArrayArithmetic: # Base test class for MaskedArrays. def setup(self): @@ -1715,7 +1713,7 @@ class TestMaskedArrayArithmetic(object): assert_equal(a.mask, [0, 0, 0, 0, 1]) -class TestMaskedArrayAttributes(object): +class TestMaskedArrayAttributes: def test_keepmask(self): # Tests the keep mask flag @@ -1891,7 +1889,7 @@ class TestMaskedArrayAttributes(object): assert_equal(m._mask, np.ma.nomask) -class TestFillingValues(object): +class TestFillingValues: def test_check_on_scalar(self): # Test _check_fill_value set to valid and invalid values @@ -2229,7 +2227,7 @@ class TestFillingValues(object): assert_equal(a["f1"].fill_value, default_fill_value("eggs")) -class TestUfuncs(object): +class TestUfuncs: # Test class for the application of ufuncs on MaskedArrays. def setup(self): @@ -2309,7 +2307,7 @@ class TestUfuncs(object): assert_raises(TypeError, operator.mul, a, "abc") assert_raises(TypeError, operator.truediv, a, "abc") - class MyClass(object): + class MyClass: __array_priority__ = a.__array_priority__ + 1 def __mul__(self, other): @@ -2323,7 +2321,7 @@ class TestUfuncs(object): assert_(a * me == "My rmul") # and that __array_priority__ is respected - class MyClass2(object): + class MyClass2: __array_priority__ = 100 def __mul__(self, other): @@ -2373,7 +2371,7 @@ class TestUfuncs(object): # also check that allclose uses ma ufuncs, to avoid warning allclose(m, 0.5) -class TestMaskedArrayInPlaceArithmetics(object): +class TestMaskedArrayInPlaceArithmetics: # Test MaskedArray Arithmetics def setup(self): @@ -2875,7 +2873,7 @@ class TestMaskedArrayInPlaceArithmetics(object): assert_equal(len(w), 0, "Failed on type=%s." % t) -class TestMaskedArrayMethods(object): +class TestMaskedArrayMethods: # Test class for miscellaneous MaskedArrays methods. def setup(self): # Base data definition. @@ -3582,7 +3580,7 @@ class TestMaskedArrayMethods(object): assert_equal(xd.data, x.diagonal().data) -class TestMaskedArrayMathMethods(object): +class TestMaskedArrayMathMethods: def setup(self): # Base data definition. @@ -3860,7 +3858,7 @@ class TestMaskedArrayMathMethods(object): assert_equal(a.max(1), [3, 6]) -class TestMaskedArrayMathMethodsComplex(object): +class TestMaskedArrayMathMethodsComplex: # Test class for miscellaneous MaskedArrays methods. def setup(self): # Base data definition. @@ -3913,7 +3911,7 @@ class TestMaskedArrayMathMethodsComplex(object): mX[:, k].compressed().std()) -class TestMaskedArrayFunctions(object): +class TestMaskedArrayFunctions: # Test class for miscellaneous functions. def setup(self): @@ -4552,7 +4550,7 @@ class TestMaskedArrayFunctions(object): assert_equal(test, masked_equal([-1, -1, -1, -1, -1], -1)) -class TestMaskedFields(object): +class TestMaskedFields: def setup(self): ilist = [1, 2, 3, 4, 5] @@ -4714,7 +4712,7 @@ class TestMaskedFields(object): assert_equal(len(rec), len(self.data['ddtype'])) -class TestMaskedObjectArray(object): +class TestMaskedObjectArray: def test_getitem(self): arr = np.ma.array([None, None]) @@ -4762,7 +4760,7 @@ class TestMaskedObjectArray(object): assert_(arr[0] is np.ma.masked) -class TestMaskedView(object): +class TestMaskedView: def setup(self): iterator = list(zip(np.arange(10), np.random.rand(10))) @@ -4840,7 +4838,7 @@ class TestMaskedView(object): assert_(not isinstance(test, MaskedArray)) -class TestOptionalArgs(object): +class TestOptionalArgs: def test_ndarrayfuncs(self): # test axis arg behaves the same as ndarray (including multiple axes) @@ -4927,7 +4925,7 @@ class TestOptionalArgs(object): assert_raises(np.AxisError, count, np.ma.array(1), axis=1) -class TestMaskedConstant(object): +class TestMaskedConstant: def _do_add_test(self, add): # sanity check assert_(add(np.ma.masked, 1) is np.ma.masked) @@ -5044,7 +5042,7 @@ class TestMaskedConstant(object): assert_raises(AttributeError, setattr, np.ma.masked, 'dtype', np.int64) -class TestMaskedWhereAliases(object): +class TestMaskedWhereAliases: # TODO: Test masked_object, masked_equal, ... diff --git a/numpy/ma/tests/test_deprecations.py b/numpy/ma/tests/test_deprecations.py index 72cc29aa0..14f697375 100644 --- a/numpy/ma/tests/test_deprecations.py +++ b/numpy/ma/tests/test_deprecations.py @@ -1,14 +1,12 @@ """Test deprecation and future warnings. """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_warns from numpy.ma.testutils import assert_equal from numpy.ma.core import MaskedArrayFutureWarning -class TestArgsort(object): +class TestArgsort: """ gh-8701 """ def _test_base(self, argsort, cls): arr_0d = np.array(1).view(cls) @@ -37,7 +35,7 @@ class TestArgsort(object): return self._test_base(np.ma.MaskedArray.argsort, np.ma.MaskedArray) -class TestMinimumMaximum(object): +class TestMinimumMaximum: def test_minimum(self): assert_warns(DeprecationWarning, np.ma.minimum, np.ma.array([1, 2])) diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py index c75c47801..1c8610625 100644 --- a/numpy/ma/tests/test_extras.py +++ b/numpy/ma/tests/test_extras.py @@ -7,8 +7,6 @@ Adapted from the original test_ma by Pierre Gerard-Marchant :version: $Id: test_extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ -from __future__ import division, absolute_import, print_function - import warnings import itertools import pytest @@ -34,7 +32,7 @@ from numpy.ma.extras import ( ) -class TestGeneric(object): +class TestGeneric: # def test_masked_all(self): # Tests masked_all @@ -142,7 +140,7 @@ class TestGeneric(object): assert_equal(test, []) -class TestAverage(object): +class TestAverage: # Several tests of average. Why so many ? Good point... def test_testAverage1(self): # Test of average. @@ -273,7 +271,7 @@ class TestAverage(object): assert_almost_equal(wav1.imag, expected1.imag) -class TestConcatenator(object): +class TestConcatenator: # Tests for mr_, the equivalent of r_ for masked arrays. def test_1d(self): @@ -317,7 +315,7 @@ class TestConcatenator(object): assert_equal(actual.data[:2], [1, 2]) -class TestNotMasked(object): +class TestNotMasked: # Tests notmasked_edges and notmasked_contiguous. def test_edges(self): @@ -387,7 +385,7 @@ class TestNotMasked(object): ]) -class TestCompressFunctions(object): +class TestCompressFunctions: def test_compress_nd(self): # Tests compress_nd @@ -652,7 +650,7 @@ class TestCompressFunctions(object): assert_equal(a, res) -class TestApplyAlongAxis(object): +class TestApplyAlongAxis: # Tests 2D functions def test_3d(self): a = arange(12.).reshape(2, 2, 3) @@ -674,7 +672,7 @@ class TestApplyAlongAxis(object): assert_equal(xa, [[2, 5], [8, 11]]) -class TestApplyOverAxes(object): +class TestApplyOverAxes: # Tests apply_over_axes def test_basic(self): a = arange(24).reshape(2, 3, 4) @@ -687,7 +685,7 @@ class TestApplyOverAxes(object): assert_equal(test, ctrl) -class TestMedian(object): +class TestMedian: def test_pytype(self): r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1) assert_equal(r, np.inf) @@ -1066,7 +1064,7 @@ class TestMedian(object): assert_(type(np.ma.median(o.astype(object))), float) -class TestCov(object): +class TestCov: def setup(self): self.data = array(np.random.rand(12)) @@ -1133,7 +1131,7 @@ class TestCov(object): x.shape[0] / frac)) -class TestCorrcoef(object): +class TestCorrcoef: def setup(self): self.data = array(np.random.rand(12)) @@ -1240,7 +1238,7 @@ class TestCorrcoef(object): control[:-1, :-1]) -class TestPolynomial(object): +class TestPolynomial: # def test_polyfit(self): # Tests polyfit @@ -1298,7 +1296,7 @@ class TestPolynomial(object): assert_almost_equal(a, a_) -class TestArraySetOps(object): +class TestArraySetOps: def test_unique_onlist(self): # Test unique on list @@ -1530,7 +1528,7 @@ class TestArraySetOps(object): assert_array_equal(setdiff1d(a, b), np.array(['c'])) -class TestShapeBase(object): +class TestShapeBase: def test_atleast_2d(self): # Test atleast_2d @@ -1586,7 +1584,7 @@ class TestShapeBase(object): assert_equal(b.mask.shape, b.data.shape) -class TestStack(object): +class TestStack: def test_stack_1d(self): a = masked_array([0, 1, 2], mask=[0, 1, 0]) diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py index 94e772d55..c2f859273 100644 --- a/numpy/ma/tests/test_mrecords.py +++ b/numpy/ma/tests/test_mrecords.py @@ -5,8 +5,6 @@ :contact: pierregm_at_uga_dot_edu """ -from __future__ import division, absolute_import, print_function - import numpy as np import numpy.ma as ma from numpy import recarray @@ -26,7 +24,7 @@ from numpy.ma.testutils import ( from numpy.compat import pickle -class TestMRecords(object): +class TestMRecords: ilist = [1, 2, 3, 4, 5] flist = [1.1, 2.2, 3.3, 4.4, 5.5] @@ -348,7 +346,7 @@ class TestMRecords(object): dtype=mult.dtype)) -class TestView(object): +class TestView: def setup(self): (a, b) = (np.arange(10), np.random.rand(10)) @@ -386,7 +384,7 @@ class TestView(object): ############################################################################## -class TestMRecordsImport(object): +class TestMRecordsImport: _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int) _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float) diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py index 7100eccbb..96c7e3609 100644 --- a/numpy/ma/tests/test_old_ma.py +++ b/numpy/ma/tests/test_old_ma.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -33,7 +31,7 @@ def eq(v, w, msg=''): return result -class TestMa(object): +class TestMa: def setup(self): x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) @@ -700,7 +698,7 @@ class TestMa(object): assert_equal(b[1].shape, ()) -class TestUfuncs(object): +class TestUfuncs: def setup(self): self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6), array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),) @@ -765,7 +763,7 @@ class TestUfuncs(object): assert_(eq(nonzero(x), [0])) -class TestArrayMethods(object): +class TestArrayMethods: def setup(self): x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928, diff --git a/numpy/ma/tests/test_regression.py b/numpy/ma/tests/test_regression.py index b83873a5a..9f3368489 100644 --- a/numpy/ma/tests/test_regression.py +++ b/numpy/ma/tests/test_regression.py @@ -1,12 +1,10 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import ( assert_, assert_array_equal, assert_allclose, suppress_warnings ) -class TestRegression(object): +class TestRegression: def test_masked_array_create(self): # Ticket #17 x = np.ma.masked_array([0, 1, 2, 3, 0, 4, 5, 6], diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py index 440b36722..02aeebd17 100644 --- a/numpy/ma/tests/test_subclassing.py +++ b/numpy/ma/tests/test_subclassing.py @@ -6,8 +6,6 @@ :version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_, assert_raises from numpy.ma.testutils import assert_equal @@ -80,7 +78,7 @@ msubarray = MSubArray # and overrides __array_wrap__, updating the info dict, to check that this # doesn't get destroyed by MaskedArray._update_from. But this one also needs # its own iterator... -class CSAIterator(object): +class CSAIterator: """ Flat iterator object that uses its own setter/getter (works around ndarray.flat not propagating subclass setters/getters @@ -154,7 +152,7 @@ class ComplicatedSubArray(SubArray): return obj -class TestSubclassing(object): +class TestSubclassing: # Test suite for masked subclasses of ndarray. def setup(self): diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py index c0deaa9f4..51ab03948 100644 --- a/numpy/ma/testutils.py +++ b/numpy/ma/testutils.py @@ -5,8 +5,6 @@ :version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $ """ -from __future__ import division, absolute_import, print_function - import operator import numpy as np diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py index 4ad635e38..83bd7852e 100644 --- a/numpy/ma/timer_comparison.py +++ b/numpy/ma/timer_comparison.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import timeit from functools import reduce @@ -15,7 +13,7 @@ np.seterr(all='ignore') pi = np.pi -class ModuleTester(object): +class ModuleTester: def __init__(self, module): self.module = module self.allequal = module.allequal diff --git a/numpy/matlib.py b/numpy/matlib.py index b1b155586..f3eb8eb4b 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.matrixlib.defmatrix import matrix, asmatrix # need * as we're copying the numpy namespace (FIXME: this makes little sense) diff --git a/numpy/matrixlib/__init__.py b/numpy/matrixlib/__init__.py index 777e0cd33..54154d11f 100644 --- a/numpy/matrixlib/__init__.py +++ b/numpy/matrixlib/__init__.py @@ -1,8 +1,6 @@ """Sub-package containing the matrix class and related functions. """ -from __future__ import division, absolute_import, print_function - from .defmatrix import * __all__ = defmatrix.__all__ diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py index cabd41367..12ac74cb2 100644 --- a/numpy/matrixlib/defmatrix.py +++ b/numpy/matrixlib/defmatrix.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] import sys diff --git a/numpy/matrixlib/setup.py b/numpy/matrixlib/setup.py index d0981d658..c4eee4be4 100644 --- a/numpy/matrixlib/setup.py +++ b/numpy/matrixlib/setup.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, print_function - def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matrixlib', parent_package, top_path) diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py index aa6e08d64..a8070898f 100644 --- a/numpy/matrixlib/tests/test_defmatrix.py +++ b/numpy/matrixlib/tests/test_defmatrix.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - try: # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 @@ -16,7 +14,7 @@ from numpy.testing import ( from numpy.linalg import matrix_power from numpy.matrixlib import mat -class TestCtor(object): +class TestCtor: def test_basic(self): A = np.array([[1, 2], [3, 4]]) mA = matrix(A) @@ -63,7 +61,7 @@ class TestCtor(object): assert_(np.all(b2 == mixresult)) -class TestProperties(object): +class TestProperties: def test_sum(self): """Test whether matrix.sum(axis=1) preserves orientation. Fails in NumPy <= 0.9.6.2127. @@ -196,7 +194,7 @@ class TestProperties(object): B = matrix([[True], [True], [False]]) assert_array_equal(A, B) -class TestCasting(object): +class TestCasting: def test_basic(self): A = np.arange(100).reshape(10, 10) mA = matrix(A) @@ -215,7 +213,7 @@ class TestCasting(object): assert_(np.all(mA != mB)) -class TestAlgebra(object): +class TestAlgebra: def test_basic(self): import numpy.linalg as linalg @@ -274,7 +272,7 @@ class TestAlgebra(object): A*object() -class TestMatrixReturn(object): +class TestMatrixReturn: def test_instance_methods(self): a = matrix([1.0], dtype='f8') methodargs = { @@ -316,7 +314,7 @@ class TestMatrixReturn(object): assert_(type(d) is np.ndarray) -class TestIndexing(object): +class TestIndexing: def test_basic(self): x = asmatrix(np.zeros((3, 2), float)) y = np.zeros((3, 1), float) @@ -325,7 +323,7 @@ class TestIndexing(object): assert_equal(x, [[0, 1], [0, 0], [0, 0]]) -class TestNewScalarIndexing(object): +class TestNewScalarIndexing: a = matrix([[1, 2], [3, 4]]) def test_dimesions(self): @@ -392,7 +390,7 @@ class TestNewScalarIndexing(object): assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) -class TestPower(object): +class TestPower: def test_returntype(self): a = np.array([[0, 1], [0, 0]]) assert_(type(matrix_power(a, 2)) is np.ndarray) @@ -403,7 +401,7 @@ class TestPower(object): assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]]) -class TestShape(object): +class TestShape: a = np.array([[1], [2]]) m = matrix([[1], [2]]) diff --git a/numpy/matrixlib/tests/test_interaction.py b/numpy/matrixlib/tests/test_interaction.py index 088ae3c6a..608416ed7 100644 --- a/numpy/matrixlib/tests/test_interaction.py +++ b/numpy/matrixlib/tests/test_interaction.py @@ -2,8 +2,6 @@ Note that tests with MaskedArray and linalg are done in separate files. """ -from __future__ import division, absolute_import, print_function - import pytest import textwrap @@ -290,7 +288,7 @@ def test_kron_matrix(): assert_equal(type(np.kron(m, a)), np.matrix) -class TestConcatenatorMatrix(object): +class TestConcatenatorMatrix: # 2018-04-29: moved here from core.tests.test_index_tricks. def test_matrix(self): a = [1, 2] diff --git a/numpy/matrixlib/tests/test_masked_matrix.py b/numpy/matrixlib/tests/test_masked_matrix.py index d3911d2e1..45424ecf0 100644 --- a/numpy/matrixlib/tests/test_masked_matrix.py +++ b/numpy/matrixlib/tests/test_masked_matrix.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.ma.testutils import (assert_, assert_equal, assert_raises, assert_array_equal) @@ -29,7 +27,7 @@ class MMatrix(MaskedArray, np.matrix,): return _view -class TestMaskedMatrix(object): +class TestMaskedMatrix: def test_matrix_indexing(self): # Tests conversions and indexing x1 = np.matrix([[1, 2, 3], [4, 3, 2]]) @@ -171,7 +169,7 @@ class TestMaskedMatrix(object): assert_(not isinstance(test, MaskedArray)) -class TestSubclassing(object): +class TestSubclassing: # Test suite for masked subclasses of ndarray. def setup(self): @@ -212,7 +210,7 @@ class TestSubclassing(object): assert_(isinstance(divide(mx, x), MMatrix)) assert_equal(divide(mx, mx), divide(xmx, xmx)) -class TestConcatenator(object): +class TestConcatenator: # Tests for mr_, the equivalent of r_ for masked arrays. def test_matrix_builder(self): diff --git a/numpy/matrixlib/tests/test_matrix_linalg.py b/numpy/matrixlib/tests/test_matrix_linalg.py index 6fc733c2e..106c2e382 100644 --- a/numpy/matrixlib/tests/test_matrix_linalg.py +++ b/numpy/matrixlib/tests/test_matrix_linalg.py @@ -1,6 +1,4 @@ """ Test functions for linalg module using the matrix class.""" -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.linalg.tests.test_linalg import ( diff --git a/numpy/matrixlib/tests/test_multiarray.py b/numpy/matrixlib/tests/test_multiarray.py index 6d84bd477..638d0d153 100644 --- a/numpy/matrixlib/tests/test_multiarray.py +++ b/numpy/matrixlib/tests/test_multiarray.py @@ -1,9 +1,7 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_, assert_equal, assert_array_equal -class TestView(object): +class TestView: def test_type(self): x = np.array([1, 2, 3]) assert_(isinstance(x.view(np.matrix), np.matrix)) diff --git a/numpy/matrixlib/tests/test_numeric.py b/numpy/matrixlib/tests/test_numeric.py index 95e1c8001..a772bb388 100644 --- a/numpy/matrixlib/tests/test_numeric.py +++ b/numpy/matrixlib/tests/test_numeric.py @@ -1,9 +1,7 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_equal -class TestDot(object): +class TestDot: def test_matscalar(self): b1 = np.matrix(np.ones((3, 3), dtype=complex)) assert_equal(b1*1.0, b1) diff --git a/numpy/matrixlib/tests/test_regression.py b/numpy/matrixlib/tests/test_regression.py index 70e147279..a54d44020 100644 --- a/numpy/matrixlib/tests/test_regression.py +++ b/numpy/matrixlib/tests/test_regression.py @@ -1,10 +1,8 @@ -from __future__ import division, absolute_import, print_function - import numpy as np from numpy.testing import assert_, assert_equal, assert_raises -class TestRegression(object): +class TestRegression: def test_kron_matrix(self): # Ticket #71 x = np.matrix('[1 0; 1 0]') diff --git a/numpy/polynomial/__init__.py b/numpy/polynomial/__init__.py index 85cee9ce6..4ff2df57e 100644 --- a/numpy/polynomial/__init__.py +++ b/numpy/polynomial/__init__.py @@ -13,8 +13,6 @@ implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ -from __future__ import division, absolute_import, print_function - from .polynomial import Polynomial from .chebyshev import Chebyshev from .legendre import Legendre diff --git a/numpy/polynomial/_polybase.py b/numpy/polynomial/_polybase.py index bfa030714..28bd50ec6 100644 --- a/numpy/polynomial/_polybase.py +++ b/numpy/polynomial/_polybase.py @@ -6,8 +6,6 @@ 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. """ -from __future__ import division, absolute_import, print_function - import abc import numbers diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index 0cd9c4d23..0bb297807 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -87,8 +87,6 @@ References (preprint: https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) """ -from __future__ import division, absolute_import, print_function - import warnings import numpy as np import numpy.linalg as la diff --git a/numpy/polynomial/hermite.py b/numpy/polynomial/hermite.py index 9b1aea239..cb98b7e1f 100644 --- a/numpy/polynomial/hermite.py +++ b/numpy/polynomial/hermite.py @@ -58,8 +58,6 @@ See also `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - import warnings import numpy as np import numpy.linalg as la diff --git a/numpy/polynomial/hermite_e.py b/numpy/polynomial/hermite_e.py index c5a0a05a2..1f4a93c24 100644 --- a/numpy/polynomial/hermite_e.py +++ b/numpy/polynomial/hermite_e.py @@ -58,8 +58,6 @@ See also `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - import warnings import numpy as np import numpy.linalg as la diff --git a/numpy/polynomial/laguerre.py b/numpy/polynomial/laguerre.py index 538a1d449..bf8e11623 100644 --- a/numpy/polynomial/laguerre.py +++ b/numpy/polynomial/laguerre.py @@ -58,8 +58,6 @@ See also `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - import warnings import numpy as np import numpy.linalg as la diff --git a/numpy/polynomial/legendre.py b/numpy/polynomial/legendre.py index c11824761..d74b87d5a 100644 --- a/numpy/polynomial/legendre.py +++ b/numpy/polynomial/legendre.py @@ -81,8 +81,6 @@ numpy.polynomial.hermite numpy.polynomial.hermite_e """ -from __future__ import division, absolute_import, print_function - import warnings import numpy as np import numpy.linalg as la diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 315ea1495..92fdc06fa 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -55,8 +55,6 @@ See Also `numpy.polynomial` """ -from __future__ import division, absolute_import, print_function - __all__ = [ 'polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval', diff --git a/numpy/polynomial/polyutils.py b/numpy/polynomial/polyutils.py index 5dcfa7a7a..b65e88a83 100644 --- a/numpy/polynomial/polyutils.py +++ b/numpy/polynomial/polyutils.py @@ -43,8 +43,6 @@ Functions mapparms parameters of the linear map between domains. """ -from __future__ import division, absolute_import, print_function - import operator import functools import warnings @@ -80,7 +78,7 @@ class PolyDomainError(PolyError): # Base class for all polynomial types # -class PolyBase(object): +class PolyBase: """ Base class for all polynomial types. diff --git a/numpy/polynomial/setup.py b/numpy/polynomial/setup.py index cb59ee1e5..8fc82cba1 100644 --- a/numpy/polynomial/setup.py +++ b/numpy/polynomial/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('polynomial', parent_package, top_path) diff --git a/numpy/polynomial/tests/test_chebyshev.py b/numpy/polynomial/tests/test_chebyshev.py index c8d2d6dba..ec0a7839a 100644 --- a/numpy/polynomial/tests/test_chebyshev.py +++ b/numpy/polynomial/tests/test_chebyshev.py @@ -1,8 +1,6 @@ """Tests for chebyshev module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256] Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9] -class TestPrivate(object): +class TestPrivate: def test__cseries_to_zseries(self): for i in range(5): @@ -47,7 +45,7 @@ class TestPrivate(object): assert_equal(res, tgt) -class TestConstants(object): +class TestConstants: def test_chebdomain(self): assert_equal(cheb.chebdomain, [-1, 1]) @@ -62,7 +60,7 @@ class TestConstants(object): assert_equal(cheb.chebx, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: def test_chebadd(self): for i in range(5): @@ -123,7 +121,7 @@ class TestArithmetic(object): assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2.5, 2., 1.5]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -217,7 +215,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_chebint(self): # check exceptions @@ -319,7 +317,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_chebder(self): # check exceptions @@ -359,7 +357,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -407,7 +405,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_chebfit(self): def f(x): @@ -484,7 +482,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestInterpolate(object): +class TestInterpolate: def f(self, x): return x * (x - 1) * (x - 2) @@ -509,7 +507,7 @@ class TestInterpolate(object): assert_almost_equal(cheb.chebval(x, c), powx(x, p), decimal=12) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, cheb.chebcompanion, []) @@ -524,7 +522,7 @@ class TestCompanion(object): assert_(cheb.chebcompanion([1, 2])[0, 0] == -.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = cheb.chebgauss(100) @@ -543,7 +541,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_chebfromroots(self): res = cheb.chebfromroots([]) diff --git a/numpy/polynomial/tests/test_classes.py b/numpy/polynomial/tests/test_classes.py index 2261f960b..68656bc98 100644 --- a/numpy/polynomial/tests/test_classes.py +++ b/numpy/polynomial/tests/test_classes.py @@ -3,8 +3,6 @@ This tests the convert and cast methods of all the polynomial classes. """ -from __future__ import division, absolute_import, print_function - import operator as op from numbers import Number @@ -574,7 +572,7 @@ def test_ufunc_override(Poly): -class TestLatexRepr(object): +class TestLatexRepr: """Test the latex repr used by ipython """ def as_latex(self, obj): @@ -628,7 +626,7 @@ class TestLatexRepr(object): # -class TestInterpolate(object): +class TestInterpolate: def f(self, x): return x * (x - 1) * (x - 2) diff --git a/numpy/polynomial/tests/test_hermite.py b/numpy/polynomial/tests/test_hermite.py index 271c1964b..4b67c1b18 100644 --- a/numpy/polynomial/tests/test_hermite.py +++ b/numpy/polynomial/tests/test_hermite.py @@ -1,8 +1,6 @@ """Tests for hermite module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ def trim(x): return herm.hermtrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_hermdomain(self): assert_equal(herm.hermdomain, [-1, 1]) @@ -45,7 +43,7 @@ class TestConstants(object): assert_equal(herm.hermx, [0, .5]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-3, 3, 100) def test_hermadd(self): @@ -111,7 +109,7 @@ class TestArithmetic(object): assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2.5, 1., .75]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -205,7 +203,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_hermint(self): # check exceptions @@ -307,7 +305,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_hermder(self): # check exceptions @@ -347,7 +345,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -395,7 +393,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_hermfit(self): def f(x): @@ -472,7 +470,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, herm.hermcompanion, []) @@ -487,7 +485,7 @@ class TestCompanion(object): assert_(herm.hermcompanion([1, 2])[0, 0] == -.25) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = herm.hermgauss(100) @@ -506,7 +504,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_hermfromroots(self): res = herm.hermfromroots([]) diff --git a/numpy/polynomial/tests/test_hermite_e.py b/numpy/polynomial/tests/test_hermite_e.py index 434b30e7b..3052500cc 100644 --- a/numpy/polynomial/tests/test_hermite_e.py +++ b/numpy/polynomial/tests/test_hermite_e.py @@ -1,8 +1,6 @@ """Tests for hermite_e module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ def trim(x): return herme.hermetrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_hermedomain(self): assert_equal(herme.hermedomain, [-1, 1]) @@ -45,7 +43,7 @@ class TestConstants(object): assert_equal(herme.hermex, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-3, 3, 100) def test_hermeadd(self): @@ -111,7 +109,7 @@ class TestArithmetic(object): assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([4., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -205,7 +203,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_hermeint(self): # check exceptions @@ -307,7 +305,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_hermeder(self): # check exceptions @@ -348,7 +346,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -396,7 +394,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_hermefit(self): def f(x): @@ -473,7 +471,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, herme.hermecompanion, []) @@ -488,7 +486,7 @@ class TestCompanion(object): assert_(herme.hermecompanion([1, 2])[0, 0] == -.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = herme.hermegauss(100) @@ -507,7 +505,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_hermefromroots(self): res = herme.hermefromroots([]) diff --git a/numpy/polynomial/tests/test_laguerre.py b/numpy/polynomial/tests/test_laguerre.py index 4b9b28637..ec103c258 100644 --- a/numpy/polynomial/tests/test_laguerre.py +++ b/numpy/polynomial/tests/test_laguerre.py @@ -1,8 +1,6 @@ """Tests for laguerre module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -27,7 +25,7 @@ def trim(x): return lag.lagtrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_lagdomain(self): assert_equal(lag.lagdomain, [0, 1]) @@ -42,7 +40,7 @@ class TestConstants(object): assert_equal(lag.lagx, [1, -1]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-3, 3, 100) def test_lagadd(self): @@ -108,7 +106,7 @@ class TestArithmetic(object): assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([9., -14., 6.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -202,7 +200,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_lagint(self): # check exceptions @@ -304,7 +302,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_lagder(self): # check exceptions @@ -344,7 +342,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -392,7 +390,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_lagfit(self): def f(x): @@ -454,7 +452,7 @@ class TestFitting(object): assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1]) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, lag.lagcompanion, []) @@ -469,7 +467,7 @@ class TestCompanion(object): assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = lag.laggauss(100) @@ -488,7 +486,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_lagfromroots(self): res = lag.lagfromroots([]) diff --git a/numpy/polynomial/tests/test_legendre.py b/numpy/polynomial/tests/test_legendre.py index 917a7e03a..8846ca6f2 100644 --- a/numpy/polynomial/tests/test_legendre.py +++ b/numpy/polynomial/tests/test_legendre.py @@ -1,8 +1,6 @@ """Tests for legendre module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -30,7 +28,7 @@ def trim(x): return leg.legtrim(x, tol=1e-6) -class TestConstants(object): +class TestConstants: def test_legdomain(self): assert_equal(leg.legdomain, [-1, 1]) @@ -45,7 +43,7 @@ class TestConstants(object): assert_equal(leg.legx, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: x = np.linspace(-1, 1, 100) def test_legadd(self): @@ -112,7 +110,7 @@ class TestArithmetic(object): assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2., 2., 2.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -206,7 +204,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_legint(self): # check exceptions @@ -308,7 +306,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_legder(self): # check exceptions @@ -348,7 +346,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -396,7 +394,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestFitting(object): +class TestFitting: def test_legfit(self): def f(x): @@ -473,7 +471,7 @@ class TestFitting(object): assert_almost_equal(coef1, coef2) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, leg.legcompanion, []) @@ -488,7 +486,7 @@ class TestCompanion(object): assert_(leg.legcompanion([1, 2])[0, 0] == -.5) -class TestGauss(object): +class TestGauss: def test_100(self): x, w = leg.leggauss(100) @@ -507,7 +505,7 @@ class TestGauss(object): assert_almost_equal(w.sum(), tgt) -class TestMisc(object): +class TestMisc: def test_legfromroots(self): res = leg.legfromroots([]) diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py index 1436963c6..c90075dfe 100644 --- a/numpy/polynomial/tests/test_polynomial.py +++ b/numpy/polynomial/tests/test_polynomial.py @@ -1,8 +1,6 @@ """Tests for polynomial module. """ -from __future__ import division, absolute_import, print_function - from functools import reduce import numpy as np @@ -29,7 +27,7 @@ T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256] Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9] -class TestConstants(object): +class TestConstants: def test_polydomain(self): assert_equal(poly.polydomain, [-1, 1]) @@ -44,7 +42,7 @@ class TestConstants(object): assert_equal(poly.polyx, [0, 1]) -class TestArithmetic(object): +class TestArithmetic: def test_polyadd(self): for i in range(5): @@ -114,7 +112,7 @@ class TestArithmetic(object): assert_equal(trim(res), trim(tgt), err_msg=msg) -class TestEvaluation(object): +class TestEvaluation: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([1., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) @@ -287,7 +285,7 @@ class TestEvaluation(object): assert_(res.shape == (2, 3)*3) -class TestIntegral(object): +class TestIntegral: def test_polyint(self): # check exceptions @@ -386,7 +384,7 @@ class TestIntegral(object): assert_almost_equal(res, tgt) -class TestDerivative(object): +class TestDerivative: def test_polyder(self): # check exceptions @@ -426,7 +424,7 @@ class TestDerivative(object): assert_almost_equal(res, tgt) -class TestVander(object): +class TestVander: # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 @@ -474,7 +472,7 @@ class TestVander(object): assert_(van.shape == (1, 5, 24)) -class TestCompanion(object): +class TestCompanion: def test_raises(self): assert_raises(ValueError, poly.polycompanion, []) @@ -489,7 +487,7 @@ class TestCompanion(object): assert_(poly.polycompanion([1, 2])[0, 0] == -.5) -class TestMisc(object): +class TestMisc: def test_polyfromroots(self): res = poly.polyfromroots([]) diff --git a/numpy/polynomial/tests/test_polyutils.py b/numpy/polynomial/tests/test_polyutils.py index 801c558cc..1b27f53b5 100644 --- a/numpy/polynomial/tests/test_polyutils.py +++ b/numpy/polynomial/tests/test_polyutils.py @@ -1,8 +1,6 @@ """Tests for polyutils module. """ -from __future__ import division, absolute_import, print_function - import numpy as np import numpy.polynomial.polyutils as pu from numpy.testing import ( @@ -10,7 +8,7 @@ from numpy.testing import ( ) -class TestMisc(object): +class TestMisc: def test_trimseq(self): for i in range(5): @@ -43,7 +41,7 @@ class TestMisc(object): assert_equal(pu.trimcoef(coef, 2), [0]) -class TestDomain(object): +class TestDomain: def test_getdomain(self): # test for real values diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py index 3f1236402..049d3af2f 100644 --- a/numpy/polynomial/tests/test_printing.py +++ b/numpy/polynomial/tests/test_printing.py @@ -1,10 +1,8 @@ -from __future__ import division, absolute_import, print_function - import numpy.polynomial as poly from numpy.testing import assert_equal -class TestStr(object): +class TestStr: def test_polynomial_str(self): res = str(poly.Polynomial([0, 1])) tgt = 'poly([0. 1.])' @@ -36,7 +34,7 @@ class TestStr(object): assert_equal(res, tgt) -class TestRepr(object): +class TestRepr: def test_polynomial_str(self): res = repr(poly.Polynomial([0, 1])) tgt = 'Polynomial([0., 1.], domain=[-1, 1], window=[-1, 1])' diff --git a/numpy/random/__init__.py b/numpy/random/__init__.py index 1ceb5c4dd..0b80999d8 100644 --- a/numpy/random/__init__.py +++ b/numpy/random/__init__.py @@ -122,8 +122,6 @@ set_state Set state of generator. """ -from __future__ import division, absolute_import, print_function - __all__ = [ 'beta', 'binomial', diff --git a/numpy/random/_examples/cython/setup.py b/numpy/random/_examples/cython/setup.py index 7ed0a3a18..20cedc4e3 100644 --- a/numpy/random/_examples/cython/setup.py +++ b/numpy/random/_examples/cython/setup.py @@ -9,9 +9,9 @@ import numpy as np from distutils.core import setup from Cython.Build import cythonize from setuptools.extension import Extension -from os.path import join, abspath, dirname +from os.path import join, dirname -path = abspath(dirname(__file__)) +path = dirname(__file__) defs = [('NPY_NO_DEPRECATED_API', 0)] extending = Extension("extending", diff --git a/numpy/random/setup.py b/numpy/random/setup.py index 1b093d6d3..42c00ee5e 100644 --- a/numpy/random/setup.py +++ b/numpy/random/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - import os import platform import sys diff --git a/numpy/random/tests/test_direct.py b/numpy/random/tests/test_direct.py index 9f77f0ad2..4fa69a402 100644 --- a/numpy/random/tests/test_direct.py +++ b/numpy/random/tests/test_direct.py @@ -145,7 +145,7 @@ def test_seedsequence(): assert len(dummy.spawn(10)) == 10 -class Base(object): +class Base: dtype = np.uint64 data2 = data1 = {} @@ -410,7 +410,7 @@ class TestSFC64(Base): cls.invalid_init_values = [(-1,)] -class TestDefaultRNG(object): +class TestDefaultRNG: def test_seed(self): for args in [(), (None,), (1234,), ([1234, 5678],)]: rg = default_rng(*args) diff --git a/numpy/random/tests/test_extending.py b/numpy/random/tests/test_extending.py index 0cad76ed1..23a874fb1 100644 --- a/numpy/random/tests/test_extending.py +++ b/numpy/random/tests/test_extending.py @@ -40,10 +40,8 @@ else: @pytest.mark.skipif(cython is None, reason="requires cython") @pytest.mark.slow -@pytest.mark.skipif(sys.platform == 'win32', reason="cmd too long on CI") def test_cython(tmp_path): examples = os.path.join(os.path.dirname(__file__), '..', '_examples') - base = os.path.dirname(examples) shutil.copytree(examples, tmp_path / '_examples') subprocess.check_call([sys.executable, 'setup.py', 'build'], cwd=str(tmp_path / '_examples' / 'cython')) diff --git a/numpy/random/tests/test_generator_mt19937.py b/numpy/random/tests/test_generator_mt19937.py index 5b3d5f08a..6f4407373 100644 --- a/numpy/random/tests/test_generator_mt19937.py +++ b/numpy/random/tests/test_generator_mt19937.py @@ -19,7 +19,7 @@ def endpoint(request): return request.param -class TestSeed(object): +class TestSeed: def test_scalar(self): s = Generator(MT19937(0)) assert_equal(s.integers(1000), 479) @@ -55,7 +55,7 @@ class TestSeed(object): assert_raises(ValueError, Generator, MT19937) -class TestBinomial(object): +class TestBinomial: def test_n_zero(self): # Tests the corner case of n == 0 for the binomial distribution. # binomial(0, p) should be zero for any p in [0, 1]. @@ -70,7 +70,7 @@ class TestBinomial(object): assert_raises(ValueError, random.binomial, 1, np.nan) -class TestMultinomial(object): +class TestMultinomial: def test_basic(self): random.multinomial(100, [0.2, 0.8]) @@ -116,7 +116,7 @@ class TestMultinomial(object): assert_array_equal(non_contig, contig) -class TestMultivariateHypergeometric(object): +class TestMultivariateHypergeometric: def setup(self): self.seed = 8675309 @@ -250,7 +250,7 @@ class TestMultivariateHypergeometric(object): assert_array_equal(sample, expected) -class TestSetState(object): +class TestSetState: def setup(self): self.seed = 1234567890 self.rg = Generator(MT19937(self.seed)) @@ -284,7 +284,7 @@ class TestSetState(object): self.rg.negative_binomial(0.5, 0.5) -class TestIntegers(object): +class TestIntegers: rfunc = random.integers # valid integer/boolean types @@ -637,7 +637,7 @@ class TestIntegers(object): assert chi2 < chi2max -class TestRandomDist(object): +class TestRandomDist: # Make sure the random distribution returns the correct value for a # given seed @@ -1565,7 +1565,7 @@ class TestRandomDist(object): assert_array_equal(actual, desired) -class TestBroadcast(object): +class TestBroadcast: # tests that functions that broadcast behave # correctly when presented with non-scalar arguments def setup(self): @@ -2117,7 +2117,7 @@ class TestBroadcast(object): assert_array_equal(actual, desired) -class TestThread(object): +class TestThread: # make sure each state produces the same sequence even in threads def setup(self): self.seeds = range(4) @@ -2164,7 +2164,7 @@ class TestThread(object): # See Issue #4263 -class TestSingleEltArrayInput(object): +class TestSingleEltArrayInput: def setup(self): self.argOne = np.array([2]) self.argTwo = np.array([3]) diff --git a/numpy/random/tests/test_generator_mt19937_regressions.py b/numpy/random/tests/test_generator_mt19937_regressions.py index 7ca8b9f3c..fb0aac335 100644 --- a/numpy/random/tests/test_generator_mt19937_regressions.py +++ b/numpy/random/tests/test_generator_mt19937_regressions.py @@ -7,7 +7,7 @@ from numpy.random import Generator, MT19937 mt19937 = Generator(MT19937()) -class TestRegression(object): +class TestRegression: def test_VonMises_range(self): # Make sure generated random variables are in [-pi, pi]. @@ -136,7 +136,7 @@ class TestRegression(object): assert_array_equal(perm, np.array([2, 0, 1])) assert_array_equal(orig, np.arange(3).view(N)) - class M(object): + class M: a = np.arange(5) def __array__(self): diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py index 2e2ecedf8..a9aa15083 100644 --- a/numpy/random/tests/test_random.py +++ b/numpy/random/tests/test_random.py @@ -1,4 +1,3 @@ -from __future__ import division, absolute_import, print_function import warnings import numpy as np @@ -11,7 +10,7 @@ from numpy import random import sys -class TestSeed(object): +class TestSeed: def test_scalar(self): s = np.random.RandomState(0) assert_equal(s.randint(1000), 684) @@ -50,7 +49,7 @@ class TestSeed(object): [4, 5, 6]]) -class TestBinomial(object): +class TestBinomial: def test_n_zero(self): # Tests the corner case of n == 0 for the binomial distribution. # binomial(0, p) should be zero for any p in [0, 1]. @@ -65,7 +64,7 @@ class TestBinomial(object): assert_raises(ValueError, random.binomial, 1, np.nan) -class TestMultinomial(object): +class TestMultinomial: def test_basic(self): random.multinomial(100, [0.2, 0.8]) @@ -93,7 +92,7 @@ class TestMultinomial(object): float(1)) -class TestSetState(object): +class TestSetState: def setup(self): self.seed = 1234567890 self.prng = random.RandomState(self.seed) @@ -141,7 +140,7 @@ class TestSetState(object): self.prng.negative_binomial(0.5, 0.5) -class TestRandint(object): +class TestRandint: rfunc = np.random.randint @@ -279,7 +278,7 @@ class TestRandint(object): assert_equal(type(sample), dt) -class TestRandomDist(object): +class TestRandomDist: # Make sure the random distribution returns the correct value for a # given seed @@ -974,7 +973,7 @@ class TestRandomDist(object): assert_array_equal(actual, desired) -class TestBroadcast(object): +class TestBroadcast: # tests that functions that broadcast behave # correctly when presented with non-scalar arguments def setup(self): @@ -1544,7 +1543,7 @@ class TestBroadcast(object): assert_raises(ValueError, logseries, bad_p_two * 3) -class TestThread(object): +class TestThread: # make sure each state produces the same sequence even in threads def setup(self): self.seeds = range(4) @@ -1588,7 +1587,7 @@ class TestThread(object): # See Issue #4263 -class TestSingleEltArrayInput(object): +class TestSingleEltArrayInput: def setup(self): self.argOne = np.array([2]) self.argTwo = np.array([3]) diff --git a/numpy/random/tests/test_randomstate.py b/numpy/random/tests/test_randomstate.py index c12b685ad..ebe8558ba 100644 --- a/numpy/random/tests/test_randomstate.py +++ b/numpy/random/tests/test_randomstate.py @@ -61,7 +61,7 @@ def assert_mt19937_state_equal(a, b): assert_equal(a['gauss'], b['gauss']) -class TestSeed(object): +class TestSeed: def test_scalar(self): s = random.RandomState(0) assert_equal(s.randint(1000), 684) @@ -108,7 +108,7 @@ class TestSeed(object): assert_raises(ValueError, random.RandomState, MT19937) -class TestBinomial(object): +class TestBinomial: def test_n_zero(self): # Tests the corner case of n == 0 for the binomial distribution. # binomial(0, p) should be zero for any p in [0, 1]. @@ -123,7 +123,7 @@ class TestBinomial(object): assert_raises(ValueError, random.binomial, 1, np.nan) -class TestMultinomial(object): +class TestMultinomial: def test_basic(self): random.multinomial(100, [0.2, 0.8]) @@ -168,7 +168,7 @@ class TestMultinomial(object): assert_array_equal(non_contig, contig) -class TestSetState(object): +class TestSetState: def setup(self): self.seed = 1234567890 self.random_state = random.RandomState(self.seed) @@ -255,7 +255,7 @@ class TestSetState(object): assert repr(self.random_state).startswith('RandomState(MT19937)') -class TestRandint(object): +class TestRandint: rfunc = random.randint @@ -392,7 +392,7 @@ class TestRandint(object): assert_equal(type(sample), dt) -class TestRandomDist(object): +class TestRandomDist: # Make sure the random distribution returns the correct value for a # given seed @@ -1245,7 +1245,7 @@ class TestRandomDist(object): assert_array_equal(actual, desired) -class TestBroadcast(object): +class TestBroadcast: # tests that functions that broadcast behave # correctly when presented with non-scalar arguments def setup(self): @@ -1832,7 +1832,7 @@ class TestBroadcast(object): assert_raises(ValueError, logseries, bad_p_two * 3) -class TestThread(object): +class TestThread: # make sure each state produces the same sequence even in threads def setup(self): self.seeds = range(4) @@ -1879,7 +1879,7 @@ class TestThread(object): # See Issue #4263 -class TestSingleEltArrayInput(object): +class TestSingleEltArrayInput: def setup(self): self.argOne = np.array([2]) self.argTwo = np.array([3]) diff --git a/numpy/random/tests/test_randomstate_regression.py b/numpy/random/tests/test_randomstate_regression.py index bdc2214b6..3be9edf02 100644 --- a/numpy/random/tests/test_randomstate_regression.py +++ b/numpy/random/tests/test_randomstate_regression.py @@ -11,7 +11,7 @@ import numpy as np from numpy import random -class TestRegression(object): +class TestRegression: def test_VonMises_range(self): # Make sure generated random variables are in [-pi, pi]. @@ -147,7 +147,7 @@ class TestRegression(object): assert_array_equal(perm, np.array([0, 2, 1])) assert_array_equal(orig, np.arange(3).view(N)) - class M(object): + class M: a = np.arange(5) def __array__(self): diff --git a/numpy/random/tests/test_regression.py b/numpy/random/tests/test_regression.py index 509e2d57f..7d77a31d8 100644 --- a/numpy/random/tests/test_regression.py +++ b/numpy/random/tests/test_regression.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys from numpy.testing import ( assert_, assert_array_equal, assert_raises, @@ -9,7 +7,7 @@ from numpy.compat import long import numpy as np -class TestRegression(object): +class TestRegression: def test_VonMises_range(self): # Make sure generated random variables are in [-pi, pi]. @@ -145,7 +143,7 @@ class TestRegression(object): assert_array_equal(perm, np.array([0, 2, 1])) assert_array_equal(orig, np.arange(3).view(N)) - class M(object): + class M: a = np.arange(5) def __array__(self): diff --git a/numpy/random/tests/test_smoke.py b/numpy/random/tests/test_smoke.py index cdaac5ebb..ebfc6825e 100644 --- a/numpy/random/tests/test_smoke.py +++ b/numpy/random/tests/test_smoke.py @@ -91,7 +91,7 @@ def warmup(rg, n=None): rg.random(n, dtype=np.float32) -class RNG(object): +class RNG: @classmethod def setup_class(cls): # Overridden in test classes. Place holder to silence IDE noise diff --git a/numpy/setup.py b/numpy/setup.py index 4ccdaeea5..742de2cae 100644 --- a/numpy/setup.py +++ b/numpy/setup.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/testing/__init__.py b/numpy/testing/__init__.py index a8bd4fc15..e1f87621f 100644 --- a/numpy/testing/__init__.py +++ b/numpy/testing/__init__.py @@ -5,8 +5,6 @@ in a single location, so that test scripts can just import it and work right away. """ -from __future__ import division, absolute_import, print_function - from unittest import TestCase from ._private.utils import * diff --git a/numpy/testing/_private/decorators.py b/numpy/testing/_private/decorators.py index 24c4e385d..2012b80d3 100644 --- a/numpy/testing/_private/decorators.py +++ b/numpy/testing/_private/decorators.py @@ -13,8 +13,6 @@ function name, setup and teardown functions and so on - see ``nose.tools`` for more information. """ -from __future__ import division, absolute_import, print_function - try: # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 diff --git a/numpy/testing/_private/noseclasses.py b/numpy/testing/_private/noseclasses.py index e99bbc97d..493bacfdd 100644 --- a/numpy/testing/_private/noseclasses.py +++ b/numpy/testing/_private/noseclasses.py @@ -4,8 +4,6 @@ # Because this module imports nose directly, it should not # be used except by nosetester.py to avoid a general NumPy # dependency on nose. -from __future__ import division, absolute_import, print_function - import os import sys import doctest @@ -268,7 +266,7 @@ class NumpyDoctest(npd.Doctest): return npd.Doctest.wantFile(self, file) -class Unplugger(object): +class Unplugger: """ Nose plugin to remove named plugin late in loading By default it removes the "doctest" plugin. diff --git a/numpy/testing/_private/nosetester.py b/numpy/testing/_private/nosetester.py index 19569a509..73f5b3d35 100644 --- a/numpy/testing/_private/nosetester.py +++ b/numpy/testing/_private/nosetester.py @@ -4,8 +4,6 @@ Nose test running. This module implements ``test()`` and ``bench()`` functions for NumPy modules. """ -from __future__ import division, absolute_import, print_function - import os import sys import warnings @@ -112,7 +110,7 @@ def run_module_suite(file_to_run=None, argv=None): nose.run(argv=argv, addplugins=[KnownFailurePlugin()]) -class NoseTester(object): +class NoseTester: """ Nose test runner. @@ -456,9 +454,6 @@ class NoseTester(object): # This is very specific, so using the fragile module filter # is fine import threading - sup.filter(DeprecationWarning, - r"sys\.exc_clear\(\) not supported in 3\.x", - module=threading) sup.filter(DeprecationWarning, message=r"in 3\.x, __setslice__") sup.filter(DeprecationWarning, message=r"in 3\.x, __getslice__") sup.filter(DeprecationWarning, message=r"buffer\(\) not supported in 3\.x") diff --git a/numpy/testing/_private/parameterized.py b/numpy/testing/_private/parameterized.py index 2134cca88..dbfb4807c 100644 --- a/numpy/testing/_private/parameterized.py +++ b/numpy/testing/_private/parameterized.py @@ -293,10 +293,10 @@ def detect_runner(): _test_runner_guess = None return _test_runner_guess -class parameterized(object): +class parameterized: """ Parameterize a test case:: - class TestInt(object): + class TestInt: @parameterized([ ("A", 10), ("F", 15), diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py index 23267a9e1..9e5a2eb2a 100644 --- a/numpy/testing/_private/utils.py +++ b/numpy/testing/_private/utils.py @@ -2,8 +2,6 @@ Utility function to facilitate testing. """ -from __future__ import division, absolute_import, print_function - import os import sys import platform @@ -21,7 +19,7 @@ import pprint from numpy.core import( intp, float32, empty, arange, array_repr, ndarray, isnat, array) -import numpy.__config__ +import numpy.linalg.lapack_lite if sys.version_info[0] >= 3: from io import StringIO @@ -54,7 +52,7 @@ verbose = 0 IS_PYPY = platform.python_implementation() == 'PyPy' HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None -HAS_LAPACK64 = hasattr(numpy.__config__, 'lapack_ilp64_opt_info') +HAS_LAPACK64 = numpy.linalg.lapack_lite._ilp64 def import_nose(): @@ -1636,8 +1634,9 @@ def assert_array_max_ulp(a, b, maxulp=1, dtype=None): import numpy as np ret = nulp_diff(a, b, dtype) if not np.all(ret <= maxulp): - raise AssertionError("Arrays are not almost equal up to %g ULP" % - maxulp) + raise AssertionError("Arrays are not almost equal up to %g " + "ULP (max difference is %g ULP)" % + (maxulp, np.max(ret))) return ret @@ -2002,7 +2001,7 @@ class clear_and_catch_warnings(warnings.catch_warnings): mod.__warningregistry__.update(self._warnreg_copies[mod]) -class suppress_warnings(object): +class suppress_warnings: """ Context manager and decorator doing much the same as ``warnings.catch_warnings``. diff --git a/numpy/testing/print_coercion_tables.py b/numpy/testing/print_coercion_tables.py index 72b22cee1..84d46b59b 100755 --- a/numpy/testing/print_coercion_tables.py +++ b/numpy/testing/print_coercion_tables.py @@ -2,12 +2,10 @@ """Prints type-coercion tables for the built-in NumPy types """ -from __future__ import division, absolute_import, print_function - import numpy as np # Generic object that can be added, but doesn't do anything else -class GenericObject(object): +class GenericObject: def __init__(self, v): self.v = v diff --git a/numpy/testing/setup.py b/numpy/testing/setup.py index 7c3f2fbdf..c061b688a 100755 --- a/numpy/testing/setup.py +++ b/numpy/testing/setup.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from __future__ import division, print_function - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/testing/tests/test_decorators.py b/numpy/testing/tests/test_decorators.py index c029bf90c..77f8b66ba 100644 --- a/numpy/testing/tests/test_decorators.py +++ b/numpy/testing/tests/test_decorators.py @@ -2,8 +2,6 @@ Test the decorators from ``testing.decorators``. """ -from __future__ import division, absolute_import, print_function - import warnings import pytest @@ -23,7 +21,7 @@ else: @pytest.mark.skipif(not HAVE_NOSE, reason="Needs nose") -class TestNoseDecorators(object): +class TestNoseDecorators: # These tests are run in a class for simplicity while still # getting a report on each, skipped or success. diff --git a/numpy/testing/tests/test_doctesting.py b/numpy/testing/tests/test_doctesting.py index b77cd93e0..92c2156d8 100644 --- a/numpy/testing/tests/test_doctesting.py +++ b/numpy/testing/tests/test_doctesting.py @@ -1,8 +1,6 @@ """ Doctests for NumPy-specific nose/doctest modifications """ -from __future__ import division, absolute_import, print_function - #FIXME: None of these tests is run, because 'check' is not a recognized # testing prefix. diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py index ad72b9199..232ca0e83 100644 --- a/numpy/testing/tests/test_utils.py +++ b/numpy/testing/tests/test_utils.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import warnings import sys import os @@ -20,7 +18,7 @@ from numpy.testing import ( from numpy.core.overrides import ARRAY_FUNCTION_ENABLED -class _GenericTest(object): +class _GenericTest: def _test_equal(self, a, b): self._assert_func(a, b) @@ -211,7 +209,7 @@ class TestArrayEqual(_GenericTest): self._test_not_equal(b, a) -class TestBuildErrorMessage(object): +class TestBuildErrorMessage: def test_build_err_msg_defaults(self): x = np.array([1.00001, 2.00002, 3.00003]) @@ -618,7 +616,7 @@ class TestAlmostEqual(_GenericTest): self._assert_func(a, a) -class TestApproxEqual(object): +class TestApproxEqual: def setup(self): self._assert_func = assert_approx_equal @@ -661,7 +659,7 @@ class TestApproxEqual(object): assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) -class TestArrayAssertLess(object): +class TestArrayAssertLess: def setup(self): self._assert_func = assert_array_less @@ -771,7 +769,7 @@ class TestArrayAssertLess(object): @pytest.mark.skip(reason="The raises decorator depends on Nose") -class TestRaises(object): +class TestRaises: def setup(self): class MyException(Exception): @@ -805,7 +803,7 @@ class TestRaises(object): raise AssertionError("should have raised an AssertionError") -class TestWarns(object): +class TestWarns: def test_warn(self): def f(): @@ -856,7 +854,7 @@ class TestWarns(object): raise AssertionError("wrong warning caught by assert_warn") -class TestAssertAllclose(object): +class TestAssertAllclose: def test_simple(self): x = 1e-3 @@ -926,7 +924,7 @@ class TestAssertAllclose(object): assert_('Max relative difference: 0.5' in msg) -class TestArrayAlmostEqualNulp(object): +class TestArrayAlmostEqualNulp: def test_float64_pass(self): # The number of units of least precision @@ -1123,7 +1121,7 @@ class TestArrayAlmostEqualNulp(object): xi, y + y*1j, nulp) -class TestULP(object): +class TestULP: def test_equal(self): x = np.random.randn(10) @@ -1179,7 +1177,7 @@ class TestULP(object): maxulp=maxulp)) -class TestStringEqual(object): +class TestStringEqual: def test_simple(self): assert_string_equal("hello", "hello") assert_string_equal("hello\nmultiline", "hello\nmultiline") @@ -1241,7 +1239,7 @@ def test_warn_len_equal_call_scenarios(): # check that no assertion is uncaught # parallel scenario -- no warning issued yet - class mod(object): + class mod: pass mod_inst = mod() @@ -1251,7 +1249,7 @@ def test_warn_len_equal_call_scenarios(): # serial test scenario -- the __warningregistry__ # attribute should be present - class mod(object): + class mod: def __init__(self): self.__warningregistry__ = {'warning1':1, 'warning2':2} @@ -1526,7 +1524,7 @@ def test_clear_and_catch_warnings_inherit(): @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") -class TestAssertNoGcCycles(object): +class TestAssertNoGcCycles: """ Test assert_no_gc_cycles """ def test_passes(self): def no_cycle(): @@ -1560,7 +1558,7 @@ class TestAssertNoGcCycles(object): error, instead of hanging forever trying to clear it. """ - class ReferenceCycleInDel(object): + class ReferenceCycleInDel: """ An object that not only contains a reference cycle, but creates new cycles whenever it's garbage-collected and its __del__ runs diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 975f6ad5d..753258c13 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -3,8 +3,6 @@ Back compatibility utils module. It will import the appropriate set of tools """ -from __future__ import division, absolute_import, print_function - import warnings # 2018-04-04, numpy 1.15.0 ImportWarning diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py index 521208c36..af3730df1 100644 --- a/numpy/tests/test_ctypeslib.py +++ b/numpy/tests/test_ctypeslib.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import pytest import weakref @@ -37,7 +35,7 @@ else: reason="ctypes not available in this python") @pytest.mark.skipif(sys.platform == 'cygwin', reason="Known to fail on cygwin") -class TestLoadLibrary(object): +class TestLoadLibrary: def test_basic(self): try: # Should succeed @@ -63,7 +61,7 @@ class TestLoadLibrary(object): print(msg) -class TestNdpointer(object): +class TestNdpointer: def test_dtype(self): dt = np.intc p = ndpointer(dtype=dt) @@ -130,7 +128,7 @@ class TestNdpointer(object): @pytest.mark.skipif(ctypes is None, reason="ctypes not available on this python installation") -class TestNdpointerCFunc(object): +class TestNdpointerCFunc: def test_arguments(self): """ Test that arguments are coerced from arrays """ c_forward_pointer.restype = ctypes.c_void_p @@ -186,7 +184,7 @@ class TestNdpointerCFunc(object): @pytest.mark.skipif(ctypes is None, reason="ctypes not available on this python installation") -class TestAsArray(object): +class TestAsArray: def test_array(self): from ctypes import c_int @@ -277,7 +275,7 @@ class TestAsArray(object): @pytest.mark.skipif(ctypes is None, reason="ctypes not available on this python installation") -class TestAsCtypesType(object): +class TestAsCtypesType: """ Test conversion from dtypes to ctypes types """ def test_scalar(self): dt = np.dtype('<u2') diff --git a/numpy/tests/test_matlib.py b/numpy/tests/test_matlib.py index 38a7e39df..e04947a2e 100644 --- a/numpy/tests/test_matlib.py +++ b/numpy/tests/test_matlib.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - # As we are testing matrices, we ignore its PendingDeprecationWarnings try: import pytest diff --git a/numpy/tests/test_numpy_version.py b/numpy/tests/test_numpy_version.py index 7fac8fd22..916ab9383 100644 --- a/numpy/tests/test_numpy_version.py +++ b/numpy/tests/test_numpy_version.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import re import numpy as np diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py index 5f5ff8be0..48dd42a9f 100644 --- a/numpy/tests/test_public_api.py +++ b/numpy/tests/test_public_api.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys import subprocess import pkgutil @@ -50,7 +48,6 @@ def test_numpy_namespace(): 'fastCopyAndTranspose': 'numpy.core._multiarray_umath._fastCopyAndTranspose', 'get_array_wrap': 'numpy.lib.shape_base.get_array_wrap', 'get_include': 'numpy.lib.utils.get_include', - 'int_asbuffer': 'numpy.core._multiarray_umath.int_asbuffer', 'mafromtxt': 'numpy.lib.npyio.mafromtxt', 'ndfromtxt': 'numpy.lib.npyio.ndfromtxt', 'recfromcsv': 'numpy.lib.npyio.recfromcsv', diff --git a/numpy/tests/test_reloading.py b/numpy/tests/test_reloading.py index e378d1463..2b5a324ba 100644 --- a/numpy/tests/test_reloading.py +++ b/numpy/tests/test_reloading.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - import sys from numpy.testing import assert_raises, assert_, assert_equal diff --git a/numpy/tests/test_scripts.py b/numpy/tests/test_scripts.py index e42dc25f9..20447bcf3 100644 --- a/numpy/tests/test_scripts.py +++ b/numpy/tests/test_scripts.py @@ -2,8 +2,6 @@ Test that we can run executable scripts that have been installed with numpy. """ -from __future__ import division, print_function, absolute_import - import sys import os import pytest diff --git a/numpy/tests/test_warnings.py b/numpy/tests/test_warnings.py index f5560a099..48896f4b7 100644 --- a/numpy/tests/test_warnings.py +++ b/numpy/tests/test_warnings.py @@ -2,8 +2,6 @@ Tests which scan for certain occurrences in the code, they may not find all of these occurrences but should catch almost all. """ -from __future__ import division, absolute_import, print_function - import sys import pytest diff --git a/pavement.py b/pavement.py index 352e375d2..494d8b79d 100644 --- a/pavement.py +++ b/pavement.py @@ -22,8 +22,6 @@ TODO - fix bdist_mpkg: we build the same source twice -> how to make sure we use the same underlying python for egg install in venv and for bdist_mpkg """ -from __future__ import division, print_function - import os import sys import shutil diff --git a/pytest.ini b/pytest.ini index 74faefd6e..045406f68 100644 --- a/pytest.ini +++ b/pytest.ini @@ -14,7 +14,6 @@ filterwarnings = # Matrix PendingDeprecationWarning. ignore:the matrix subclass is not # Ignore python2.7 -3 warnings - ignore:sys\.exc_clear\(\) not supported in 3\.x:DeprecationWarning ignore:in 3\.x, __setslice__:DeprecationWarning ignore:in 3\.x, __getslice__:DeprecationWarning ignore:buffer\(\) not supported in 3\.x:DeprecationWarning diff --git a/runtests.py b/runtests.py index a38054f86..d36e5bd39 100755 --- a/runtests.py +++ b/runtests.py @@ -29,8 +29,6 @@ Generate C code coverage listing under build/lcov/: $ python runtests.py --lcov-html """ -from __future__ import division, print_function - # # This is a generic test runner script for projects using NumPy's test # framework. Change the following values to adapt to your project: @@ -17,14 +17,13 @@ variety of databases. All NumPy wheels distributed on PyPI are BSD licensed. """ -from __future__ import division, print_function - DOCLINES = (__doc__ or '').split("\n") import os import sys import subprocess import textwrap +import sysconfig if sys.version_info[:2] < (3, 6): @@ -227,6 +226,40 @@ class sdist_checked(sdist): sdist.run(self) +def get_build_overrides(): + """ + Custom build commands to add `-std=c99` to compilation + """ + from numpy.distutils.command.build_clib import build_clib + from numpy.distutils.command.build_ext import build_ext + + def _is_using_gcc(obj): + is_gcc = False + if obj.compiler.compiler_type == 'unix': + cc = sysconfig.get_config_var("CC") + if not cc: + cc = "" + compiler_name = os.path.basename(cc) + is_gcc = "gcc" in compiler_name + return is_gcc + + class new_build_clib(build_clib): + def build_a_library(self, build_info, lib_name, libraries): + if _is_using_gcc(self): + args = build_info.get('extra_compiler_args') or [] + args.append('-std=c99') + build_info['extra_compiler_args'] = args + build_clib.build_a_library(self, build_info, lib_name, libraries) + + class new_build_ext(build_ext): + def build_extension(self, ext): + if _is_using_gcc(self): + if '-std=c99' not in ext.extra_compile_args: + ext.extra_compile_args.append('-std=c99') + build_ext.build_extension(self, ext) + return new_build_clib, new_build_ext + + def generate_cython(): cwd = os.path.abspath(os.path.dirname(__file__)) print("Cythonizing sources") @@ -389,6 +422,8 @@ def setup_package(): 'f2py%s.%s = numpy.f2py.f2py2e:main' % sys.version_info[:2], ] + cmdclass={"sdist": sdist_checked, + } metadata = dict( name = 'numpy', maintainer = "NumPy Developers", @@ -407,8 +442,7 @@ def setup_package(): classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], test_suite='nose.collector', - cmdclass={"sdist": sdist_checked, - }, + cmdclass=cmdclass, python_requires='>=3.5', zip_safe=False, entry_points={ @@ -432,6 +466,8 @@ def setup_package(): generate_cython() metadata['configuration'] = configuration + # Customize extension building + cmdclass['build_clib'], cmdclass['build_ext'] = get_build_overrides() else: # Version number is added to metadata inside configuration() if build # is run. diff --git a/tools/allocation_tracking/alloc_hook.pyx b/tools/allocation_tracking/alloc_hook.pyx index d1e656f90..eeefe1704 100644 --- a/tools/allocation_tracking/alloc_hook.pyx +++ b/tools/allocation_tracking/alloc_hook.pyx @@ -22,7 +22,7 @@ cdef void pyhook(void *old, void *new, size_t size, void *user_data): PyLong_FromVoidPtr(new), size) -class NumpyAllocHook(object): +class NumpyAllocHook: def __init__(self, callback): self.callback = callback diff --git a/tools/allocation_tracking/setup.py b/tools/allocation_tracking/setup.py index a75c95e91..4462f9f4e 100644 --- a/tools/allocation_tracking/setup.py +++ b/tools/allocation_tracking/setup.py @@ -1,5 +1,3 @@ -from __future__ import division, print_function - from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext diff --git a/tools/allocation_tracking/track_allocations.py b/tools/allocation_tracking/track_allocations.py index d25993800..94d07d50e 100644 --- a/tools/allocation_tracking/track_allocations.py +++ b/tools/allocation_tracking/track_allocations.py @@ -1,11 +1,9 @@ -from __future__ import division, absolute_import, print_function - import numpy as np import gc import inspect from alloc_hook import NumpyAllocHook -class AllocationTracker(object): +class AllocationTracker: def __init__(self, threshold=0): '''track numpy allocations of size threshold bytes or more.''' diff --git a/tools/c_coverage/c_coverage_report.py b/tools/c_coverage/c_coverage_report.py index 327f6dc05..28425054f 100755 --- a/tools/c_coverage/c_coverage_report.py +++ b/tools/c_coverage/c_coverage_report.py @@ -4,8 +4,6 @@ A script to create C code-coverage reports based on the output of valgrind's callgrind tool. """ -from __future__ import division, absolute_import, print_function - import optparse import os import re diff --git a/tools/changelog.py b/tools/changelog.py index b135b14e5..00ffdd9eb 100755 --- a/tools/changelog.py +++ b/tools/changelog.py @@ -33,8 +33,6 @@ From the bash command line with $GITHUB token:: $ ./tools/announce $GITHUB v1.13.0..v1.14.0 > 1.14.0-changelog.rst """ -from __future__ import print_function, division - import os import sys import re diff --git a/tools/commitstats.py b/tools/commitstats.py index a35d7b724..14c37d4d2 100644 --- a/tools/commitstats.py +++ b/tools/commitstats.py @@ -1,5 +1,3 @@ -from __future__ import division, absolute_import, print_function - # Run svn log -l <some number> import re diff --git a/tools/cythonize.py b/tools/cythonize.py index e5352a954..4d04906ea 100755 --- a/tools/cythonize.py +++ b/tools/cythonize.py @@ -30,8 +30,6 @@ Note: this script does not check any of the dependent C libraries; it only operates on the Cython .pyx files. """ -from __future__ import division, print_function, absolute_import - import os import re import sys diff --git a/tools/find_deprecated_escaped_characters.py b/tools/find_deprecated_escaped_characters.py index 6f90001ca..401366bca 100644 --- a/tools/find_deprecated_escaped_characters.py +++ b/tools/find_deprecated_escaped_characters.py @@ -7,8 +7,6 @@ were accepted before. For instance, '\(' was previously accepted but must now be written as '\\(' or r'\('. """ -from __future__ import division, absolute_import, print_function - import sys def main(root): diff --git a/tools/npy_tempita/__init__.py b/tools/npy_tempita/__init__.py index f75f23a21..97905a16e 100644 --- a/tools/npy_tempita/__init__.py +++ b/tools/npy_tempita/__init__.py @@ -32,8 +32,6 @@ This copy of tempita was taken from https://github.com/gjhiggins/tempita with a few changes to remove the six dependency. """ -from __future__ import absolute_import, division, print_function - import re import sys try: @@ -92,7 +90,7 @@ def get_file_template(name, from_template): get_template=from_template.get_template) -class Template(object): +class Template: default_namespace = { 'start_braces': '{{', @@ -440,7 +438,7 @@ class bunch(dict): ############################################################ -class html(object): +class html: def __init__(self, value): self.value = value @@ -522,7 +520,7 @@ def sub_html(content, **kw): return tmpl.substitute(kw) -class TemplateDef(object): +class TemplateDef: def __init__(self, template, func_name, func_signature, body, ns, pos, bound_self=None): self._template = template @@ -599,7 +597,7 @@ class TemplateDef(object): return values -class TemplateObject(object): +class TemplateObject: def __init__(self, name): self.__name = name @@ -609,7 +607,7 @@ class TemplateObject(object): return '<%s %s>' % (self.__class__.__name__, self.__name) -class TemplateObjectGetter(object): +class TemplateObjectGetter: def __init__(self, template_obj): self.__template_obj = template_obj @@ -622,7 +620,7 @@ class TemplateObjectGetter(object): self.__class__.__name__, self.__template_obj) -class _Empty(object): +class _Empty: def __call__(self, *args, **kw): return self diff --git a/tools/npy_tempita/_looper.py b/tools/npy_tempita/_looper.py index 047bf5292..23121fe9e 100644 --- a/tools/npy_tempita/_looper.py +++ b/tools/npy_tempita/_looper.py @@ -17,15 +17,13 @@ looper you can get a better sense of the context. Use like:: 3 c """ -from __future__ import absolute_import, division, print_function - import sys from .compat3 import basestring_ __all__ = ['looper'] -class looper(object): +class looper: """ Helper for looping (particularly in templates) @@ -47,7 +45,7 @@ class looper(object): self.__class__.__name__, self.seq) -class looper_iter(object): +class looper_iter: def __init__(self, seq): self.seq = list(seq) @@ -67,7 +65,7 @@ class looper_iter(object): next = __next__ -class loop_pos(object): +class loop_pos: def __init__(self, seq, pos): self.seq = seq diff --git a/tools/npy_tempita/compat3.py b/tools/npy_tempita/compat3.py index 01d771345..d9d682ff5 100644 --- a/tools/npy_tempita/compat3.py +++ b/tools/npy_tempita/compat3.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, division, print_function - import sys __all__ = ['PY3', 'b', 'basestring_', 'bytes', 'next', 'is_unicode', diff --git a/tools/openblas_support.py b/tools/openblas_support.py index 4a210cfe1..2c1b70d6f 100644 --- a/tools/openblas_support.py +++ b/tools/openblas_support.py @@ -1,4 +1,3 @@ -from __future__ import division, absolute_import, print_function import os import sys import glob diff --git a/tools/refguide_check.py b/tools/refguide_check.py index ba045cebf..3b587b77b 100644 --- a/tools/refguide_check.py +++ b/tools/refguide_check.py @@ -25,8 +25,6 @@ or in RST-based documentations:: $ python refguide_check.py --rst docs """ -from __future__ import print_function - import sys import os import re @@ -797,7 +795,7 @@ def _run_doctests(tests, full_name, verbose, doctest_warnings): def out(msg): output.append(msg) - class MyStderr(object): + class MyStderr: """ Redirect stderr to the current stdout """ diff --git a/tools/swig/numpy.i b/tools/swig/numpy.i index 36bb55c98..8416e82f3 100644 --- a/tools/swig/numpy.i +++ b/tools/swig/numpy.i @@ -120,11 +120,6 @@ if (PyDict_Check( py_obj)) return "dict" ; if (PyList_Check( py_obj)) return "list" ; if (PyTuple_Check( py_obj)) return "tuple" ; -%#if PY_MAJOR_VERSION < 3 - if (PyFile_Check( py_obj)) return "file" ; - if (PyModule_Check( py_obj)) return "module" ; - if (PyInstance_Check(py_obj)) return "instance" ; -%#endif return "unknown type"; } @@ -545,7 +540,7 @@ const npy_intp *dims = array_dimensions(ary); for (i=0; i < nd; ++i) n_non_one += (dims[i] != 1) ? 1 : 0; - if (n_non_one > 1) + if (n_non_one > 1) array_clearflags(ary,NPY_ARRAY_CARRAY); array_enableflags(ary,NPY_ARRAY_FARRAY); /* Recompute the strides */ diff --git a/tools/swig/pyfragments.swg b/tools/swig/pyfragments.swg index 97ca8cf97..ce2452f80 100644 --- a/tools/swig/pyfragments.swg +++ b/tools/swig/pyfragments.swg @@ -75,21 +75,6 @@ SWIGINTERN int SWIG_AsVal_dec(unsigned long)(PyObject *obj, unsigned long *val) { - %#if PY_VERSION_HEX < 0x03000000 - if (PyInt_Check(obj)) - { - long v = PyInt_AsLong(obj); - if (v >= 0) - { - if (val) *val = v; - return SWIG_OK; - } - else - { - return SWIG_OverflowError; - } - } else - %#endif if (PyLong_Check(obj)) { unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { diff --git a/tools/swig/test/setup.py b/tools/swig/test/setup.py index 4ff870e19..6bbfac2de 100755 --- a/tools/swig/test/setup.py +++ b/tools/swig/test/setup.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, print_function - # System imports from distutils.core import * from distutils import sysconfig diff --git a/tools/swig/test/testArray.py b/tools/swig/test/testArray.py index 8d9c79772..c8d0d0edb 100755 --- a/tools/swig/test/testArray.py +++ b/tools/swig/test/testArray.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform import os diff --git a/tools/swig/test/testFarray.py b/tools/swig/test/testFarray.py index e8bf711c5..67dace5b1 100755 --- a/tools/swig/test/testFarray.py +++ b/tools/swig/test/testFarray.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform import os diff --git a/tools/swig/test/testFlat.py b/tools/swig/test/testFlat.py index 71be277b1..470f157d8 100755 --- a/tools/swig/test/testFlat.py +++ b/tools/swig/test/testFlat.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform import os diff --git a/tools/swig/test/testFortran.py b/tools/swig/test/testFortran.py index 426e8943d..76bf1dd2a 100644 --- a/tools/swig/test/testFortran.py +++ b/tools/swig/test/testFortran.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform import os diff --git a/tools/swig/test/testMatrix.py b/tools/swig/test/testMatrix.py index 065be0d44..24c64e281 100755 --- a/tools/swig/test/testMatrix.py +++ b/tools/swig/test/testMatrix.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform import os diff --git a/tools/swig/test/testSuperTensor.py b/tools/swig/test/testSuperTensor.py index 97fe80c33..f6e15b6ac 100644 --- a/tools/swig/test/testSuperTensor.py +++ b/tools/swig/test/testSuperTensor.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, print_function - # System imports from distutils.util import get_platform from math import sqrt diff --git a/tools/swig/test/testTensor.py b/tools/swig/test/testTensor.py index ac1b7491a..f8f492937 100755 --- a/tools/swig/test/testTensor.py +++ b/tools/swig/test/testTensor.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform from math import sqrt diff --git a/tools/swig/test/testVector.py b/tools/swig/test/testVector.py index 45e763b36..e28bfcc15 100755 --- a/tools/swig/test/testVector.py +++ b/tools/swig/test/testVector.py @@ -1,6 +1,4 @@ #! /usr/bin/env python -from __future__ import division, absolute_import, print_function - # System imports from distutils.util import get_platform import os |