Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8a270fc

Browse filesBrowse files
committed
Merge pull request #3060 from montefra/no_assert
MNT : converted assert into exception Convert input-validation assertions to raise Exceptions (mostly ValueError) instead.
2 parents 23f17dd + d6c3c32 commit 8a270fc
Copy full SHA for 8a270fc
Expand file treeCollapse file tree

26 files changed

+372
-174
lines changed

‎lib/matplotlib/axes/_axes.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_axes.py
+35-27Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1984,19 +1984,19 @@ def make_iterable(x):
19841984
if len(edgecolor) < nbars:
19851985
edgecolor *= nbars
19861986

1987-
# FIXME: convert the following to proper input validation
1988-
# raising ValueError; don't use assert for this.
1989-
assert len(left) == nbars, ("incompatible sizes: argument 'left' must "
1990-
"be length %d or scalar" % nbars)
1991-
assert len(height) == nbars, ("incompatible sizes: argument 'height' "
1992-
"must be length %d or scalar" %
1993-
nbars)
1994-
assert len(width) == nbars, ("incompatible sizes: argument 'width' "
1995-
"must be length %d or scalar" %
1996-
nbars)
1997-
assert len(bottom) == nbars, ("incompatible sizes: argument 'bottom' "
1998-
"must be length %d or scalar" %
1999-
nbars)
1987+
# input validation
1988+
if len(left) != nbars:
1989+
raise ValueError("incompatible sizes: argument 'left' must "
1990+
"be length %d or scalar" % nbars)
1991+
if len(height) != nbars:
1992+
raise ValueError("incompatible sizes: argument 'height' "
1993+
"must be length %d or scalar" % nbars)
1994+
if len(width) != nbars:
1995+
raise ValueError("incompatible sizes: argument 'width' "
1996+
"must be length %d or scalar" % nbars)
1997+
if len(bottom) != nbars:
1998+
raise ValueError("incompatible sizes: argument 'bottom' "
1999+
"must be length %d or scalar" % nbars)
20002000

20012001
patches = []
20022002

