Skip to content

Commit

Permalink
Merge pull request #15407 from charris/replace-basestring
Browse files Browse the repository at this point in the history
MAINT: Replace basestring with str.
  • Loading branch information
seberg committed Jan 24, 2020
2 parents 4c32890 + b4e3a42 commit 68224f4
Show file tree
Hide file tree
Showing 15 changed files with 36 additions and 46 deletions.
7 changes: 3 additions & 4 deletions numpy/core/einsumfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:]]

Expand Down Expand Up @@ -820,15 +819,15 @@ 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
elif len(path_type) and (path_type[0] == 'einsum_path'):
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]
Expand Down
4 changes: 2 additions & 2 deletions numpy/core/memmap.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions numpy/core/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion numpy/core/numerictypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
3 changes: 1 addition & 2 deletions numpy/distutils/misc_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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. """
Expand Down
2 changes: 1 addition & 1 deletion numpy/f2py/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
14 changes: 7 additions & 7 deletions numpy/lib/_iotools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) + [''])
#
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -884,15 +884,15 @@ 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))
else:
# 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:
Expand Down
6 changes: 2 additions & 4 deletions numpy/lib/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
"""
import re

from numpy.compat import basestring


__all__ = ['NumpyVersion']

Expand Down Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions numpy/lib/histograms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
Expand Down Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions numpy/lib/npyio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 3 additions & 4 deletions numpy/lib/recfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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, ]
#
Expand Down Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions numpy/ma/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 #
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions numpy/ma/mrecords.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand Down
5 changes: 2 additions & 3 deletions numpy/testing/_private/nosetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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:
Expand Down
1 change: 0 additions & 1 deletion numpy/tests/test_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down

0 comments on commit 68224f4

Please sign in to comment.