Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Completely deprecate is_string_like.
I had missed that numpy's `str_` (and `unicode_` on Py2) derive from the
corresponding builtin type(s), so `isinstance(x, six.string_types)` is
just as good.
  • Loading branch information
anntzer committed Apr 15, 2017
commit 5ca32abb4633431783c415c147ee943a32208bda
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)`` and. In particular, this means that arrays are

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

and what?

@anntzer anntzer Apr 15, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

typo, fixed

now not num-like.

`cbook.is_string_like` and `cbook.is_sequence_of_strings` have been
deprecated. Use ``isinstance(obj, six.string_types)`` and ``all(isinstance(o,
six.string_types) for o in obj) and not iterable(obj)`` instead.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

That doesn't seem right:

In [9]: from matplotlib.cbook import iterable, is_sequence_of_strings

In [10]: obj = ['a', 'b', 'c']

In [11]: is_sequence_of_strings(obj)
Out[11]: True

In [12]: import six

In [13]: all(isinstance(o, six.string_types) for o in obj) and not iterable(obj)
Out[13]: False

(using 2.0.0, though)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the "not" needs to be removed, fixed

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
4 changes: 2 additions & 2 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
# 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,
from matplotlib.cbook import (
mplDeprecation,
dedent, get_label,
sanitize_sequence)
Expand Down Expand Up @@ -1225,7 +1225,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
10 changes: 5 additions & 5 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import matplotlib.cbook as cbook
from matplotlib.cbook import (mplDeprecation, STEP_LOOKUP_MAP,
iterable, is_string_like,
iterable,
safe_first_element)
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
Expand Down Expand Up @@ -2662,7 +2662,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 +5472,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 +6380,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
8 changes: 4 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,7 @@ 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 +1556,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
3 changes: 1 addition & 2 deletions lib/matplotlib/backends/backend_cairo.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ def _fn_name(): return sys._getframe(1).f_code.co_name

from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
FigureManagerBase, FigureCanvasBase
from matplotlib.cbook import is_string_like
from matplotlib.figure import Figure
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
Expand Down Expand Up @@ -555,7 +554,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
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def _fn_name(): return sys._getframe(1).f_code.co_name
from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
FigureManagerBase, FigureCanvasBase

from matplotlib.cbook import is_string_like, get_realpath_and_stat, \
from matplotlib.cbook import get_realpath_and_stat, \
is_writable_file_like, maxdict, file_requires_unicode
from matplotlib.compat.subprocess import subprocess
from matplotlib.figure import Figure
Expand Down Expand Up @@ -141,7 +141,7 @@ def _get_papertype(w, h):
return 'a0'

def _num_to_str(val):
if is_string_like(val): return val
if isinstance(val, six.string_types): return val

ival = int(val)
if val==ival: return str(ival)
Expand Down Expand Up @@ -977,7 +977,7 @@ def _print_figure(self, outfile, format, dpi=72, facecolor='w', edgecolor='w',
"""
isEPSF = format == 'eps'
passed_in_file_object = False
if is_string_like(outfile):
if isinstance(outfile, six.string_types):
title = outfile
elif is_writable_file_like(outfile):
title = None
Expand Down Expand Up @@ -1220,7 +1220,7 @@ def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor,
the key 'Creator' is used.
"""
isEPSF = format == 'eps'
if is_string_like(outfile):
if isinstance(outfile, six.string_types):
title = outfile
elif is_writable_file_like(outfile):
title = None
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/backends/backend_qt4.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import matplotlib

from matplotlib.cbook import is_string_like
from matplotlib.backend_bases import FigureManagerBase
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.backend_bases import NavigationToolbar2
Expand Down
Loading