@@ -2434,8 +2434,10 @@ def pie(self, x, explode=None, labels=None, colors=None,
24342434
labels = [''] * len(x)
24352435
if explode is None:
24362436
explode = [0] * len(x)
2437-
assert(len(x) == len(labels))
2438-
assert(len(x) == len(explode))
2437+
if len(x) != len(labels):
2438+
raise ValueError("'label' must be of length 'x'")
2439+
if len(x) != len(explode):
2440+
raise ValueError("'explode' must be of length 'x'")
24392441
if colors is None:
24402442
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w')
24412443

@@ -3692,8 +3694,9 @@ def scatter(self, x, y, s=20, c=None, marker='o', cmap=None, norm=None,
36923694
collection.update(kwargs)
36933695

36943696
if colors is None:
3695-
if norm is not None:
3696-
assert(isinstance(norm, mcolors.Normalize))
3697+
if norm is not None and not isinstance(norm, mcolors.Normalize):
3698+
msg = "'norm' must be an instance of 'mcolors.Normalize'"
3699+
raise ValueError(msg)
36973700
collection.set_array(np.asarray(c))
36983701
collection.set_cmap(cmap)
36993702
collection.set_norm(norm)
@@ -4063,8 +4066,9 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None,
40634066
bins = np.sort(bins)
40644067
accum = bins.searchsorted(accum)
40654068

4066-
if norm is not None:
4067-
assert(isinstance(norm, mcolors.Normalize))
4069+
if norm is not None and not isinstance(norm, mcolors.Normalize):
4070+
msg = "'norm' must be an instance of 'mcolors.Normalize'"
4071+
raise ValueError(msg)
40684072
collection.set_array(accum)
40694073
collection.set_cmap(cmap)
40704074
collection.set_norm(norm)
@@ -4679,8 +4683,9 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
46794683
if not self._hold:
46804684
self.cla()
46814685

4682-
if norm is not None:
4683-
assert(isinstance(norm, mcolors.Normalize))
4686+
if norm is not None and not isinstance(norm, mcolors.Normalize):
4687+
msg = "'norm' must be an instance of 'mcolors.Normalize'"
4688+
raise ValueError(msg)
46844689
if aspect is None:
46854690
aspect = rcParams['image.aspect']
46864691
self.set_aspect(aspect)
@@ -5006,8 +5011,9 @@ def pcolor(self, *args, **kwargs):
50065011

50075012
collection.set_alpha(alpha)
50085013
collection.set_array(C)
5009-
if norm is not None:
5010-
assert(isinstance(norm, mcolors.Normalize))
5014+
if norm is not None and not isinstance(norm, mcolors.Normalize):
5015+
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5016+
raise ValueError(msg)
50115017
collection.set_cmap(cmap)
50125018
collection.set_norm(norm)
50135019
collection.set_clim(vmin, vmax)
@@ -5155,8 +5161,9 @@ def pcolormesh(self, *args, **kwargs):
51555161
antialiased=antialiased, shading=shading, **kwargs)
51565162
collection.set_alpha(alpha)
51575163
collection.set_array(C)
5158-
if norm is not None:
5159-
assert(isinstance(norm, mcolors.Normalize))
5164+
if norm is not None and not isinstance(norm, mcolors.Normalize):
5165+
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5166+
raise ValueError(msg)
51605167
collection.set_cmap(cmap)
51615168
collection.set_norm(norm)
51625169
collection.set_clim(vmin, vmax)
@@ -5280,8 +5287,9 @@ def pcolorfast(self, *args, **kwargs):
52805287
cmap = kwargs.pop('cmap', None)
52815288
vmin = kwargs.pop('vmin', None)
52825289
vmax = kwargs.pop('vmax', None)
5283-
if norm is not None:
5284-
assert(isinstance(norm, mcolors.Normalize))
5290+
if norm is not None and not isinstance(norm, mcolors.Normalize):
5291+
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5292+
raise ValueError(msg)
52855293

52865294
C = args[-1]
52875295
nr, nc = C.shape

‎lib/matplotlib/axes/_base.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_base.py
+8-2Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,7 +2111,10 @@ def draw_artist(self, a):
21112111
caches the renderer. It is used to efficiently update Axes
21122112
data (axis ticks, labels, etc are not updated)
21132113
"""
2114-
assert self._cachedRenderer is not None
2114+
if self._cachedRenderer is None:
2115+
msg = ('draw_artist can only be used after an initial draw which'
2116+
' caches the render')
2117+
raise AttributeError(msg)
21152118
a.draw(self._cachedRenderer)
21162119

21172120
def redraw_in_frame(self):
@@ -2120,7 +2123,10 @@ def redraw_in_frame(self):
21202123
caches the renderer. It is used to efficiently update Axes
21212124
data (axis ticks, labels, etc are not updated)
21222125
"""
2123-
assert self._cachedRenderer is not None
2126+
if self._cachedRenderer is None:
2127+
msg = ('redraw_in_frame can only be used after an initial draw'
2128+
' which caches the render')
2129+
raise AttributeError(msg)
21242130
self.draw(self._cachedRenderer, inframe=True)
21252131

21262132
def get_renderer_cache(self):

‎lib/matplotlib/axis.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axis.py
+12-7Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1728,11 +1728,13 @@ def set_label_position(self, position):
17281728
17291729
ACCEPTS: [ 'top' | 'bottom' ]
17301730
"""
1731-
assert position == 'top' or position == 'bottom'
17321731
if position == 'top':
17331732
self.label.set_verticalalignment('baseline')
1734-
else:
1733+
elif position == 'bottom':
17351734
self.label.set_verticalalignment('top')
1735+
else:
1736+
msg = "Position accepts only [ 'top' | 'bottom' ]"
1737+
raise ValueError(msg)
17361738
self.label_position = position
17371739

17381740
def _update_label_position(self, bboxes, bboxes2):
@@ -2042,13 +2044,15 @@ def set_label_position(self, position):
20422044
20432045
ACCEPTS: [ 'left' | 'right' ]
20442046
"""
2045-
assert position == 'left' or position == 'right'
20462047
self.label.set_rotation_mode('anchor')
20472048
self.label.set_horizontalalignment('center')
20482049
if position == 'left':
20492050
self.label.set_verticalalignment('bottom')
2050-
else:
2051+
elif position == 'right':
20512052
self.label.set_verticalalignment('top')
2053+
else:
2054+
msg = "Position accepts only [ 'left' | 'right' ]"
2055+
raise ValueError(msg)
20522056
self.label_position = position
20532057

20542058
def _update_label_position(self, bboxes, bboxes2):
@@ -2101,13 +2105,14 @@ def _update_offset_text_position(self, bboxes, bboxes2):
21012105
)
21022106

21032107
def set_offset_position(self, position):
2104-
assert position == 'left' or position == 'right'
2105-
21062108
x, y = self.offsetText.get_position()
21072109
if position == 'left':
21082110
x = 0
2109-
else:
2111+
elif position == 'right':
21102112
x = 1
2113+
else:
2114+
msg = "Position accepts only [ 'left' | 'right' ]"
2115+
raise ValueError(msg)
21112116

21122117
self.offsetText.set_ha(position)
21132118
self.offsetText.set_position((x, y))

‎lib/matplotlib/backend_bases.py

