Skip to content

Deprecate is_string_like, is_sequence_of_strings #8011

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions doc/api/api_changes/2017-01-30-AL_is_numlike_stringlike.rst
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
`cbook.is_numlike` and `cbook.is_string_like` only perform an instance check
````````````````````````````````````````````````````````````````````````````
`cbook.is_numlike` only performs an instance check, `cbook.is_string_like` is deprecated
````````````````````````````````````````````````````````````````````````````````````````

`cbook.is_numlike` and `cbook.is_string_like` now only check that
their argument is an instance of ``(numbers.Number, np.Number)`` and
``(six.string_types, np.str_, np.unicode_)`` respectively. In particular, this
means that arrays are now never num-like or string-like regardless of their
dtype.
`cbook.is_numlike` now only checks that its argument is an instance of
``(numbers.Number, np.Number)``. In particular, this means that arrays are now
not num-like.

`cbook.is_string_like` and `cbook.is_sequence_of_strings` have been
deprecated. Use ``isinstance(obj, six.string_types)`` and ``iterable(obj) and
all(isinstance(o, six.string_types) for o in obj)`` instead.
6 changes: 6 additions & 0 deletions doc/users/whats_new/scatter_no_longer_flattens.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
`Collection` offsets are no longer implicitly flattened
-------------------------------------------------------

`Collection` (and thus `scatter` -- both 2D and 3D) no longer implicitly
flattens its offsets. As a consequence, `scatter`'s x and y arguments can no
longer be 2+-dimensional arrays.
3 changes: 1 addition & 2 deletions examples/misc/rc_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import os
import re
import traits.api as traits
from matplotlib.cbook import is_string_like
from matplotlib.artist import Artist

doprint = True
Expand Down Expand Up @@ -75,7 +74,7 @@ def tuple_to_rgba(ob, name, val):
def hex_to_rgba(ob, name, val):
rgx = re.compile('^#[0-9A-Fa-f]{6}$')

if not is_string_like(val):
if not isinstance(val, six.string_types):
raise TypeError
if rgx.match(val) is None:
raise ValueError
Expand Down
6 changes: 3 additions & 3 deletions examples/mplot3d/2dcollections3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
# Fixing random state for reproducibility
np.random.seed(19680801)

x = np.random.sample(20*len(colors))
y = np.random.sample(20*len(colors))
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
c_list.append([c]*20)
c_list.extend([c] * 20)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually related?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not really, moved out.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh actually i remember now, it is.
this is because 3d scatter no longer implicitly flattens its input (see the last hunk of the diff).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably should add that to the API what's new, then.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Also documented the similar change in #7786 at the same time.

# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x,y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x,z)')
Expand Down
12 changes: 4 additions & 8 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,10 @@
# cbook must import matplotlib only within function
# definitions, so it is safe to import from it here.
from . import cbook
from matplotlib.cbook import (is_string_like,
mplDeprecation,
dedent, get_label,
sanitize_sequence)
from matplotlib.cbook import (
mplDeprecation, dedent, get_label, sanitize_sequence)
from matplotlib.compat import subprocess
from matplotlib.rcsetup import (defaultParams,
validate_backend,
cycler)
from matplotlib.rcsetup import defaultParams, validate_backend, cycler

import numpy
from six.moves.urllib.request import urlopen
Expand Down Expand Up @@ -1225,7 +1221,7 @@ def rc(group, **kwargs):
'aa': 'antialiased',
}

