8000 API: remove np.compat usage from codebase · numpy/numpy@a82a435 · GitHub
[go: up one dir, main page]

Skip to content

Commit a82a435

Browse files
committed
API: remove np.compat usage from codebase
1 parent 63b5edc commit a82a435

36 files changed

+134
-161
lines changed

numpy/__init__.py

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -155,15 +155,6 @@
155155
from . import matrixlib as _mat
156156
from .matrixlib import *
157157

158-
# Deprecations introduced in 1.25.0, 2023-05-xx TODO update day
159-
from . import compat
160-
161-
__deprecated_attrs__["compat"] = (compat,
162-
"`np.compat`, which was used during the Python 2 to 3 transition,"
163-
" is deprecated since 1.25.0, and will be removed")
164-
165-
del compat
166-
167158
# Deprecations introduced in NumPy 1.20.0, 2020-06-06
168159
import builtins as _builtins
169160

@@ -241,20 +232,9 @@
241232
__all__.extend(['__version__', 'show_config'])
242233
__all__.extend(core.__all__)
243234
__all__.extend(_mat.__all__)
235+
__all__.extend(lib.__all__)
244236
__all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
245237

246-
_lib_expired_utils_names = ["byte_bounds", "safe_eval", "who"]
247-
lib__all__ = lib.__all__[:]
248-
for name in _lib_expired_utils_names:
249-
lib__all__.remove(name)
250-
__expired_functions__[name] = (
251-
f"{name} is deprecated and removed from the "
252-
f"main namespace. If you still want to use it "
253-
f"please use it directly from np.lib or np.lib.utils"
254-
)
255-
del byte_bounds, safe_eval, who
256-
__all__.extend(lib__all__)
257-
258238
# Remove one of the two occurrences of `issubdtype`, which is exposed as
259239
# both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
260240
__all__.remove('issubdtype')
@@ -339,6 +319,9 @@ def _expired(*args, **kwds):
339319
elif attr == 'Tester':
340320
"Removed in NumPy 1.25.0"
341321
raise RuntimeError("Tester was removed in NumPy 1.25.")
322+
elif attr == "compat":
323+
import numpy.compat as compat
324+
return compat
342325

343326
raise AttributeError("module {!r} has no attribute "
344327
"{!r}".format(__name__, attr))

numpy/__init__.pyi

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,10 @@ from numpy.lib.utils import (
626626
get_include as get_include,
627627
info as info,
628628
source as source,
629+
who as who,
629630
lookfor as lookfor,
631+
byte_bounds as byte_bounds,
632+
safe_eval as safe_eval,
630633
show_runtime as show_runtime,
631634
)
632635

numpy/_utils/_convertions.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
A set of methods retained from np.compat module that
3+
are still used across codebase.
4+
"""
5+
6+
__all__ = ["asunicode", "asbytes"]
7+
8+
9+
def asunicode(s):
10+
if isinstance(s, bytes):
11+
return s.decode('latin1')
12+
return str(s)
13+
14+
15+
def asbytes(s):
16+
if isinstance(s, bytes):
17+
return s
18+
return str(s).encode('latin1')

numpy/compat/__init__.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,23 @@
77
* compatibility
88
* we may only need a small subset of the copied library/module
99
10-
This module is deprecated since 1.25.0 and will be removed in future versions.
10+
This module is deprecated since 1.26.0 and will be removed in future versions.
1111
1212
"""
1313

1414
import warnings
1515

16-
warnings.warn(
17-
"`np.compat`, which was used during the Python 2 to 3 transition,"
18-
" is deprecated since 1.25.0, and will be removed", stacklevel=2
19-
)
20-
2116
from .._utils import _inspect
2217
from .._utils._inspect import getargspec, formatargspec
2318
from . import py3k
2419
from .py3k import *
2520

21+
warnings.warn(
22+
"`np.compat`, which was used during the Python 2 to 3 transition,"
23+
" is deprecated since 1.26.0, and will be removed",
24+
DeprecationWarning, stacklevel=2
25+
)
26+
2627
__all__ = []
2728
__all__.extend(_inspect.__all__)
2829
__all__.extend(py3k.__all__)

numpy/compat/tests/test_compat.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

