diff options
author | Sebastian Berg <sebastian@sipsolutions.net> | 2021-03-20 14:55:41 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-03-20 14:55:41 -0500 |
commit | 9629cd9221766b087478d3dceca8c260b76e82b7 (patch) | |
tree | 7051db3cb0203c4d8d8da286b2a88341b960467c | |
parent | 2ccc7942f072b7fdbe54f148cdcb6a7d79388a89 (diff) | |
parent | c1aa1af62f6e9fcdda92d6d0991b15051a565814 (diff) | |
download | numpy-9629cd9221766b087478d3dceca8c260b76e82b7.tar.gz |
Merge pull request #18648 from mwtoews/pep-3135
MAINT: use super() as described by PEP 3135
-rw-r--r-- | doc/source/user/basics.subclassing.rst | 16 | ||||
-rw-r--r-- | numpy/_globals.py | 2 | ||||
-rw-r--r-- | numpy/core/_exceptions.py | 2 | ||||
-rw-r--r-- | numpy/core/arrayprint.py | 4 | ||||
-rw-r--r-- | numpy/core/memmap.py | 4 | ||||
-rw-r--r-- | numpy/core/records.py | 6 | ||||
-rw-r--r-- | numpy/core/tests/test_arrayprint.py | 6 | ||||
-rw-r--r-- | numpy/core/tests/test_regression.py | 2 | ||||
-rw-r--r-- | numpy/core/tests/test_umath.py | 4 | ||||
-rw-r--r-- | numpy/f2py/tests/test_assumed_shape.py | 2 | ||||
-rw-r--r-- | numpy/lib/index_tricks.py | 4 | ||||
-rw-r--r-- | numpy/lib/tests/test_format.py | 2 | ||||
-rw-r--r-- | numpy/ma/core.py | 41 | ||||
-rw-r--r-- | numpy/ma/extras.py | 4 | ||||
-rw-r--r-- | numpy/ma/tests/test_subclassing.py | 18 | ||||
-rw-r--r-- | numpy/testing/_private/utils.py | 6 | ||||
-rw-r--r-- | numpy/testing/tests/test_utils.py | 8 |
17 files changed, 63 insertions, 68 deletions
diff --git a/doc/source/user/basics.subclassing.rst b/doc/source/user/basics.subclassing.rst index 8ffa31688..1b7880986 100644 --- a/doc/source/user/basics.subclassing.rst +++ b/doc/source/user/basics.subclassing.rst @@ -223,8 +223,8 @@ where our object creation housekeeping usually goes. new ndarray instance of its own class. In practice this means that we, the authors of the code, will need to make a call to ``ndarray.__new__(MySubClass,...)``, a class-hierarchy prepared call to - ``super(MySubClass, cls).__new__(cls, ...)``, or do view casting of an - existing array (see below) + ``super().__new__(cls, ...)``, or do view casting of an existing array + (see below) * For view casting and new-from-template, the equivalent of ``ndarray.__new__(MySubClass,...`` is called, at the C level. @@ -240,7 +240,7 @@ The following code allows us to look at the call sequences and arguments: class C(np.ndarray): def __new__(cls, *args, **kwargs): print('In __new__ with class %s' % cls) - return super(C, cls).__new__(cls, *args, **kwargs) + return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): # in practice you probably will not need or want an __init__ @@ -312,9 +312,8 @@ Simple example - adding an extra attribute to ndarray # ndarray input arguments. This will call the standard # ndarray constructor, but return an object of our type. # It also triggers a call to InfoArray.__array_finalize__ - obj = super(InfoArray, subtype).__new__(subtype, shape, dtype, - buffer, offset, strides, - order) + obj = super().__new__(subtype, shape, dtype, + buffer, offset, strides, order) # set the new 'info' attribute to the value passed obj.info = info # Finally, we must return the newly created object: @@ -486,8 +485,7 @@ following. if out_no: info['outputs'] = out_no - results = super(A, self).__array_ufunc__(ufunc, method, - *args, **kwargs) + results = super().__array_ufunc__(ufunc, method, *args, **kwargs) if results is NotImplemented: return NotImplemented @@ -600,7 +598,7 @@ some print statements: print(' self is %s' % repr(self)) print(' arr is %s' % repr(out_arr)) # then just call the parent - return super(MySubClass, self).__array_wrap__(self, out_arr, context) + return super().__array_wrap__(self, out_arr, context) We run a ufunc on an instance of our new array: diff --git a/numpy/_globals.py b/numpy/_globals.py index 4a8c266d3..0b715c870 100644 --- a/numpy/_globals.py +++ b/numpy/_globals.py @@ -77,7 +77,7 @@ class _NoValueType: def __new__(cls): # ensure that only one instance exists if not cls.__instance: - cls.__instance = super(_NoValueType, cls).__new__(cls) + cls.__instance = super().__new__(cls) return cls.__instance # needed for python 2 to preserve identity through a pickle diff --git a/numpy/core/_exceptions.py b/numpy/core/_exceptions.py index 5e17ed3b2..77aa2f6e1 100644 --- a/numpy/core/_exceptions.py +++ b/numpy/core/_exceptions.py @@ -135,7 +135,7 @@ class AxisError(ValueError, IndexError): if msg_prefix is not None: msg = "{}: {}".format(msg_prefix, msg) - super(AxisError, self).__init__(msg) + super().__init__(msg) @_display_as_base diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 5c1d6cb63..3251c51e3 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -1253,12 +1253,12 @@ class DatetimeFormat(_TimelikeFormat): self.legacy = legacy # must be called after the above are configured - super(DatetimeFormat, self).__init__(x) + super().__init__(x) def __call__(self, x): if self.legacy == '1.13': return self._format_non_nat(x) - return super(DatetimeFormat, self).__call__(x) + return super().__call__(x) def _format_non_nat(self, x): return "'%s'" % datetime_as_string(x, diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 892ad2540..b0d9cb3af 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -316,7 +316,7 @@ class memmap(ndarray): self.base.flush() def __array_wrap__(self, arr, context=None): - arr = super(memmap, self).__array_wrap__(arr, context) + arr = super().__array_wrap__(arr, context) # Return a memmap if a memmap was given as the output of the # ufunc. Leave the arr class unchanged if self is not a memmap @@ -331,7 +331,7 @@ class memmap(ndarray): return arr.view(np.ndarray) def __getitem__(self, index): - res = super(memmap, self).__getitem__(index) + res = super().__getitem__(index) if type(res) is memmap and res._mmap is None: return res.view(type=ndarray) return res diff --git a/numpy/core/records.py b/numpy/core/records.py index a626a0589..0efc951a3 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -244,12 +244,12 @@ class record(nt.void): def __repr__(self): if get_printoptions()['legacy'] == '1.13': return self.__str__() - return super(record, self).__repr__() + return super().__repr__() def __str__(self): if get_printoptions()['legacy'] == '1.13': return str(self.item()) - return super(record, self).__str__() + return super().__str__() def __getattribute__(self, attr): if attr in ('setfield', 'getfield', 'dtype'): @@ -518,7 +518,7 @@ class recarray(ndarray): return self.setfield(val, *res) def __getitem__(self, indx): - obj = super(recarray, self).__getitem__(indx) + obj = super().__getitem__(indx) # copy behavior of getattr, except that here # we might also be returning a single element diff --git a/numpy/core/tests/test_arrayprint.py b/numpy/core/tests/test_arrayprint.py index 2c5f1577d..8f63b5b70 100644 --- a/numpy/core/tests/test_arrayprint.py +++ b/numpy/core/tests/test_arrayprint.py @@ -45,7 +45,7 @@ class TestArrayRepr: return obj def __getitem__(self, ind): - ret = super(sub, self).__getitem__(ind) + ret = super().__getitem__(ind) return sub(ret) # test that object + subclass is OK: @@ -67,7 +67,7 @@ class TestArrayRepr: return obj def __getitem__(self, ind): - ret = super(sub, self).__getitem__(ind) + ret = super().__getitem__(ind) return sub(ret) x = sub(1) @@ -101,7 +101,7 @@ class TestArrayRepr: # gh-10663 class DuckCounter(np.ndarray): def __getitem__(self, item): - result = super(DuckCounter, self).__getitem__(item) + result = super().__getitem__(item) if not isinstance(result, DuckCounter): result = result[...].view(DuckCounter) return result diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 099293307..66b5d5516 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -1750,7 +1750,7 @@ class TestRegression: # it is designed to simulate an old API # expectation to guard against regression def squeeze(self): - return super(OldSqueeze, self).squeeze() + return super().squeeze() oldsqueeze = OldSqueeze(np.array([[1],[2],[3]])) diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 2249c866c..556856faf 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -2703,8 +2703,8 @@ class TestSpecialMethods: if out_no: info['outputs'] = out_no - results = super(A, self).__array_ufunc__(ufunc, method, - *args, **kwargs) + results = super().__array_ufunc__(ufunc, method, + *args, **kwargs) if results is NotImplemented: return NotImplemented diff --git a/numpy/f2py/tests/test_assumed_shape.py b/numpy/f2py/tests/test_assumed_shape.py index dfc252660..79e3ad138 100644 --- a/numpy/f2py/tests/test_assumed_shape.py +++ b/numpy/f2py/tests/test_assumed_shape.py @@ -47,7 +47,7 @@ class TestF2cmapOption(TestAssumedShapeSumExample): self.sources.append(self.f2cmap_file.name) self.options = ["--f2cmap", self.f2cmap_file.name] - super(TestF2cmapOption, self).setup() + super().setup() def teardown(self): os.unlink(self.f2cmap_file.name) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index fa7c51832..72d8e9de4 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -251,7 +251,7 @@ class MGridClass(nd_grid): """ def __init__(self): - super(MGridClass, self).__init__(sparse=False) + super().__init__(sparse=False) mgrid = MGridClass() @@ -298,7 +298,7 @@ class OGridClass(nd_grid): """ def __init__(self): - super(OGridClass, self).__init__(sparse=True) + super().__init__(sparse=True) ogrid = OGridClass() diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index bac42fad3..10656a233 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -402,7 +402,7 @@ class BytesIOSRandomSize(BytesIO): def read(self, size=None): import random size = random.randint(1, size) - return super(BytesIOSRandomSize, self).read(size) + return super().read(size) def roundtrip(arr): diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 10ee0fb06..cebacf5e1 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -914,7 +914,7 @@ class _MaskedUnaryOperation(_MaskedUFunc): """ def __init__(self, mufunc, fill=0, domain=None): - super(_MaskedUnaryOperation, self).__init__(mufunc) + super().__init__(mufunc) self.fill = fill self.domain = domain ufunc_domain[mufunc] = domain @@ -996,7 +996,7 @@ class _MaskedBinaryOperation(_MaskedUFunc): abfunc(x, filly) = x for all x to enable reduce. """ - super(_MaskedBinaryOperation, self).__init__(mbfunc) + super().__init__(mbfunc) self.fillx = fillx self.filly = filly ufunc_domain[mbfunc] = None @@ -1142,7 +1142,7 @@ class _DomainedBinaryOperation(_MaskedUFunc): """abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce. """ - super(_DomainedBinaryOperation, self).__init__(dbfunc) + super().__init__(dbfunc) self.domain = domain self.fillx = fillx self.filly = filly @@ -3400,7 +3400,7 @@ class MaskedArray(ndarray): # Define so that we can overwrite the setter. @property def dtype(self): - return super(MaskedArray, self).dtype + return super().dtype @dtype.setter def dtype(self, dtype): @@ -3416,7 +3416,7 @@ class MaskedArray(ndarray): @property def shape(self): - return super(MaskedArray, self).shape + return super().shape @shape.setter def shape(self, shape): @@ -4985,8 +4985,8 @@ class MaskedArray(ndarray): #!!!: implement out + test! m = self._mask if m is nomask: - result = super(MaskedArray, self).trace(offset=offset, axis1=axis1, - axis2=axis2, out=out) + result = super().trace(offset=offset, axis1=axis1, axis2=axis2, + out=out) return result.astype(dtype) else: D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) @@ -5237,8 +5237,7 @@ class MaskedArray(ndarray): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if self._mask is nomask: - result = super(MaskedArray, self).mean(axis=axis, - dtype=dtype, **kwargs)[()] + result = super().mean(axis=axis, dtype=dtype, **kwargs)[()] else: dsum = self.sum(axis=axis, dtype=dtype, **kwargs) cnt = self.count(axis=axis, **kwargs) @@ -5315,8 +5314,8 @@ class MaskedArray(ndarray): # Easy case: nomask, business as usual if self._mask is nomask: - ret = super(MaskedArray, self).var(axis=axis, dtype=dtype, out=out, - ddof=ddof, **kwargs)[()] + ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof, + **kwargs)[()] if out is not None: if isinstance(out, MaskedArray): out.__setmask__(nomask) @@ -5947,13 +5946,13 @@ class MaskedArray(ndarray): warnings.warn("Warning: 'partition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) - return super(MaskedArray, self).partition(*args, **kwargs) + return super().partition(*args, **kwargs) def argpartition(self, *args, **kwargs): warnings.warn("Warning: 'argpartition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) - return super(MaskedArray, self).argpartition(*args, **kwargs) + return super().argpartition(*args, **kwargs) def take(self, indices, axis=None, out=None, mode='raise'): """ @@ -6179,7 +6178,7 @@ class MaskedArray(ndarray): """ cf = 'CF'[self.flags.fnc] - data_state = super(MaskedArray, self).__reduce__()[2] + data_state = super().__reduce__()[2] return data_state + (getmaskarray(self).tobytes(cf), self._fill_value) def __setstate__(self, state): @@ -6195,7 +6194,7 @@ class MaskedArray(ndarray): """ (_, shp, typ, isf, raw, msk, flv) = state - super(MaskedArray, self).__setstate__((shp, typ, isf, raw)) + super().__setstate__((shp, typ, isf, raw)) self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk)) self.fill_value = flv @@ -6256,7 +6255,7 @@ class mvoid(MaskedArray): @property def _data(self): # Make sure that the _data part is a np.void - return super(mvoid, self)._data[()] + return super()._data[()] def __getitem__(self, indx): """ @@ -6293,7 +6292,7 @@ class mvoid(MaskedArray): return str(self._data) rdtype = _replace_dtype_fields(self._data.dtype, "O") - data_arr = super(mvoid, self)._data + data_arr = super()._data res = data_arr.astype(rdtype) _recursive_printoption(res, self._mask, masked_print_option) return str(res) @@ -6455,7 +6454,7 @@ class MaskedConstant(MaskedArray): if not self.__has_singleton(): # this handles the `.view` in __new__, which we want to copy across # properties normally - return super(MaskedConstant, self).__array_finalize__(obj) + return super().__array_finalize__(obj) elif self is self.__singleton: # not clear how this can happen, play it safe pass @@ -6529,14 +6528,14 @@ class MaskedConstant(MaskedArray): def __setattr__(self, attr, value): if not self.__has_singleton(): # allow the singleton to be initialized - return super(MaskedConstant, self).__setattr__(attr, value) + return super().__setattr__(attr, value) elif self is self.__singleton: raise AttributeError( f"attributes of {self!r} are not writeable") else: # duplicate instance - we can end up here from __array_finalize__, # where we set the __class__ attribute - return super(MaskedConstant, self).__setattr__(attr, value) + return super().__setattr__(attr, value) masked = masked_singleton = MaskedConstant() @@ -6628,7 +6627,7 @@ class _extrema_operation(_MaskedUFunc): """ def __init__(self, ufunc, compare, fill_value): - super(_extrema_operation, self).__init__(ufunc) + super().__init__(ufunc) self.compare = compare self.fill_value_func = fill_value diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index a775a15bf..8c123bc3b 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -1483,7 +1483,7 @@ class MAxisConcatenator(AxisConcatenator): # deprecate that class. In preparation, we use the unmasked version # to construct the matrix (with copy=False for backwards compatibility # with the .view) - data = super(MAxisConcatenator, cls).makemat(arr.data, copy=False) + data = super().makemat(arr.data, copy=False) return array(data, mask=arr.mask) def __getitem__(self, key): @@ -1491,7 +1491,7 @@ class MAxisConcatenator(AxisConcatenator): if isinstance(key, str): raise MAError("Unavailable for masked array.") - return super(MAxisConcatenator, self).__getitem__(key) + return super().__getitem__(key) class mr_class(MAxisConcatenator): diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py index f2623406d..1af539625 100644 --- a/numpy/ma/tests/test_subclassing.py +++ b/numpy/ma/tests/test_subclassing.py @@ -28,19 +28,18 @@ class SubArray(np.ndarray): return x def __array_finalize__(self, obj): - if callable(getattr(super(SubArray, self), - '__array_finalize__', None)): - super(SubArray, self).__array_finalize__(obj) + if callable(getattr(super(), '__array_finalize__', None)): + super().__array_finalize__(obj) self.info = getattr(obj, 'info', {}).copy() return def __add__(self, other): - result = super(SubArray, self).__add__(other) + result = super().__add__(other) result.info['added'] = result.info.get('added', 0) + 1 return result def __iadd__(self, other): - result = super(SubArray, self).__iadd__(other) + result = super().__iadd__(other) result.info['iadded'] = result.info.get('iadded', 0) + 1 return result @@ -51,7 +50,7 @@ subarray = SubArray class SubMaskedArray(MaskedArray): """Pure subclass of MaskedArray, keeping some info on subclass.""" def __new__(cls, info=None, **kwargs): - obj = super(SubMaskedArray, cls).__new__(cls, **kwargs) + obj = super().__new__(cls, **kwargs) obj._optinfo['info'] = info return obj @@ -123,12 +122,11 @@ class ComplicatedSubArray(SubArray): def __setitem__(self, item, value): # validation ensures direct assignment with ndarray or # masked_print_option will fail - super(ComplicatedSubArray, self).__setitem__( - item, self._validate_input(value)) + super().__setitem__(item, self._validate_input(value)) def __getitem__(self, item): # ensure getter returns our own class also for scalars - value = super(ComplicatedSubArray, self).__getitem__(item) + value = super().__getitem__(item) if not isinstance(value, np.ndarray): # scalar value = value.__array__().view(ComplicatedSubArray) return value @@ -143,7 +141,7 @@ class ComplicatedSubArray(SubArray): y[:] = value def __array_wrap__(self, obj, context=None): - obj = super(ComplicatedSubArray, self).__array_wrap__(obj, context) + obj = super().__array_wrap__(obj, context) if context is not None and context[0] is np.multiply: obj.info['multiplied'] = obj.info.get('multiplied', 0) + 1 diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py index b4d42728e..5b87d0a06 100644 --- a/numpy/testing/_private/utils.py +++ b/numpy/testing/_private/utils.py @@ -2006,7 +2006,7 @@ class clear_and_catch_warnings(warnings.catch_warnings): def __init__(self, record=False, modules=()): self.modules = set(modules).union(self.class_modules) self._warnreg_copies = {} - super(clear_and_catch_warnings, self).__init__(record=record) + super().__init__(record=record) def __enter__(self): for mod in self.modules: @@ -2014,10 +2014,10 @@ class clear_and_catch_warnings(warnings.catch_warnings): mod_reg = mod.__warningregistry__ self._warnreg_copies[mod] = mod_reg.copy() mod_reg.clear() - return super(clear_and_catch_warnings, self).__enter__() + return super().__enter__() def __exit__(self, *exc_info): - super(clear_and_catch_warnings, self).__exit__(*exc_info) + super().__exit__(*exc_info) for mod in self.modules: if hasattr(mod, '__warningregistry__'): mod.__warningregistry__.clear() diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py index 261ed9705..31d2cdc76 100644 --- a/numpy/testing/tests/test_utils.py +++ b/numpy/testing/tests/test_utils.py @@ -434,10 +434,10 @@ class TestArrayAlmostEqual(_GenericTest): # (which, e.g., astropy Quantity cannot usefully do). See gh-8452. class MyArray(np.ndarray): def __eq__(self, other): - return super(MyArray, self).__eq__(other).view(np.ndarray) + return super().__eq__(other).view(np.ndarray) def __lt__(self, other): - return super(MyArray, self).__lt__(other).view(np.ndarray) + return super().__lt__(other).view(np.ndarray) def all(self, *args, **kwargs): raise NotImplementedError @@ -585,10 +585,10 @@ class TestAlmostEqual(_GenericTest): # (which, e.g., astropy Quantity cannot usefully do). See gh-8452. class MyArray(np.ndarray): def __eq__(self, other): - return super(MyArray, self).__eq__(other).view(np.ndarray) + return super().__eq__(other).view(np.ndarray) def __lt__(self, other): - return super(MyArray, self).__lt__(other).view(np.ndarray) + return super().__lt__(other).view(np.ndarray) def all(self, *args, **kwargs): raise NotImplementedError |