if is_string_like(group):
if isinstance(group, six.string_types):
group = (group,)
for g in group:
for k, v in six.iteritems(kwargs):
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
import contextlib
import tempfile
import warnings
from matplotlib.cbook import iterable, is_string_like, deprecated
from matplotlib.cbook import iterable, deprecated
from matplotlib.compat import subprocess
from matplotlib import verbose
from matplotlib import rcParams, rcParamsDefault, rc_context
Expand Down Expand Up @@ -1023,7 +1023,7 @@ class to use, such as 'ffmpeg' or 'mencoder'. If `None`,
# to use
if writer is None:
writer = rcParams['animation.writer']
elif (not is_string_like(writer) and
elif (not isinstance(writer, six.string_types) and
any(arg is not None
for arg in (fps, codec, bitrate, extra_args, metadata))):
raise RuntimeError('Passing in values for arguments '
Expand Down Expand Up @@ -1068,7 +1068,7 @@ class to use, such as 'ffmpeg' or 'mencoder'. If `None`,

# If we have the name of a writer, instantiate an instance of the
# registered class.
if is_string_like(writer):
if isinstance(writer, six.string_types):
if writer in writers.avail:
writer = writers[writer](fps, codec, bitrate,
extra_args=extra_args,
Expand Down
13 changes: 6 additions & 7 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@
from matplotlib import _preprocess_data

import matplotlib.cbook as cbook
from matplotlib.cbook import (mplDeprecation, STEP_LOOKUP_MAP,
iterable, is_string_like,
safe_first_element)
from matplotlib.cbook import (
mplDeprecation, STEP_LOOKUP_MAP, iterable, safe_first_element)
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
import matplotlib.contour as mcontour
Expand Down Expand Up @@ -2662,7 +2661,7 @@ def get_next_color():
if autopct is not None:
xt = x + pctdistance * radius * math.cos(thetam)
yt = y + pctdistance * radius * math.sin(thetam)
if is_string_like(autopct):
if isinstance(autopct, six.string_types):
s = autopct % (100. * frac)
elif callable(autopct):
s = autopct(100. * frac)
Expand Down Expand Up @@ -5472,8 +5471,8 @@ def pcolor(self, *args, **kwargs):
# makes artifacts that are often disturbing.
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and (is_string_like(ec) and
ec.lower() == "none"):
if 'antialiaseds' not in kwargs and (
isinstance(ec, six.string_types) and ec.lower() == "none"):
kwargs['antialiaseds'] = False

kwargs.setdefault('snap', False)
Expand Down Expand Up @@ -6380,7 +6379,7 @@ def hist(self, x, bins=None, range=None, normed=False, weights=None,

if label is None:
labels = [None]
elif is_string_like(label):
elif isinstance(label, six.string_types):
labels = [label]
else:
labels = [six.text_type(lab) for lab in label]
Expand Down
9 changes: 5 additions & 4 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def _makefill(self, x, y, kw, kwargs):

def _plot_args(self, tup, kwargs):
ret = []
if len(tup) > 1 and is_string_like(tup[-1]):
if len(tup) > 1 and isinstance(tup[-1], six.string_types):
linestyle, marker, color = _process_plot_format(tup[-1])
tup = tup[:-1]
elif len(tup) == 3:
Expand Down Expand Up @@ -398,7 +398,7 @@ def _plot_args(self, tup, kwargs):
def _grab_next_args(self, *args, **kwargs):
while args:
this, args = args[:2], args[2:]
if args and is_string_like(args[0]):
if args and isinstance(args[0], six.string_types):
this += args[0],
args = args[1:]
for seg in self._plot_args(this, kwargs):
Expand Down Expand Up @@ -1281,7 +1281,8 @@ def set_aspect(self, aspect, adjustable=None, anchor=None):
etc.
===== =====================
"""
if cbook.is_string_like(aspect) and aspect in ('equal', 'auto'):
if (isinstance(aspect, six.string_types)
and aspect in ('equal', 'auto')):
self._aspect = aspect
else:
self._aspect = float(aspect) # raise ValueError if necessary
Expand Down Expand Up @@ -1556,7 +1557,7 @@ def axis(self, *v, **kwargs):

emit = kwargs.get('emit', True)

if len(v) == 1 and is_string_like(v[0]):
if len(v) == 1 and isinstance(v[0], six.string_types):
s = v[0].lower()
if s == 'on':
self.set_axis_on()
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def get_registered_canvas_class(format):
if format not in _default_backends:
return None
backend_class = _default_backends[format]
if cbook.is_string_like(backend_class):
if isinstance(backend_class, six.string_types):
backend_class = importlib.import_module(backend_class).FigureCanvas
_default_backends[format] = backend_class
return backend_class
Expand Down Expand Up @@ -2090,11 +2090,11 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,

if format is None:
# get format from filename, or from backend's default filetype
if cbook.is_string_like(filename):
if isinstance(filename, six.string_types):
format = os.path.splitext(filename)[1][1:]
if format is None or format == '':
format = self.get_default_filetype()
if cbook.is_string_like(filename):
if isinstance(filename, six.string_types):
filename = filename.rstrip('.') + '.' + format
format = format.lower()

Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from matplotlib import verbose, rcParams, __version__
from matplotlib.backend_bases import (RendererBase, FigureManagerBase,
FigureCanvasBase)
from matplotlib.cbook import is_string_like, maxdict, restrict_dict
from matplotlib.cbook import maxdict, restrict_dict
from matplotlib.figure import Figure
from matplotlib.font_manager import findfont, get_font
from matplotlib.ft2font import (LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING,
Expand Down Expand Up @@ -530,7 +530,7 @@ def print_raw(self, filename_or_obj, *args, **kwargs):
renderer = self.get_renderer()
original_dpi = renderer.dpi
renderer.dpi = self.figure.dpi
if is_string_like(filename_or_obj):
if isinstance(filename_or_obj, six.string_types):
fileobj = open(filename_or_obj, 'wb')
close = True
else:
Expand All @@ -549,7 +549,7 @@ def print_png(self, filename_or_obj, *args, **kwargs):
renderer = self.get_renderer()
original_dpi = renderer.dpi
renderer.dpi = self.figure.dpi
if is_string_like(filename_or_obj):
if isinstance(filename_or_obj, six.string_types):
filename_or_obj = open(filename_or_obj, 'wb')
close = True
else:
Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/backends/backend_cairo.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def _fn_name(): return sys._getframe(1).f_code.co_name
try:
import cairo
except ImportError:
raise ImportError("Cairo backend requires that cairocffi or pycairo is installed.")
raise ImportError("Cairo backend requires that cairocffi or pycairo "
"is installed.")
else:
HAS_CAIRO_CFFI = False
else:
Expand All @@ -49,9 +50,8 @@ def _fn_name(): return sys._getframe(1).f_code.co_name
backend_version = cairo.version
del _version_required

from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
FigureManagerBase, FigureCanvasBase
from matplotlib.cbook import is_string_like
from matplotlib.backend_bases import (
RendererBase, GraphicsContextBase, FigureManagerBase, FigureCanvasBase)
from matplotlib.figure import Figure
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
Expand Down Expand Up @@ -555,7 +555,7 @@ def _save (self, fo, format, **kwargs):
raise RuntimeError ('cairo has not been compiled with SVG '
'support enabled')
if format == 'svgz':
if is_string_like(fo):
if isinstance(fo, six.string_types):
fo = gzip.GzipFile(fo, 'wb')
else:
fo = gzip.GzipFile(None, 'wb', fileobj=fo)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_gdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def fn_name(): return sys._getframe(1).f_code.co_name
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import RendererBase, GraphicsContextBase, \
FigureManagerBase, FigureCanvasBase
from matplotlib.cbook import is_string_like, restrict_dict, warn_deprecated
from matplotlib.cbook import restrict_dict, warn_deprecated
from matplotlib.figure import Figure
from matplotlib.mathtext import MathTextParser
from matplotlib.transforms import Affine2D
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_gtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def fn_name(): return sys._getframe(1).f_code.co_name
from matplotlib.backend_bases import ShowBase

from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK
from matplotlib.cbook import is_string_like, is_writable_file_like
from matplotlib.cbook import is_writable_file_like
from matplotlib.figure import Figure
from matplotlib.widgets import SubplotTool
from matplotlib.cbook import warn_deprecated
Expand Down Expand Up @@ -490,7 +490,7 @@ def _print_image(self, filename, format, *args, **kwargs):

options['quality'] = str(options['quality'])

if is_string_like(filename):
if isinstance(filename, six.string_types):
try:
pixbuf.save(filename, format, options=options)
except gobject.GError as exc:
Expand Down Expand Up @@ -908,7 +908,7 @@ class DialogLineprops(object):
linestyled = {s: i for i, s in enumerate(linestyles)}

markers = [m for m in markers.MarkerStyle.markers
if cbook.is_string_like(m)]
if isinstance(m, six.string_types)]
markerd = {s: i for i, s in enumerate(markers)}

def __init__(self, lines):
Expand Down Expand Up @@ -1068,7 +1068,7 @@ def error_msg_gtk(msg, parent=None):
if parent.flags() & gtk.TOPLEVEL == 0:
parent = None

if not is_string_like(msg):
if not isinstance(msg, six.string_types):
msg = ','.join(map(str,msg))

dialog = gtk.MessageDialog(
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_gtk3.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def fn_name(): return sys._getframe(1).f_code.co_name
from matplotlib.backend_managers import ToolManager
from matplotlib import backend_tools

from matplotlib.cbook import is_string_like, is_writable_file_like
from matplotlib.cbook import is_writable_file_like
from matplotlib.figure import Figure
from matplotlib.widgets import SubplotTool

Expand Down Expand Up @@ -954,7 +954,7 @@ def error_msg_gtk(msg, parent=None):
if not parent.is_toplevel():
parent = None

if not is_string_like(msg):
if not isinstance(msg, six.string_types):
msg = ','.join(map(str,msg))

dialog = Gtk.MessageDialog(
Expand Down
7 changes: 5 additions & 2 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from matplotlib.backend_bases import (RendererBase, GraphicsContextBase,
FigureManagerBase, FigureCanvasBase)
from matplotlib.backends.backend_mixed import MixedModeRenderer
from matplotlib.cbook import (Bunch, is_string_like, get_realpath_and_stat,
from matplotlib.cbook import (Bunch, get_realpath_and_stat,
is_writable_file_like, maxdict)
from matplotlib.figure import Figure
from matplotlib.font_manager import findfont, is_opentype_cff_font, get_font
Expand Down Expand Up @@ -434,7 +434,7 @@ def __init__(self, filename, metadata=None):
self.passed_in_file_object = False
self.original_file_like = None
self.tell_base = 0
if is_string_like(filename):
if isinstance(filename, six.string_types):
fh = open(filename, 'wb')
elif is_writable_file_like(filename):
try:
Expand Down Expand Up @@ -1564,6 +1564,9 @@ def writeXref(self):
def writeInfoDict(self):
"""Write out the info dictionary, checking it for good form"""

def is_string_like(x):
return isinstance(x, six.string_types)

def is_date(x):
return isinstance(x, datetime)

Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from matplotlib.text import Text
from matplotlib.path import Path
from matplotlib import _png, rcParams
from matplotlib.cbook import is_string_like, is_writable_file_like
from matplotlib.cbook import is_writable_file_like
from matplotlib.compat import subprocess
from matplotlib.compat.subprocess import check_output

Expand Down Expand Up @@ -859,7 +859,7 @@ def print_pgf(self, fname_or_fh, *args, **kwargs):
return

# figure out where the pgf is to be written to
if is_string_like(fname_or_fh):
if isinstance(fname_or_fh, six.string_types):
with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh:
self._print_pgf_to_fh(fh, *args, **kwargs)
elif is_writable_file_like(fname_or_fh):
Expand Down Expand Up @@ -923,7 +923,7 @@ def print_pdf(self, fname_or_fh, *args, **kwargs):
return

# figure out where the pdf is to be written to
if is_string_like(fname_or_fh):
if isinstance(fname_or_fh, six.string_types):
with open(fname_or_fh, "wb") as fh:
self._print_pdf_to_fh(fh, *args, **kwargs)
elif is_writable_file_like(fname_or_fh):
Expand Down Expand Up @@ -959,7 +959,7 @@ def print_png(self, fname_or_fh, *args, **kwargs):
self._print_pgf_to_fh(None, *args, **kwargs)
return

if is_string_like(fname_or_fh):
if isinstance(fname_or_fh, six.string_types):
with open(fname_or_fh, "wb") as fh:
self._print_png_to_fh(fh, *args, **kwargs)
elif is_writable_file_like(fname_or_fh):
Expand Down
Loading