numpy/core/_methods.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@
33
and the Python code for the NumPy-namespace function
44
55
"""
6+
import os
7+
import pickle
68
import warnings
79
from contextlib import nullcontext
810

911
from numpy.core import multiarray as mu
1012
from numpy.core import umath as um
1113
from numpy.core.multiarray import asanyarray
1214
from numpy.core import numerictypes as nt
13-
from numpy.core import _exceptions
1415
from numpy.core._ufunc_config import _no_nep50_warning
1516
from numpy._globals import _NoValue
16-
from numpy.compat import pickle, os_fspath
1717

1818
# save those O(100) nanoseconds!
1919
umr_maximum = um.maximum.reduce
@@ -226,7 +226,7 @@ def _dump(self, file, protocol=2):
226226
if hasattr(file, 'write'):
227227
ctx = nullcontext(file)
228228
else:
229-
ctx = open(os_fspath(file), "wb")
229+
ctx = open(os.fspath(file), "wb")
230230
with ctx as f:
231231
pickle.dump(self, f, protocol=protocol)
232232

numpy/core/_type_aliases.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
1818
"""
1919

20-
from numpy.compat import unicode
2120
from numpy.core._string_helpers import english_lower
2221
from numpy.core.multiarray import typeinfo, dtype
2322
from numpy.core._dtype import _kind_name
@@ -195,10 +194,11 @@ def _set_up_aliases():
195194

196195

197196
sctypes = {'int': [],
198-
'uint':[],
199-
'float':[],
200-
'complex':[],
201-
'others':[bool, object, bytes, unicode, void]}
197+
'uint': [],
198+
'float': [],
199+
'complex': [],
200+
'others': [bool, object, bytes, str, void]}
201+
202202

203203
def _add_array_type(typename, bits):
204204
try:

numpy/core/defchararray.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from .numeric import array as narray
2525
from numpy.core.multiarray import _vec_string
2626
from numpy.core import overrides
27-
from numpy.compat import asbytes
27+
from numpy._utils._convertions import asbytes
2828
import numpy
2929

