Skip to content
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
9 changes: 9 additions & 0 deletions doc/api/next_api_changes/2019-06-07-AL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Exception changes
`````````````````

Various APIs that raised a `ValueError` for incorrectly typed inputs now raise
`TypeError` instead: `backend_bases.GraphicsContextBase.set_clip_path`,
`blocking_input.BlockingInput.__call__`, `cm.register_cmap`, `dviread.DviFont`,
`rcsetup.validate_hatch`, `rcsetup.validate_animation_writer_path`, `spines.Spine`,
many classes in the :mod:`matplotlib.transforms` module and :mod:`matplotlib.tri`
package, and Axes methods that take a ``norm`` parameter.
21 changes: 0 additions & 21 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4454,9 +4454,6 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
collection.update(kwargs)

if colors is None:
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_array(c)
collection.set_cmap(cmap)
collection.set_norm(norm)
Expand Down Expand Up @@ -4770,11 +4767,6 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None,
offset_position="data"
)

# Check for valid norm
if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)

# Set normalizer if bins is 'log'
if bins == 'log':
if norm is not None:
Expand Down Expand Up @@ -5590,9 +5582,6 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
`~matplotlib.pyplot.imshow` expects RGB images adopting the straight
(unassociated) alpha representation.
"""
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
if aspect is None:
aspect = rcParams['image.aspect']
self.set_aspect(aspect)
Expand Down Expand Up @@ -5882,9 +5871,6 @@ def pcolor(self, *args, alpha=None, norm=None, cmap=None, vmin=None,

collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_clim(vmin, vmax)
Expand Down Expand Up @@ -6099,9 +6085,6 @@ def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
**kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_clim(vmin, vmax)
Expand Down Expand Up @@ -6238,11 +6221,7 @@ def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
Notes
-----
.. [notes section required to get data note injection right]

"""
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")

C = args[-1]
nr, nc = np.shape(C)[:2]
Expand Down
16 changes: 4 additions & 12 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1631,9 +1631,7 @@ def set_major_formatter(self, formatter):
----------
formatter : ~matplotlib.ticker.Formatter
"""
if not isinstance(formatter, mticker.Formatter):
raise TypeError("formatter argument should be instance of "
"matplotlib.ticker.Formatter")
cbook._check_isinstance(mticker.Formatter, formatter=formatter)
self.isDefault_majfmt = False
self.major.formatter = formatter
formatter.set_axis(self)
Expand All @@ -1647,9 +1645,7 @@ def set_minor_formatter(self, formatter):
----------
formatter : ~matplotlib.ticker.Formatter
"""
if not isinstance(formatter, mticker.Formatter):
raise TypeError("formatter argument should be instance of "
"matplotlib.ticker.Formatter")
cbook._check_isinstance(mticker.Formatter, formatter=formatter)
self.isDefault_minfmt = False
self.minor.formatter = formatter
formatter.set_axis(self)
Expand All @@ -1663,9 +1659,7 @@ def set_major_locator(self, locator):
----------
locator : ~matplotlib.ticker.Locator
"""
if not isinstance(locator, mticker.Locator):
raise TypeError("locator argument should be instance of "
"matplotlib.ticker.Locator")
cbook._check_isinstance(mticker.Locator, locator=locator)
self.isDefault_majloc = False
self.major.locator = locator
if self.major.formatter:
Expand All @@ -1681,9 +1675,7 @@ def set_minor_locator(self, locator):
----------
locator : ~matplotlib.ticker.Locator
"""
if not isinstance(locator, mticker.Locator):
raise TypeError("locator argument should be instance of "
"matplotlib.ticker.Locator")
cbook._check_isinstance(mticker.Locator, locator=locator)
self.isDefault_minloc = False
self.minor.locator = locator
if self.minor.formatter:
Expand Down
12 changes: 6 additions & 6 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -879,13 +879,13 @@ def set_clip_rectangle(self, rectangle):

def set_clip_path(self, path):
"""
Set the clip path and transformation. Path should be a
:class:`~matplotlib.transforms.TransformedPath` instance.
Set the clip path and transformation.

Parameters
----------
path : `~matplotlib.transforms.TransformedPath` or None
"""
if (path is not None
and not isinstance(path, transforms.TransformedPath)):
raise ValueError("Path should be a "
"matplotlib.transforms.TransformedPath instance")
cbook._check_isinstance((transforms.TransformedPath, None), path=path)
self._clippath = path

def set_dashes(self, dash_offset, dash_list):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/blocking_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import logging
from numbers import Integral

from matplotlib import cbook
import matplotlib.lines as mlines

_log = logging.getLogger(__name__)
Expand Down Expand Up @@ -76,8 +77,7 @@ def pop_event(self, index=-1):

def __call__(self, n=1, timeout=30):
"""Blocking call to retrieve *n* events."""
if not isinstance(n, Integral):
raise ValueError("Requires an integer argument")
cbook._check_isinstance(Integral, n=n)
self.n = n
self.events = []

Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@

import numpy as np

import matplotlib.units as units
import matplotlib.ticker as ticker
from matplotlib import cbook, ticker, units


_log = logging.getLogger(__name__)
Expand Down Expand Up @@ -204,8 +203,7 @@ def update(self, data):
convertible = True
for val in OrderedDict.fromkeys(data):
# OrderedDict just iterates over unique values in data.
if not isinstance(val, (str, bytes)):
raise TypeError("{val!r} is not a string".format(val=val))
cbook._check_isinstance((str, bytes), value=val)
if convertible:
# this will only be called so long as convertible is True.
convertible = self._str_is_convertible(val)
Expand Down
34 changes: 34 additions & 0 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2011,6 +2011,40 @@ def _check_and_log_subprocess(command, logger, **kwargs):
return report


def _check_isinstance(types, **kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* is an instance
of one of *types*; if not, raise an appropriate TypeError.

As a special case, a ``None`` entry in *types* is treated as NoneType.

Examples
--------
>>> cbook._check_isinstance((SomeClass, None), arg=arg)
"""
if isinstance(types, type) or types is None:
types = (types,)
none_allowed = None in types
types = tuple(tp for tp in types if tp is not None)

def type_name(tp):
return (tp.__qualname__ if tp.__module__ == "builtins"
else f"{tp.__module__}.{tp.__qualname__}")

names = [*map(type_name, types)]
if none_allowed:
types = (*types, type(None))
names.append("None")
for k, v in kwargs.items():
if not isinstance(v, types):
raise TypeError(
"{!r} must be an instance of {}, not a {}".format(
k,
", ".join(names[:-1]) + " or " + names[-1]
if len(names) > 1 else names[0],
type_name(type(v))))


def _check_in_list(values, **kwargs):
"""
For each *key, value* pair in *kwargs*, check that *value* is in *values*;
Expand Down
8 changes: 2 additions & 6 deletions lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,21 +130,16 @@ def register_cmap(name=None, cmap=None, data=None, lut=None):
In the second case, the three arguments are passed to
the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
and the resulting colormap is registered.

"""
cbook._check_isinstance((str, None), name=name)
if name is None:
try:
name = cmap.name
except AttributeError:
raise ValueError("Arguments must include a name or a Colormap")

if not isinstance(name, str):
raise ValueError("Colormap name must be a string")

if isinstance(cmap, colors.Colormap):
cmap_d[name] = cmap
return

# For the remainder, let exceptions propagate.
if lut is None:
lut = mpl.rcParams['image.lut']
Expand Down Expand Up @@ -362,6 +357,7 @@ def set_norm(self, norm):
on the colorbar to default.

"""
cbook._check_isinstance((colors.Normalize, None), norm=norm)
if norm is None:
norm = colors.Normalize()
self.norm = norm
Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/dviread.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,9 +525,7 @@ class DviFont:
__slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')

def __init__(self, scale, tfm, texname, vf):
if not isinstance(texname, bytes):
raise ValueError("texname must be a bytestring, got %s"
% type(texname))
cbook._check_isinstance(bytes, texname=texname)
self._scale = scale
self._tfm = tfm
self.texname = texname
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ def add(self, key, a):
"""
# All the error checking may be unnecessary; but this method
# is called so seldom that the overhead is negligible.
if not isinstance(a, Axes):
raise ValueError("second argument, {!r}, is not an Axes".format(a))
cbook._check_isinstance(Axes, a=a)
try:
hash(key)
except TypeError:
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,10 +738,10 @@ def validate_hatch(s):
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\ / | - + * . x o O``.

"""
if not isinstance(s, str):
raise ValueError("Hatch pattern must be a string")
cbook._check_isinstance(str, hatch_pattern=s)
unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
if unknown:
raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
Expand Down Expand Up @@ -955,8 +955,7 @@ def validate_animation_writer_path(p):
# Make sure it's a string and then figure out if the animations
# are already loaded and reset the writers (which will validate
# the path on next call)
if not isinstance(p, str):
raise ValueError("path must be a (unicode) string")
cbook._check_isinstance(str, path=p)
from sys import modules
# set dirty, so that the next call to the registry will re-evaluate
# the state.
Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/spines.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,7 @@ def __init__(self, axes, spine_type, path, **kwargs):
# non-rectangular axes is currently implemented, and this lets
# them pass through the spines machinery without errors.)
self._position = None
if not isinstance(path, matplotlib.path.Path):
raise ValueError(
"'path' must be an instance of 'matplotlib.path.Path'")
cbook._check_isinstance(matplotlib.path.Path, path=path)
self._path = path

# To support drawing both linear and circular spines, this
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,7 @@ def __setitem__(self, position, cell):
"""
Set a custom cell in a given position.
"""
if not isinstance(cell, CustomCell):
raise TypeError('Table only accepts CustomCell')
cbook._check_isinstance(CustomCell, cell=cell)
try:
row, col = position[0], position[1]
except Exception:
Expand Down
17 changes: 4 additions & 13 deletions lib/matplotlib/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -989,9 +989,7 @@ def __init__(self, bbox, transform, **kwargs):
"""
if not bbox.is_bbox:
raise ValueError("'bbox' is not a bbox")
if not isinstance(transform, Transform):
raise ValueError("'transform' must be an instance of "
"'matplotlib.transform.Transform'")
cbook._check_isinstance(Transform, transform=transform)
if transform.input_dims != 2 or transform.output_dims != 2:
raise ValueError(
"The input and output dimensions of 'transform' must be 2")
Expand Down Expand Up @@ -1586,9 +1584,7 @@ def __init__(self, child):
*child*: A class:`Transform` instance. This child may later
be replaced with :meth:`set`.
"""
if not isinstance(child, Transform):
raise ValueError("'child' must be an instance of "
"'matplotlib.transform.Transform'")
cbook._check_isinstance(Transform, child=child)
self._init(child)
self.set_children(child)

Expand Down Expand Up @@ -1864,9 +1860,7 @@ def set(self, other):
Set this transformation from the frozen copy of another
:class:`Affine2DBase` object.
"""
if not isinstance(other, Affine2DBase):
raise ValueError("'other' must be an instance of "
"'matplotlib.transform.Affine2DBase'")
cbook._check_isinstance(Affine2DBase, other=other)
self._mtx = other.get_matrix()
self.invalidate()

Expand Down Expand Up @@ -2655,11 +2649,8 @@ def __init__(self, path, transform):
path : `~.path.Path`
transform : `Transform`
"""
if not isinstance(transform, Transform):
raise ValueError("'transform' must be an instance of "
"'matplotlib.transform.Transform'")
cbook._check_isinstance(Transform, transform=transform)
TransformNode.__init__(self)

self._path = path
self._transform = transform
self.set_children(transform)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tri/trifinder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np

from matplotlib import cbook
from matplotlib.tri import Triangulation


Expand All @@ -16,8 +17,7 @@ class TriFinder:
coordinates of the same shape.
"""
def __init__(self, triangulation):
if not isinstance(triangulation, Triangulation):
raise ValueError('Expected a Triangulation object')
cbook._check_isinstance(Triangulation, triangulation=triangulation)
self._triangulation = triangulation


Expand Down
Loading