From b67d35f335a2d85ac3642bbc1879fa85275969c2 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 28 Aug 2018 18:52:23 +0200 Subject: [PATCH] cbook.iterable -> np.iterable. --- .../2018-08-17-AL-deprecations.rst | 1 + examples/units/basic_units.py | 7 ++- examples/units/evans_test.py | 7 +-- lib/matplotlib/animation.py | 2 +- lib/matplotlib/artist.py | 2 +- lib/matplotlib/axes/_axes.py | 43 +++++++++---------- lib/matplotlib/axes/_base.py | 10 ++--- lib/matplotlib/cbook/__init__.py | 5 ++- lib/matplotlib/colorbar.py | 10 ++--- lib/matplotlib/colors.py | 14 +++--- lib/matplotlib/contour.py | 6 +-- lib/matplotlib/dates.py | 12 +++--- lib/matplotlib/figure.py | 6 +-- lib/matplotlib/lines.py | 9 ++-- lib/matplotlib/mlab.py | 18 ++++---- lib/matplotlib/patches.py | 6 +-- lib/matplotlib/sankey.py | 7 ++- .../testing/jpl_units/EpochConverter.py | 7 +-- .../testing/jpl_units/StrConverter.py | 5 ++- .../testing/jpl_units/UnitDblConverter.py | 6 +-- lib/matplotlib/tests/test_mlab.py | 2 +- lib/matplotlib/tests/test_units.py | 5 +-- lib/matplotlib/units.py | 6 +-- lib/mpl_toolkits/axes_grid1/colorbar.py | 2 +- lib/mpl_toolkits/mplot3d/art3d.py | 2 +- lib/mpl_toolkits/mplot3d/axes3d.py | 12 +++--- 26 files changed, 106 insertions(+), 106 deletions(-) rename doc/api/{api_changes => next_api_changes}/2018-08-17-AL-deprecations.rst (84%) diff --git a/doc/api/api_changes/2018-08-17-AL-deprecations.rst b/doc/api/next_api_changes/2018-08-17-AL-deprecations.rst similarity index 84% rename from doc/api/api_changes/2018-08-17-AL-deprecations.rst rename to doc/api/next_api_changes/2018-08-17-AL-deprecations.rst index 71d2c2c2e5a1..d83b63f561f6 100644 --- a/doc/api/api_changes/2018-08-17-AL-deprecations.rst +++ b/doc/api/next_api_changes/2018-08-17-AL-deprecations.rst @@ -4,4 +4,5 @@ API deprecations The following API elements are deprecated: - ``tk_window_focus``, +- ``cbook.iterable``, - ``mlab.demean``, diff --git a/examples/units/basic_units.py b/examples/units/basic_units.py index 0af2e1dd576d..ffc1222e4381 100644 --- a/examples/units/basic_units.py +++ b/examples/units/basic_units.py @@ -11,7 +11,6 @@ import matplotlib.units as units import matplotlib.ticker as ticker -from matplotlib.cbook import iterable class ProxyDelegate(object): @@ -345,7 +344,7 @@ def axisinfo(unit, axis): def convert(val, unit, axis): if units.ConversionInterface.is_numlike(val): return val - if iterable(val): + if np.iterable(val): return [thisval.convert_to(unit).get_value() for thisval in val] else: return val.convert_to(unit).get_value() @@ -353,14 +352,14 @@ def convert(val, unit, axis): @staticmethod def default_units(x, axis): 'return the default unit for x or None' - if iterable(x): + if np.iterable(x): for thisx in x: return thisx.unit return x.unit def cos(x): - if iterable(x): + if np.iterable(x): return [math.cos(val.convert_to(radians).get_value()) for val in x] else: return math.cos(x.convert_to(radians).get_value()) diff --git a/examples/units/evans_test.py b/examples/units/evans_test.py index 36dcc240ea75..72acfb4bf6ca 100644 --- a/examples/units/evans_test.py +++ b/examples/units/evans_test.py @@ -9,7 +9,8 @@ to what kind of units client packages use. """ -from matplotlib.cbook import iterable +import numpy as np + import matplotlib.units as units import matplotlib.ticker as ticker import matplotlib.pyplot as plt @@ -49,7 +50,7 @@ def convert(obj, unit, axis): if units.ConversionInterface.is_numlike(obj): return obj - if iterable(obj): + if np.iterable(obj): return [o.value(unit) for o in obj] else: return obj.value(unit) @@ -57,7 +58,7 @@ def convert(obj, unit, axis): @staticmethod def default_units(x, axis): 'return the default unit for x or None' - if iterable(x): + if np.iterable(x): for thisx in x: return thisx.unit else: diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index 2a85d23bb724..56e45d5865dc 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -1643,7 +1643,7 @@ def __init__(self, fig, func, frames=None, init_func=None, fargs=None, self._iter_gen = itertools.count elif callable(frames): self._iter_gen = frames - elif cbook.iterable(frames): + elif np.iterable(frames): self._iter_gen = lambda: iter(frames) if hasattr(frames, '__len__'): self.save_count = len(frames) diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index 184253791b3c..3a5fec61a878 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -1175,7 +1175,7 @@ def __init__(self, o): responsibility to make sure this is so. """ if not isinstance(o, Artist): - if cbook.iterable(o): + if np.iterable(o): o = list(o) if len(o): o = o[0] diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 5e01e5a1c537..47ba5739e46f 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -33,7 +33,6 @@ import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.tri as mtri -from matplotlib.cbook import iterable from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer from matplotlib.axes._base import _AxesBase, _process_plot_format @@ -1035,11 +1034,11 @@ def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', xmin = self.convert_xunits(xmin) xmax = self.convert_xunits(xmax) - if not iterable(y): + if not np.iterable(y): y = [y] - if not iterable(xmin): + if not np.iterable(xmin): xmin = [xmin] - if not iterable(xmax): + if not np.iterable(xmax): xmax = [xmax] y, xmin, xmax = cbook.delete_masked_points(y, xmin, xmax) @@ -1113,11 +1112,11 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', ymin = self.convert_yunits(ymin) ymax = self.convert_yunits(ymax) - if not iterable(x): + if not np.iterable(x): x = [x] - if not iterable(ymin): + if not np.iterable(ymin): ymin = [ymin] - if not iterable(ymax): + if not np.iterable(ymax): ymax = [ymax] x, ymin, ymax = cbook.delete_masked_points(x, ymin, ymax) @@ -1243,9 +1242,9 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, lineoffsets = self.convert_yunits(lineoffsets) linelengths = self.convert_yunits(linelengths) - if not iterable(positions): + if not np.iterable(positions): positions = [positions] - elif any(iterable(position) for position in positions): + elif any(np.iterable(position) for position in positions): positions = [np.asanyarray(position) for position in positions] else: positions = [np.asanyarray(positions)] @@ -1259,15 +1258,15 @@ def eventplot(self, positions, orientation='horizontal', lineoffsets=1, linewidths = cbook.local_over_kwdict(linewidths, kwargs, 'linewidth') linestyles = cbook.local_over_kwdict(linestyles, kwargs, 'linestyle') - if not iterable(lineoffsets): + if not np.iterable(lineoffsets): lineoffsets = [lineoffsets] - if not iterable(linelengths): + if not np.iterable(linelengths): linelengths = [linelengths] - if not iterable(linewidths): + if not np.iterable(linewidths): linewidths = [linewidths] - if not iterable(colors): + if not np.iterable(colors): colors = [colors] - if hasattr(linestyles, 'lower') or not iterable(linestyles): + if hasattr(linestyles, 'lower') or not np.iterable(linestyles): linestyles = [linestyles] lineoffsets = np.asarray(lineoffsets) @@ -3065,18 +3064,18 @@ def errorbar(self, x, y, yerr=None, xerr=None, ecolor = base_style['color'] # make sure all the args are iterable; use lists not arrays to # preserve units - if not iterable(x): + if not np.iterable(x): x = [x] - if not iterable(y): + if not np.iterable(y): y = [y] if xerr is not None: - if not iterable(xerr): + if not np.iterable(xerr): xerr = [xerr] * len(x) if yerr is not None: - if not iterable(yerr): + if not np.iterable(yerr): yerr = [yerr] * len(y) # make the style dict for the 'normal' plot line @@ -3168,7 +3167,7 @@ def extract_err(err, data): except (TypeError, ValueError): pass else: - if iterable(a) and iterable(b): + if np.iterable(a) and np.iterable(b): # using list comps rather than arrays to preserve units low = [thisx - thiserr for thisx, thiserr in cbook.safezip(data, a)] @@ -4437,7 +4436,7 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, x, y, C = cbook.delete_masked_points(x, y, C) # Set the size of the hexagon grid - if iterable(gridsize): + if np.iterable(gridsize): nx, ny = gridsize else: nx = gridsize @@ -4632,7 +4631,7 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, norm.autoscale(accum) if bins is not None: - if not iterable(bins): + if not np.iterable(bins): minimum, maximum = min(accum), max(accum) bins -= 1 # one less edge than bins bins = minimum + (maximum - minimum) * np.arange(bins) / bins @@ -6514,7 +6513,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, bin_range = self.convert_xunits(bin_range) # Check whether bins or range are given explicitly. - binsgiven = (cbook.iterable(bins) or bin_range is not None) + binsgiven = np.iterable(bins) or bin_range is not None # We need to do to 'weights' what was done to 'x' if weights is not None: diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 73dbea627fa5..d7bdc4a08475 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -13,7 +13,7 @@ from matplotlib import cbook, rcParams from matplotlib.cbook import ( - _OrderedSet, _check_1d, _string_to_bool, iterable, index_of, get_label) + _OrderedSet, _check_1d, _string_to_bool, index_of, get_label) from matplotlib import docstring import matplotlib.colors as mcolors import matplotlib.lines as mlines @@ -3005,7 +3005,7 @@ def set_xbound(self, lower=None, upper=None): .. ACCEPTS: (lower: float, upper: float) """ - if upper is None and iterable(lower): + if upper is None and np.iterable(lower): lower, upper = lower old_lower, old_upper = self.get_xbound() @@ -3124,7 +3124,7 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, >>> set_xlim(5000, 0) """ - if right is None and iterable(left): + if right is None and np.iterable(left): left, right = left if xmin is not None: cbook.warn_deprecated('3.0', name='`xmin`', @@ -3357,7 +3357,7 @@ def set_ybound(self, lower=None, upper=None): .. ACCEPTS: (lower: float, upper: float) """ - if upper is None and iterable(lower): + if upper is None and np.iterable(lower): lower, upper = lower old_lower, old_upper = self.get_ybound() @@ -3457,7 +3457,7 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, >>> set_ylim(5000, 0) """ - if top is None and iterable(bottom): + if top is None and np.iterable(bottom): bottom, top = bottom if ymin is not None: cbook.warn_deprecated('3.0', name='`ymin`', diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 20cc748abbb2..3debb61c08ee 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -327,6 +327,7 @@ class is even handier, and prettier to use. Whenever you want to pass +@deprecated('3.1', alternative='np.iterable') def iterable(obj): """return true if *obj* is iterable""" try: @@ -415,7 +416,7 @@ def open_file_cm(path_or_file, mode="r", encoding=None): def is_scalar_or_string(val): """Return whether the given object is a scalar or string like.""" - return isinstance(val, str) or not iterable(val) + return isinstance(val, str) or not np.iterable(val) def _string_to_bool(s): @@ -1026,7 +1027,7 @@ def delete_masked_points(*args): margs = [] seqlist = [False] * len(args) for i, x in enumerate(args): - if not isinstance(x, str) and iterable(x) and len(x) == nrecs: + if not isinstance(x, str) and np.iterable(x) and len(x) == nrecs: seqlist[i] = True if isinstance(x, np.ma.MaskedArray): if x.ndim > 1: diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index a198cb5fe66c..e2cdcb91a60f 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -388,7 +388,7 @@ def __init__(self, ax, cmap=None, self.ticklocation = ticklocation self.set_label(label) - if cbook.iterable(ticks): + if np.iterable(ticks): self.locator = ticker.FixedLocator(ticks, nbins=len(ticks)) else: self.locator = ticks # Handle default in _ticker() @@ -559,7 +559,7 @@ def set_ticks(self, ticks, update_ticks=True): use :meth:`update_ticks` to manually update the ticks. """ - if cbook.iterable(ticks): + if np.iterable(ticks): self.locator = ticker.FixedLocator(ticks, nbins=len(ticks)) else: self.locator = ticks @@ -707,9 +707,9 @@ def add_lines(self, levels, colors, linewidths, erase=True): y = self._locate(levels) igood = (y < 1.001) & (y > -0.001) y = y[igood] - if cbook.iterable(colors): + if np.iterable(colors): colors = np.asarray(colors)[igood] - if cbook.iterable(linewidths): + if np.iterable(linewidths): linewidths = np.asarray(linewidths)[igood] X, Y = np.meshgrid([0, 1], y) if self.orientation == 'vertical': @@ -1289,7 +1289,7 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, anchor = kw.pop('anchor', loc_settings['anchor']) parent_anchor = kw.pop('panchor', loc_settings['panchor']) - parents_iterable = cbook.iterable(parents) + parents_iterable = np.iterable(parents) # turn parents into a list if it is not already. We do this w/ np # because `plt.subplots` can return an ndarray and is natural to # pass to `colorbar`. diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index ef51fc20bdd7..75ac1a85e098 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -484,7 +484,7 @@ def __call__(self, X, alpha=None, bytes=False): if not self._isinit: self._init() mask_bad = None - if not cbook.iterable(X): + if not np.iterable(X): vtype = 'scalar' xa = np.array([X]) else: @@ -716,7 +716,7 @@ def from_list(name, colors, N=256, gamma=1.0): to divide the range unevenly. """ - if not cbook.iterable(colors): + if not np.iterable(colors): raise ValueError('colors must be iterable') if (isinstance(colors[0], Sized) and len(colors[0]) == 2 @@ -812,7 +812,7 @@ def __init__(self, colors, name='from_list', N=None): if isinstance(colors, str): self.colors = [colors] * N self.monochrome = True - elif cbook.iterable(colors): + elif np.iterable(colors): if len(colors) == 1: self.monochrome = True self.colors = list( @@ -907,7 +907,7 @@ def process_value(value): Experimental; we may want to add an option to force the use of float32. """ - is_scalar = not cbook.iterable(value) + is_scalar = not np.iterable(value) if is_scalar: value = [value] dtype = np.min_scalar_type(value) @@ -962,7 +962,7 @@ def inverse(self, value): (vmin,), _ = self.process_value(self.vmin) (vmax,), _ = self.process_value(self.vmax) - if cbook.iterable(value): + if np.iterable(value): val = np.ma.asarray(value) return vmin + val * (vmax - vmin) else: @@ -1035,7 +1035,7 @@ def inverse(self, value): raise ValueError("Not invertible until scaled") vmin, vmax = self.vmin, self.vmax - if cbook.iterable(value): + if np.iterable(value): val = np.ma.asarray(value) return vmin * np.ma.power((vmax / vmin), val) else: @@ -1222,7 +1222,7 @@ def inverse(self, value): gamma = self.gamma vmin, vmax = self.vmin, self.vmax - if cbook.iterable(value): + if np.iterable(value): val = np.ma.asarray(value) return np.ma.power(val, 1. / gamma) * (vmax - vmin) + vmin else: diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 620103849384..43bc3c116207 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -197,7 +197,7 @@ def clabel(self, *args, self.labelXYs = [] - if cbook.iterable(self.labelManual): + if np.iterable(self.labelManual): for x, y in self.labelManual: self.add_label_near(x, y, inline, inline_spacing) @@ -1333,7 +1333,7 @@ def _process_linewidths(self): if linewidths is None: tlinewidths = [(mpl.rcParams['lines.linewidth'],)] * Nlev else: - if not cbook.iterable(linewidths): + if not np.iterable(linewidths): linewidths = [linewidths] * Nlev else: linewidths = list(linewidths) @@ -1359,7 +1359,7 @@ def _process_linestyles(self): else: if isinstance(linestyles, str): tlinestyles = [linestyles] * Nlev - elif cbook.iterable(linestyles): + elif np.iterable(linestyles): tlinestyles = list(linestyles) if len(tlinestyles) < Nlev: nreps = int(np.ceil(Nlev / len(linestyles))) diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index 57c1d6bdce98..a229e09f5e63 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -413,7 +413,7 @@ def date2num(d): if ((isinstance(d, np.ndarray) and np.issubdtype(d.dtype, np.datetime64)) or isinstance(d, np.datetime64)): return _dt64_to_ordinalf(d) - if not cbook.iterable(d): + if not np.iterable(d): return _to_ordinalf(d) else: d = np.asarray(d) @@ -436,7 +436,7 @@ def julian2num(j): float or sequence of floats Matplotlib date(s) """ - if cbook.iterable(j): + if np.iterable(j): j = np.asarray(j) return j - JULIAN_OFFSET @@ -455,7 +455,7 @@ def num2julian(n): float or sequence of floats Julian date(s) """ - if cbook.iterable(n): + if np.iterable(n): n = np.asarray(n) return n + JULIAN_OFFSET @@ -488,7 +488,7 @@ def num2date(x, tz=None): """ if tz is None: tz = _get_rc_timezone() - if not cbook.iterable(x): + if not np.iterable(x): return _from_ordinalf(x, tz) else: x = np.asarray(x) @@ -521,7 +521,7 @@ def num2timedelta(x): `datetime.timedelta` or list[`datetime.timedelta`] """ - if not cbook.iterable(x): + if not np.iterable(x): return _ordinalf_to_timedelta(x) else: x = np.asarray(x) @@ -1676,7 +1676,7 @@ def mx2num(mxdates): instances) to the new date format. """ scalar = False - if not cbook.iterable(mxdates): + if not np.iterable(mxdates): scalar = True mxdates = [mxdates] ret = epoch2num([m.ticks() for m in mxdates]) diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 917a53568f71..5cf42d349638 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -27,7 +27,7 @@ import matplotlib.cbook as cbook -from matplotlib.cbook import Stack, iterable +from matplotlib.cbook import Stack from matplotlib import image as mimage from matplotlib.image import FigureImage @@ -1028,7 +1028,7 @@ def fixitems(items): for k, v in items: # some objects can define __getitem__ without being # iterable and in those cases the conversion to tuples - # will fail. So instead of using the iterable(v) function + # will fail. So instead of using the np.iterable(v) function # we simply try and convert to a tuple, and proceed if not. try: v = tuple(v) @@ -1040,7 +1040,7 @@ def fixitems(items): def fixlist(args): ret = [] for a in args: - if iterable(a): + if np.iterable(a): a = tuple(a) ret.append(a) return tuple(ret) diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index fe08d8e8bb7f..18cc6d389b24 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -12,8 +12,7 @@ from . import artist, cbook, colors as mcolors, docstring, rcParams from .artist import Artist, allow_rasterization from .cbook import ( - _to_unmasked_float_array, iterable, ls_mapper, ls_mapper_r, - STEP_LOOKUP_MAP) + _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP) from .markers import MarkerStyle from .path import Path from .transforms import Bbox, TransformedPath @@ -190,7 +189,7 @@ def _slice_or_none(in_v, slc): # mazol tov, it's already a slice, just return return Path(verts[markevery], _slice_or_none(codes, markevery)) - elif iterable(markevery): + elif np.iterable(markevery): #fancy indexing try: return Path(verts[markevery], _slice_or_none(codes, markevery)) @@ -311,9 +310,9 @@ def __init__(self, xdata, ydata, Artist.__init__(self) #convert sequences to numpy arrays - if not iterable(xdata): + if not np.iterable(xdata): raise RuntimeError('xdata must be a sequence') - if not iterable(ydata): + if not np.iterable(ydata): raise RuntimeError('ydata must be a sequence') if linewidth is None: diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 2a7cb55fdddc..18754c64a789 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -133,7 +133,7 @@ def apply_window(x, window, axis=0, return_window=None): xshape = list(x.shape) xshapetarg = xshape.pop(axis) - if cbook.iterable(window): + if np.iterable(window): if len(window) != xshapetarg: raise ValueError('The len(window) must be the same as the shape ' 'of x for the chosen axis') @@ -1309,7 +1309,7 @@ def cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=detrend_none, # cache the FFT of every windowed, detrended NFFT length segment # of every channel. If preferSpeedOverMemory, cache the conjugate # as well - if cbook.iterable(window): + if np.iterable(window): if len(window) != NFFT: raise ValueError("The length of the window must be equal to NFFT") windowVals = window @@ -1634,7 +1634,7 @@ def prctile_rank(x, p): indicates how many quantiles of data you want ranked. """ - if not cbook.iterable(p): + if not np.iterable(p): p = np.arange(100.0/p, 100.0, 100.0/p) else: p = np.asarray(p) @@ -1850,7 +1850,7 @@ def fftsurr(x, detrend=detrend_none, window=window_none): """ Compute an FFT phase randomized surrogate of *x*. """ - if cbook.iterable(window): + if np.iterable(window): x = window*detrend(x) else: x = window(detrend(x)) @@ -2218,7 +2218,7 @@ def rec_append_fields(rec, names, arrs, dtypes=None): *arrs* and *dtypes* do not have to be lists. They can just be the values themselves. """ - if (not isinstance(names, str) and cbook.iterable(names) + if (not isinstance(names, str) and np.iterable(names) and len(names) and isinstance(names[0], str)): if len(names) != len(arrs): raise ValueError("number of arrays do not match number of names") @@ -2228,7 +2228,7 @@ def rec_append_fields(rec, names, arrs, dtypes=None): arrs = list(map(np.asarray, arrs)) if dtypes is None: dtypes = [a.dtype for a in arrs] - elif not cbook.iterable(dtypes): + elif not np.iterable(dtypes): dtypes = [dtypes] if len(arrs) != len(dtypes): if len(dtypes) == 1: @@ -3710,10 +3710,10 @@ def poly_between(x, ylower, yupper): numpy = np Nx = len(x) - if not cbook.iterable(ylower): + if not np.iterable(ylower): ylower = ylower*numpy.ones(Nx) - if not cbook.iterable(yupper): + if not np.iterable(yupper): yupper = yupper*numpy.ones(Nx) x = numpy.concatenate((x, x[::-1])) @@ -3889,7 +3889,7 @@ def offset_line(y, yerr): plt.show() """ - if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and + if cbook.is_numlike(yerr) or (np.iterable(yerr) and len(yerr) == len(y)): ymin = y - yerr ymax = y + yerr diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 12a4e5bb7f21..ab9938fcc749 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -3221,7 +3221,7 @@ def __call__(self, path, mutation_size, linewidth, path_mutated, fillable = self.transmute(path_shrunk, linewidth, mutation_size) - if cbook.iterable(fillable): + if np.iterable(fillable): path_list = [] for p in zip(path_mutated): v, c = p.vertices, p.codes @@ -4244,7 +4244,7 @@ def get_path(self): """ _path, fillable = self.get_path_in_displaycoord() - if cbook.iterable(fillable): + if np.iterable(fillable): _path = concatenate_paths(_path) return self.get_transform().inverted().transform_path(_path) @@ -4292,7 +4292,7 @@ def draw(self, renderer): self.set_dpi_cor(renderer.points_to_pixels(1.)) path, fillable = self.get_path_in_displaycoord() - if not cbook.iterable(fillable): + if not np.iterable(fillable): path = [path] fillable = [fillable] diff --git a/lib/matplotlib/sankey.py b/lib/matplotlib/sankey.py index 72460f4a0ed2..77964a76882e 100644 --- a/lib/matplotlib/sankey.py +++ b/lib/matplotlib/sankey.py @@ -7,7 +7,6 @@ import numpy as np -from matplotlib.cbook import iterable from matplotlib.path import Path from matplotlib.patches import PathPatch from matplotlib.transforms import Affine2D @@ -451,8 +450,8 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', "orientations has length %d, but flows has length %d." % (len(orientations), n)) if labels != '' and getattr(labels, '__iter__', False): - # iterable() isn't used because it would give True if labels is a - # string + # np.iterable() isn't used because it would give True if labels is + # a string if len(labels) != n: raise ValueError( "If labels is a list, then labels and flows must have the " @@ -550,7 +549,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', angles[i] = DOWN # Justify the lengths of the paths. - if iterable(pathlengths): + if np.iterable(pathlengths): if len(pathlengths) != n: raise ValueError( "If pathlengths is a list, then pathlengths and flows must " diff --git a/lib/matplotlib/testing/jpl_units/EpochConverter.py b/lib/matplotlib/testing/jpl_units/EpochConverter.py index f66932ac9927..b07ffef5e03f 100644 --- a/lib/matplotlib/testing/jpl_units/EpochConverter.py +++ b/lib/matplotlib/testing/jpl_units/EpochConverter.py @@ -1,8 +1,9 @@ """EpochConverter module containing class EpochConverter.""" +import numpy as np + import matplotlib.units as units import matplotlib.dates as date_ticker -from matplotlib.cbook import iterable __all__ = ['EpochConverter'] @@ -97,7 +98,7 @@ def convert(value, unit, axis): isNotEpoch = True isDuration = False - if iterable(value) and not isinstance(value, str): + if np.iterable(value) and not isinstance(value, str): if len(value) == 0: return [] else: @@ -131,7 +132,7 @@ def default_units(value, axis): - Returns the default units to use for value. """ frame = None - if iterable(value) and not isinstance(value, str): + if np.iterable(value) and not isinstance(value, str): return EpochConverter.default_units(value[0], axis) else: frame = value.frame() diff --git a/lib/matplotlib/testing/jpl_units/StrConverter.py b/lib/matplotlib/testing/jpl_units/StrConverter.py index ac6b847e93a5..a595a5d6abe4 100644 --- a/lib/matplotlib/testing/jpl_units/StrConverter.py +++ b/lib/matplotlib/testing/jpl_units/StrConverter.py @@ -1,7 +1,8 @@ """StrConverter module containing class StrConverter.""" +import numpy as np + import matplotlib.units as units -from matplotlib.cbook import iterable __all__ = ['StrConverter'] @@ -70,7 +71,7 @@ def convert(value, unit, axis): ticks = [] labels = [] - if not iterable(value): + if not np.iterable(value): value = [value] newValues = [] diff --git a/lib/matplotlib/testing/jpl_units/UnitDblConverter.py b/lib/matplotlib/testing/jpl_units/UnitDblConverter.py index b53291b48300..342ac00cc523 100644 --- a/lib/matplotlib/testing/jpl_units/UnitDblConverter.py +++ b/lib/matplotlib/testing/jpl_units/UnitDblConverter.py @@ -1,9 +1,9 @@ """UnitDblConverter module containing class UnitDblConverter.""" import numpy as np + import matplotlib.units as units import matplotlib.projections.polar as polar -from matplotlib.cbook import iterable __all__ = ['UnitDblConverter'] @@ -85,7 +85,7 @@ def convert(value, unit, axis): isNotUnitDbl = True - if iterable(value) and not isinstance(value, str): + if np.iterable(value) and not isinstance(value, str): if len(value) == 0: return [] else: @@ -128,7 +128,7 @@ def default_units(value, axis): # Determine the default units based on the user preferences set for # default units when printing a UnitDbl. - if iterable(value) and not isinstance(value, str): + if np.iterable(value) and not isinstance(value, str): return UnitDblConverter.default_units(value[0], axis) else: return UnitDblConverter.defaults[value.type()] diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 6109d326f4a0..30f2b9db4e4f 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -305,7 +305,7 @@ def check_window_apply_repeat(self, x, window, NFFT, noverlap): n = len(ind) result = np.zeros((NFFT, n)) - if cbook.iterable(window): + if np.iterable(window): windowVals = window else: windowVals = window(np.ones((NFFT,), x.dtype)) diff --git a/lib/matplotlib/tests/test_units.py b/lib/matplotlib/tests/test_units.py index 20840d7b8702..9433ed4105ef 100644 --- a/lib/matplotlib/tests/test_units.py +++ b/lib/matplotlib/tests/test_units.py @@ -1,6 +1,5 @@ from unittest.mock import MagicMock -from matplotlib.cbook import iterable import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison import matplotlib.units as munits @@ -29,7 +28,7 @@ def __getattr__(self, attr): return getattr(self.magnitude, attr) def __getitem__(self, item): - if iterable(self.magnitude): + if np.iterable(self.magnitude): return Quantity(self.magnitude[item], self.units) else: return Quantity(self.magnitude, self.units) @@ -51,7 +50,7 @@ def test_numpy_facade(): def convert(value, unit, axis): if hasattr(value, 'units'): return value.to(unit).magnitude - elif iterable(value): + elif np.iterable(value): try: return [v.to(unit).magnitude for v in value] except AttributeError: diff --git a/lib/matplotlib/units.py b/lib/matplotlib/units.py index c23d791b092a..12d7a7e2617e 100644 --- a/lib/matplotlib/units.py +++ b/lib/matplotlib/units.py @@ -46,7 +46,7 @@ def default_units(x, axis): import numpy as np -from matplotlib.cbook import iterable, safe_first_element +from matplotlib import cbook class AxisInfo(object): @@ -122,7 +122,7 @@ def is_numlike(x): current unit. The converter may be passed these floats, or arrays of them, even when units are set. """ - if iterable(x): + if np.iterable(x): for thisx in x: return isinstance(thisx, Number) else: @@ -184,7 +184,7 @@ def get_converter(self, x): # If we haven't found a converter yet, try to get the first element if converter is None: try: - thisx = safe_first_element(x) + thisx = cbook.safe_first_element(x) except (TypeError, StopIteration): pass else: diff --git a/lib/mpl_toolkits/axes_grid1/colorbar.py b/lib/mpl_toolkits/axes_grid1/colorbar.py index 32d638988e57..baf6ca2d94d3 100644 --- a/lib/mpl_toolkits/axes_grid1/colorbar.py +++ b/lib/mpl_toolkits/axes_grid1/colorbar.py @@ -384,7 +384,7 @@ def __init__(self, ax, cmap=None, else: self.cbar_axis.set_major_formatter(formatter) - if cbook.iterable(ticks): + if np.iterable(ticks): self.cbar_axis.set_ticks(ticks) elif ticks is not None: self.cbar_axis.set_major_locator(ticks) diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py index 862d04788bc3..0b592c68e877 100644 --- a/lib/mpl_toolkits/mplot3d/art3d.py +++ b/lib/mpl_toolkits/mplot3d/art3d.py @@ -66,7 +66,7 @@ def get_dir_vector(zdir): return np.array((0, 0, 1)) elif zdir is None: return np.array((0, 0, 0)) - elif cbook.iterable(zdir) and len(zdir) == 3: + elif np.iterable(zdir) and len(zdir) == 3: return zdir else: raise ValueError("'x', 'y', 'z', None or vector of length 3 expected") diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 211c807eb8c6..efbaedfef284 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -586,7 +586,7 @@ def get_w_lims(self): return minx, maxx, miny, maxy, minz, maxz def _determine_lims(self, xmin=None, xmax=None, *args, **kwargs): - if xmax is None and cbook.iterable(xmin): + if xmax is None and np.iterable(xmin): xmin, xmax = xmin if xmin == xmax: xmin -= 0.05 @@ -601,7 +601,7 @@ def set_xlim3d(self, left=None, right=None, emit=True, auto=False, See :meth:`matplotlib.axes.Axes.set_xlim` for full documentation. """ - if right is None and cbook.iterable(left): + if right is None and np.iterable(left): left, right = left if xmin is not None: cbook.warn_deprecated('3.0', name='`xmin`', @@ -659,7 +659,7 @@ def set_ylim3d(self, bottom=None, top=None, emit=True, auto=False, See :meth:`matplotlib.axes.Axes.set_ylim` for full documentation. """ - if top is None and cbook.iterable(bottom): + if top is None and np.iterable(bottom): bottom, top = bottom if ymin is not None: cbook.warn_deprecated('3.0', name='`ymin`', @@ -717,7 +717,7 @@ def set_zlim3d(self, bottom=None, top=None, emit=True, auto=False, See :meth:`matplotlib.axes.Axes.set_ylim` for full documentation """ - if top is None and cbook.iterable(bottom): + if top is None and np.iterable(bottom): bottom, top = bottom if zmin is not None: cbook.warn_deprecated('3.0', name='`zmin`', @@ -1466,7 +1466,7 @@ def set_zbound(self, lower=None, upper=None): .. versionadded :: 1.1.0 This function was added, but not tested. Please report any bugs. """ - if upper is None and cbook.iterable(lower): + if upper is None and np.iterable(lower): lower,upper = lower old_lower,old_upper = self.get_zbound() @@ -2292,7 +2292,7 @@ def scatter(self, xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True, xs, ys, zs, s, c = cbook.delete_masked_points(xs, ys, zs, s, c) patches = super().scatter(xs, ys, s=s, c=c, *args, **kwargs) - is_2d = not cbook.iterable(zs) + is_2d = not np.iterable(zs) zs = np.broadcast_to(zs, len(xs)) art3d.patch_collection_2d_to_3d(patches, zs=zs, zdir=zdir, depthshade=depthshade)