3030
__all__ = [
@@ -86,6 +86,7 @@ def _clean_args(*args):
8686
newargs.append(chk)
8787
return newargs
8888

89+
8990
def _get_num_chars(a):
9091
"""
9192
Helper function that returns the number of characters per field in

numpy/core/memmap.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import numpy as np
44
from .._utils import set_module
55
from .numeric import uint8, ndarray, dtype
6-
from numpy.compat import os_fspath, is_pathlib_path
76

87
__all__ = ['memmap']
98

@@ -226,7 +225,10 @@ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
226225
if hasattr(filename, 'read'):
227226
f_ctx = nullcontext(filename)
228227
else:
229-
f_ctx = open(os_fspath(filename), ('r' if mode == 'c' else mode)+'b')
228+
f_ctx = open(
229+
os.fspath(filename),
230+
('r' if mode == 'c' else mode)+'b'
231+
)
230232

231233
with f_ctx as fid:
232234
fid.seek(0, 2)
@@ -273,7 +275,7 @@ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
273275
self.offset = offset
274276
self.mode = mode
275277

276-
if is_pathlib_path(filename):
278+
if isinstance(filename, os.PathLike):
277279
# special case - if we were constructed with a pathlib.path,
278280
# then filename is a path object, not a string
279281
self.filename = filename.resolve()

numpy/core/numerictypes.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,6 @@
116116
# we don't export these for import *, but we do want them accessible
117117
# as numerictypes.bool, etc.
118118
from builtins import bool, int, float, complex, object, str, bytes
119-
from numpy.compat import long, unicode
120119

121120

122121
# We use this later

numpy/core/records.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,14 @@
3333
array([2., 2.])
3434
3535
"""
36+
import os
3637
import warnings
3738
from collections import Counter
3839
from contextlib import nullcontext
3940

4041
from .._utils import set_module
4142
from . import numeric as sb
4243
from . import numerictypes as nt
43-
from numpy.compat import os_fspath
4444
from .arrayprint import _get_legacy_print_mode
4545

4646
# All of the functions allow formats to be a dtype
@@ -913,7 +913,7 @@ def fromfile(fd, dtype=None, shape=None, offset=0, formats=None,
913913
ctx = nullcontext(fd)
914914
else:
915915
# open file
916-
ctx = open(os_fspath(fd), 'rb')
916+
ctx = open(os.fspath(fd), 'rb')
917917

918918
with ctx as fd:
919919
if offset > 0:

numpy/core/setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
from numpy.distutils.msvccompiler import lib_opts_if_msvc
1313
from distutils.dep_util import newer
1414
from sysconfig import get_config_var
15-
from numpy.compat import npy_load_module
1615
from setup_common import * # noqa: F403
1716

1817
# Set to True to enable relaxed strides checking. This (mostly) means

numpy/core/src/multiarray/methods.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ NpyPath_PathlikeToFspath(PyObject *file)
1515
{
1616
static PyObject *os_PathLike = NULL;
1717
static PyObject *os_fspath = NULL;
18-
npy_cache_import("numpy.compat", "os_PathLike", &os_PathLike);
18+
npy_cache_import("os", "PathLike", &os_PathLike);
1919
if (os_PathLike == NULL) {
2020
return NULL;
2121
}
22-
npy_cache_import("numpy.compat", "os_fspath", &os_fspath);
22+
npy_cache_import("os", "fspath", &os_fspath);
2323
if (os_fspath == NULL) {
2424
return NULL;
2525
}

numpy/core/tests/test_datetime.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1+
import datetime
2+
import pickle
3+
4+
import pytest
15

26
import numpy
37
import numpy as np
4-
import datetime
5-
import pytest
68
from numpy.testing import (
79
IS_WASM,
810
assert_, assert_equal, assert_raises, assert_warns, suppress_warnings,
911
assert_raises_regex, assert_array_equal,
1012
)
11-
from numpy.compat import pickle
1213

1314
# Use pytz to test out various time zones if available
1415
try:

numpy/core/tests/test_deprecations.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -818,18 +818,18 @@ def test_deprecated_np_lib_math(self):
818818

819819

820820
class TestCompatImport(_DeprecationTestCase):
821-
# Deprecated in Numpy 1.25.0, 2023-05-xx TODO update day
821+
# Deprecated in Numpy 1.26.0, 2023-09
822822
def test_deprecated_np_compat(self):
823-
self.assert_deprecated(lambda: np.compat)
823+
# as `assert_deprecated` expects function to be idempotent
824+
# we catch import warnings ourselves
825+
with warnings.catch_warnings(record=True) as w:
826+
import numpy.compat as compat
827+
assert len(w) == 1
828+
assert w[0].category == DeprecationWarning
824829

825830

826831
class TestLibImports(_DeprecationTestCase):
827-
# Deprecated in Numpy 1.25.0, 2023-05-xx TODO update day
828-
def test_lib_functions_deprecation(self):
829-
self.assert_deprecated(lambda: np.byte_bounds)
830-
self.assert_deprecated(lambda: np.safe_eval)
831-
self.assert_deprecated(lambda: np.who)
832-
832+
# Deprecated in Numpy 1.26.0, 2023-09
833833
def test_lib_functions_deprecation_call(self):
834834
from numpy.lib import byte_bounds, safe_eval, who
835835
self.assert_deprecated(lambda: byte_bounds(np.array([1])))

numpy/core/tests/test_dtype.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import gc
66
import types
77
from typing import Any
8+
import pickle
89

910
import numpy as np
1011
import numpy.dtypes
@@ -13,7 +14,6 @@
1314
from numpy.testing import (
1415
assert_, assert_equal, assert_array_equal, assert_raises, HAS_REFCOUNT,
1516
IS_PYSTON, _OLD_PROMOTION)
16-
from numpy.compat import pickle
1717
from itertools import permutations
1818
import random
1919

@@ -33,8 +33,7 @@ def assert_dtype_not_equal(a, b):
3333
"two different types hash to the same value !")
3434

3535
class TestBuiltin:
36-
@pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object,
37-
np.compat.unicode])
36+
@pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object])
3837
def test_run(self, t):
3938
"""Only test hash runs at all."""
4039
dt = np.dtype(t)
@@ -1299,7 +1298,7 @@ def check_pickling(self, dtype):
12991298
assert_equal(x[0], y[0])
13001299

13011300
@pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object,
1302-
np.compat.unicode, bool])
1301+
bool])
13031302
def test_builtin(self, t):
13041303
self.check_pickling(np.dtype(t))
13051304

numpy/core/tests/test_multiarray.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@
1515
import weakref
1616
import pytest
1717
from contextlib import contextmanager
18-
19-
from numpy.compat import pickle
20-
18+
import pickle
2119
import pathlib
2220
import builtins
2321
from decimal import Decimal

numpy/core/tests/test_overrides.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@
44
import tempfile
55
from io import StringIO
66
from unittest import mock
7+
import pickle
8+
9+
import pytest
710

811
import numpy as np
912
from numpy.testing import (
1013
assert_, assert_equal, assert_raises, assert_raises_regex)
1114
from numpy.core.overrides import (
1215
_get_implementing_args, array_function_dispatch,
1316
verify_matching_signatures)
14-
from numpy.compat import pickle
15-
import pytest
1617

1718

1819
def _return_not_implemented(self, *args, **kwargs):

0 commit comments

Comments
 (0)
0