Copy file name to clipboardExpand all lines: lib/matplotlib/backend_bases.py
+5-1Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -969,7 +969,11 @@ def set_clip_path(self, path):
969969
Set the clip path and transformation. Path should be a
970970
:class:`~matplotlib.transforms.TransformedPath` instance.
971971
"""
972-
assert path is None or isinstance(path, transforms.TransformedPath)
972+
if path is not None and not isinstance(path,
973+
transforms.TransformedPath):
974+
msg = ("Path should be a matplotlib.transforms.TransformedPath"
975+
"instance.")
976+
raise ValueError(msg)
973977
self._clippath = path
974978

975979
def set_dashes(self, dash_offset, dash_list):

‎lib/matplotlib/blocking_input.py

Copy file name to clipboardExpand all lines: lib/matplotlib/blocking_input.py
+13-9Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
from matplotlib.cbook import is_sequence_of_strings
3131
import matplotlib.lines as mlines
3232

33+
import warnings
34+
3335

3436
class BlockingInput(object):
3537
"""
@@ -38,8 +40,8 @@ class BlockingInput(object):
3840
"""
3941
def __init__(self, fig, eventslist=()):
4042
self.fig = fig
41-
assert is_sequence_of_strings(
42-
eventslist), "Requires a sequence of event name strings"
43+
if not is_sequence_of_strings(eventslist):
44+
raise ValueError("Requires a sequence of event name strings")
4345
self.eventslist = eventslist
4446

4547
def on_event(self, event):
@@ -95,7 +97,8 @@ def __call__(self, n=1, timeout=30):
9597
Blocking call to retrieve n events
9698
"""
9799

98-
assert isinstance(n, int), "Requires an integer argument"
100+
if not isinstance(n, int):
101+
raise ValueError("Requires an integer argument")
99102
self.n = n
100103

101104
self.events = []
@@ -146,9 +149,9 @@ def post_event(self):
146149
"""
147150
This will be called to process events
148151
"""
149-
assert len(self.events) > 0, "No events yet"
150-
151-
if self.events[-1].name == 'key_press_event':
152+
if len(self.events) == 0:
153+
warnings.warn("No events yet")
154+
elif self.events[-1].name == 'key_press_event':
152155
self.key_event()
153156
else:
154157
self.mouse_event()
@@ -359,9 +362,10 @@ def post_event(self):
359362
"""
360363
Determines if it is a key event
361364
"""
362-
assert len(self.events) > 0, "No events yet"
363-
364-
self.keyormouse = self.events[-1].name == 'key_press_event'
365+
if len(self.events) == 0:
366+
warnings.warn("No events yet")
367+
else:
368+
self.keyormouse = self.events[-1].name == 'key_press_event'
365369

366370
def __call__(self, timeout=30):
367371
"""

‎lib/matplotlib/contour.py

Copy file name to clipboardExpand all lines: lib/matplotlib/contour.py
+6-4Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -857,10 +857,12 @@ def __init__(self, ax, *args, **kwargs):
857857
else:
858858
self.logscale = False
859859

860-
if self.origin is not None:
861-
assert(self.origin in ['lower', 'upper', 'image'])
862-
if self.extent is not None:
863-
assert(len(self.extent) == 4)
860+
if self.origin not in [None, 'lower', 'upper', 'image']:
861+
raise ValueError("If given, *origin* must be one of [ 'lower' |"
862+
" 'upper' | 'image']")
863+
if self.extent is not None and len(self.extent) != 4:
864+
raise ValueError("If given, *extent* must be '[ *None* |"
865+
" (x0,x1,y0,y1) ]'")
864866
if self.colors is not None and cmap is not None:
865867
raise ValueError('Either colors or cmap must be None')
866868
if self.origin == 'image':

‎lib/matplotlib/figure.py

Copy file name to clipboardExpand all lines: lib/matplotlib/figure.py
+11-3Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -872,7 +872,9 @@ def add_axes(self, *args, **kwargs):
872872

873873
if isinstance(args[0], Axes):
874874
a = args[0]
875-
assert(a.get_figure() is self)
875+
if a.get_figure() is not self:
876+
msg = "The Axes must have been created in the present figure"
877+
raise ValueError(msg)
876878
else:
877879
rect = args[0]
878880
projection_class, kwargs, key = process_projection_requirements(
@@ -946,7 +948,10 @@ def add_subplot(self, *args, **kwargs):
946948
if isinstance(args[0], SubplotBase):
947949

948950
a = args[0]
949-
assert(a.get_figure() is self)
951+
if a.get_figure() is not self:
952+
msg = ("The Subplot must have been created in the present"
953+
" figure")
954+
raise ValueError(msg)
950955
# make a key for the subplot (which includes the axes object id
951956
# in the hash)
952957
key = self._make_key(*args, **kwargs)
@@ -1104,7 +1109,10 @@ def draw_artist(self, a):
11041109
draw :class:`matplotlib.artist.Artist` instance *a* only --
11051110
this is available only after the figure is drawn
11061111
"""
1107-
assert self._cachedRenderer is not None
1112+
if self._cachedRenderer is None:
1113+
msg = ('draw_artist can only be used after an initial draw which'
1114+
' caches the render')
1115+
raise AttributeError(msg)
11081116
a.draw(self._cachedRenderer)
11091117

11101118
def get_axes(self):

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.