From b4e3a4227e3a9cfe28717db458e67d79e916a418 Mon Sep 17 00:00:00 2001 From: Charles Harris Date: Thu, 23 Jan 2020 14:44:36 -0700 Subject: [PATCH] MAINT: Replace basestring with str. This replaces basestring with str except in - tools/npy_tempita/ - numpy/compat/py3k.py --- numpy/core/einsumfunc.py | 7 +++---- numpy/core/memmap.py | 4 ++-- numpy/core/numeric.py | 3 +-- numpy/core/numerictypes.py | 2 +- numpy/distutils/misc_util.py | 3 +-- numpy/f2py/__init__.py | 2 +- numpy/lib/_iotools.py | 14 +++++++------- numpy/lib/_version.py | 6 ++---- numpy/lib/histograms.py | 3 +-- numpy/lib/npyio.py | 10 +++++----- numpy/lib/recfunctions.py | 7 +++---- numpy/ma/core.py | 10 +++++----- numpy/ma/mrecords.py | 5 ++--- numpy/testing/_private/nosetester.py | 5 ++--- numpy/tests/test_scripts.py | 1 - 15 files changed, 36 insertions(+), 46 deletions(-) diff --git a/numpy/core/einsumfunc.py b/numpy/core/einsumfunc.py index ec3eb19d2c32..342fbbbe13ad 100644 --- a/numpy/core/einsumfunc.py +++ b/numpy/core/einsumfunc.py @@ -4,7 +4,6 @@ """ import itertools -from numpy.compat import basestring from numpy.core.multiarray import c_einsum from numpy.core.numeric import asanyarray, tensordot from numpy.core.overrides import array_function_dispatch @@ -550,7 +549,7 @@ def _parse_einsum_input(operands): if len(operands) == 0: raise ValueError("No input operands") - if isinstance(operands[0], basestring): + if isinstance(operands[0], str): subscripts = operands[0].replace(" ", "") operands = [asanyarray(v) for v in operands[1:]] @@ -820,7 +819,7 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False): memory_limit = None # No optimization or a named path algorithm - if (path_type is False) or isinstance(path_type, basestring): + if (path_type is False) or isinstance(path_type, str): pass # Given an explicit path @@ -828,7 +827,7 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False): pass # Path tuple with memory limit - elif ((len(path_type) == 2) and isinstance(path_type[0], basestring) and + elif ((len(path_type) == 2) and isinstance(path_type[0], str) and isinstance(path_type[1], (int, float))): memory_limit = int(path_type[1]) path_type = path_type[0] diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index ad0d7ad79fb7..61b8ba3aca4e 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -1,7 +1,7 @@ import numpy as np from .numeric import uint8, ndarray, dtype from numpy.compat import ( - long, basestring, os_fspath, contextlib_nullcontext, is_pathlib_path + long, os_fspath, contextlib_nullcontext, is_pathlib_path ) from numpy.core.overrides import set_module @@ -271,7 +271,7 @@ def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0, # special case - if we were constructed with a pathlib.path, # then filename is a path object, not a string self.filename = filename.resolve() - elif hasattr(fid, "name") and isinstance(fid.name, basestring): + elif hasattr(fid, "name") and isinstance(fid.name, str): # py3 returns int for TemporaryFile().name self.filename = os.path.abspath(fid.name) # same as memmap copies (e.g. memmap + 1) diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index f1d7d48f1711..5e8151e68a22 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -6,7 +6,6 @@ import numbers import numpy as np -from numpy.compat import basestring from . import multiarray from .multiarray import ( _fastCopyAndTranspose as fastCopyAndTranspose, ALLOW_THREADS, @@ -625,7 +624,7 @@ def flatnonzero(a): def _mode_from_name(mode): - if isinstance(mode, basestring): + if isinstance(mode, str): return _mode_from_name_dict[mode.lower()[0]] return mode diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index c06552c4e331..bd946d7608c1 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -391,7 +391,7 @@ def issubdtype(arg1, arg2): if not isinstance(arg2_orig, dtype): # weird deprecated behaviour, that tried to infer np.floating from # float, and similar less obvious things, such as np.generic from - # basestring + # str. mro = arg2.mro() arg2 = mro[1] if len(mro) > 1 else mro[0] diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index 68fd9ea36957..b7fd74c477dc 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -32,7 +32,6 @@ def clean_up_temporary_directory(): atexit.register(clean_up_temporary_directory) -from numpy.compat import basestring from numpy.compat import npy_load_module __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', @@ -450,7 +449,7 @@ def _get_f90_modules(source): return modules def is_string(s): - return isinstance(s, basestring) + return isinstance(s, str) def all_strings(lst): """Return True if all items in lst are string objects. """ diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py index 13ffef6fc5b5..65ad4da72f16 100644 --- a/numpy/f2py/__init__.py +++ b/numpy/f2py/__init__.py @@ -87,7 +87,7 @@ def compile(source, args = ['-c', '-m', modulename, f.name] - if isinstance(extra_args, np.compat.basestring): + if isinstance(extra_args, str): is_posix = (os.name == 'posix') extra_args = shlex.split(extra_args, posix=is_posix) diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py index dd6e9ec66c29..251d2d2a7a81 100644 --- a/numpy/lib/_iotools.py +++ b/numpy/lib/_iotools.py @@ -5,7 +5,7 @@ import numpy as np import numpy.core.numeric as nx -from numpy.compat import asbytes, asunicode, bytes, basestring +from numpy.compat import asbytes, asunicode, bytes def _decode_line(line, encoding=None): @@ -175,7 +175,7 @@ def __init__(self, delimiter=None, comments='#', autostrip=True, self.comments = comments # Delimiter is a character - if (delimiter is None) or isinstance(delimiter, basestring): + if (delimiter is None) or isinstance(delimiter, str): delimiter = delimiter or None _handyman = self._delimited_splitter # Delimiter is a list of field widths @@ -345,7 +345,7 @@ def validate(self, names, defaultfmt="f%i", nbfields=None): if (nbfields is None): return None names = [] - if isinstance(names, basestring): + if isinstance(names, str): names = [names, ] if nbfields is not None: nbnames = len(names) @@ -659,7 +659,7 @@ def __init__(self, dtype_or_func=None, default=None, missing_values=None, if missing_values is None: self.missing_values = {''} else: - if isinstance(missing_values, basestring): + if isinstance(missing_values, str): missing_values = missing_values.split(",") self.missing_values = set(list(missing_values) + ['']) # @@ -834,7 +834,7 @@ def update(self, func, default=None, testing_value=None, else: if not np.iterable(missing_values): missing_values = [missing_values] - if not all(isinstance(v, basestring) for v in missing_values): + if not all(isinstance(v, str) for v in missing_values): raise TypeError("missing_values must be strings or unicode") self.missing_values.update(missing_values) @@ -884,7 +884,7 @@ def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): nbfields = len(ndtype) if names is None: names = [''] * len(ndtype) - elif isinstance(names, basestring): + elif isinstance(names, str): names = names.split(",") names = validate(names, nbfields=nbfields, defaultfmt=defaultfmt) ndtype = np.dtype(dict(formats=ndtype, names=names)) @@ -892,7 +892,7 @@ def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): # Explicit names if names is not None: validate = NameValidator(**validationargs) - if isinstance(names, basestring): + if isinstance(names, str): names = names.split(",") # Simple dtype: repeat to match the nb of names if ndtype.names is None: diff --git a/numpy/lib/_version.py b/numpy/lib/_version.py index 6a7c5cba1d77..d4098acb5aea 100644 --- a/numpy/lib/_version.py +++ b/numpy/lib/_version.py @@ -7,8 +7,6 @@ """ import re -from numpy.compat import basestring - __all__ = ['NumpyVersion'] @@ -114,10 +112,10 @@ def _compare_pre_release(self, other): return vercmp def _compare(self, other): - if not isinstance(other, (basestring, NumpyVersion)): + if not isinstance(other, (str, NumpyVersion)): raise ValueError("Invalid object to compare with NumpyVersion.") - if isinstance(other, basestring): + if isinstance(other, str): other = NumpyVersion(other) vercmp = self._compare_version(other) diff --git a/numpy/lib/histograms.py b/numpy/lib/histograms.py index 70ecd6eb150e..5358c6846e9a 100644 --- a/numpy/lib/histograms.py +++ b/numpy/lib/histograms.py @@ -7,7 +7,6 @@ import warnings import numpy as np -from numpy.compat.py3k import basestring from numpy.core import overrides __all__ = ['histogram', 'histogramdd', 'histogram_bin_edges'] @@ -383,7 +382,7 @@ def _get_bin_edges(a, bins, range, weights): n_equal_bins = None bin_edges = None - if isinstance(bins, basestring): + if isinstance(bins, str): bin_name = bins # if `bins` is a string for an automatic method, # this will replace it with the number of bins calculated diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index 48d4f7fa28fb..f43fcf0c05a7 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -23,7 +23,7 @@ ) from numpy.compat import ( - asbytes, asstr, asunicode, bytes, basestring, os_fspath, os_PathLike, + asbytes, asstr, asunicode, bytes, os_fspath, os_PathLike, pickle, contextlib_nullcontext ) @@ -918,7 +918,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, """ # Type conversions for Py3 convenience if comments is not None: - if isinstance(comments, (basestring, bytes)): + if isinstance(comments, (str, bytes)): comments = [comments] comments = [_decode_line(x) for x in comments] # Compile regex for comments beforehand @@ -1391,7 +1391,7 @@ def first_write(self, v): if len(fmt) != ncol: raise AttributeError('fmt has wrong shape. %s' % str(fmt)) format = asstr(delimiter).join(map(asstr, fmt)) - elif isinstance(fmt, basestring): + elif isinstance(fmt, str): n_fmt_chars = fmt.count('%') error = ValueError('fmt has wrong number of %% formats: %s' % fmt) if n_fmt_chars == 1: @@ -1747,7 +1747,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, try: if isinstance(fname, os_PathLike): fname = os_fspath(fname) - if isinstance(fname, basestring): + if isinstance(fname, str): fid = np.lib._datasource.open(fname, 'rt', encoding=encoding) fid_ctx = contextlib.closing(fid) else: @@ -1889,7 +1889,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, if value not in entry: entry.append(value) # We have a string : apply it to all entries - elif isinstance(user_missing_values, basestring): + elif isinstance(user_missing_values, str): user_value = user_missing_values.split(",") for entry in missing_values: entry.extend(user_value) diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index af4cfa09d7d1..03c0c82f5cf1 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -13,7 +13,6 @@ from numpy.ma.mrecords import MaskedRecords from numpy.core.overrides import array_function_dispatch from numpy.lib._iotools import _is_string_like -from numpy.compat import basestring from numpy.testing import suppress_warnings _check_fill_value = np.ma.core._check_fill_value @@ -299,7 +298,7 @@ def _izip_fields(iterable): """ for element in iterable: if (hasattr(element, '__iter__') and - not isinstance(element, basestring)): + not isinstance(element, str)): for f in _izip_fields(element): yield f elif isinstance(element, np.void) and len(tuple(element)) == 1: @@ -698,7 +697,7 @@ def append_fields(base, names, data, dtypes=None, if len(names) != len(data): msg = "The number of arrays does not match the number of names" raise ValueError(msg) - elif isinstance(names, basestring): + elif isinstance(names, str): names = [names, ] data = [data, ] # @@ -1455,7 +1454,7 @@ def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', "'outer' or 'leftouter' (got '%s' instead)" % jointype ) # If we have a single key, put it in a tuple - if isinstance(key, basestring): + if isinstance(key, str): key = (key,) # Check the keys diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 41c35026dcc3..6fe442c69195 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -35,7 +35,7 @@ from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( - getargspec, formatargspec, long, basestring, unicode, bytes + getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple @@ -456,7 +456,7 @@ def _check_fill_value(fill_value, ndtype): fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype), dtype=ndtype) else: - if isinstance(fill_value, basestring) and (ndtype.char not in 'OSVU'): + if isinstance(fill_value, str) and (ndtype.char not in 'OSVU'): # Note this check doesn't work if fill_value is not a scalar err_msg = "Cannot set fill value of string with array of dtype %s" raise TypeError(err_msg % ndtype) @@ -781,9 +781,9 @@ def fix_invalid(a, mask=nomask, copy=True, fill_value=None): return a def is_string_or_list_of_strings(val): - return (isinstance(val, basestring) or + return (isinstance(val, str) or (isinstance(val, list) and val and - builtins.all(isinstance(s, basestring) for s in val))) + builtins.all(isinstance(s, str) for s in val))) ############################################################################### # Ufuncs # @@ -3300,7 +3300,7 @@ def __setitem__(self, indx, value): raise MaskError('Cannot alter the masked element.') _data = self._data _mask = self._mask - if isinstance(indx, basestring): + if isinstance(indx, str): _data[indx] = value if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py index 4ff7866ab5c8..a154cbbc8464 100644 --- a/numpy/ma/mrecords.py +++ b/numpy/ma/mrecords.py @@ -17,7 +17,6 @@ import warnings import numpy as np -from numpy.compat import basestring from numpy import ( bool_, dtype, ndarray, recarray, array as narray ) @@ -303,7 +302,7 @@ def __getitem__(self, indx): _mask = ndarray.__getattribute__(self, '_mask') _data = ndarray.view(self, _localdict['_baseclass']) # We want a field - if isinstance(indx, basestring): + if isinstance(indx, str): # Make sure _sharedmask is True to propagate back to _fieldmask # Don't use _set_mask, there are some copies being made that # break propagation Don't force the mask to nomask, that wreaks @@ -330,7 +329,7 @@ def __setitem__(self, indx, value): """ MaskedArray.__setitem__(self, indx, value) - if isinstance(indx, basestring): + if isinstance(indx, str): self._mask[indx] = ma.getmaskarray(value) def __str__(self): diff --git a/numpy/testing/_private/nosetester.py b/numpy/testing/_private/nosetester.py index 45a582bb62fd..bd6d002aa535 100644 --- a/numpy/testing/_private/nosetester.py +++ b/numpy/testing/_private/nosetester.py @@ -7,7 +7,6 @@ import os import sys import warnings -from numpy.compat import basestring import numpy as np from .utils import import_nose, suppress_warnings @@ -212,7 +211,7 @@ def _test_argv(self, label, verbose, extra_argv): ''' argv = [__file__, self.package_path, '-s'] if label and label != 'full': - if not isinstance(label, basestring): + if not isinstance(label, str): raise TypeError('Selection label should be a string') if label == 'fast': label = 'not slow' @@ -419,7 +418,7 @@ def test(self, label='fast', verbose=1, extra_argv=None, _warn_opts = dict(develop=(Warning,), release=()) - if isinstance(raise_warnings, basestring): + if isinstance(raise_warnings, str): raise_warnings = _warn_opts[raise_warnings] with suppress_warnings("location") as sup: diff --git a/numpy/tests/test_scripts.py b/numpy/tests/test_scripts.py index 20447bcf358c..658606f8218f 100644 --- a/numpy/tests/test_scripts.py +++ b/numpy/tests/test_scripts.py @@ -9,7 +9,6 @@ import subprocess import numpy as np -from numpy.compat.py3k import basestring from numpy.testing import assert_, assert_equal is_inplace = isfile(pathjoin(dirname(np.__file__), '..', 'setup.py'))