Skip to content

Commit 944a9e5

Browse files
committed
Logging and exception messages cleanup.
- `log.warning(msg % args)` => `log.warning(msg, *args)` - `msg = ...; raise ValueError(msg)` => `raise ValueError(...)`
1 parent f96fac0 commit 944a9e5

34 files changed

+232
-296
lines changed

examples/api/custom_projection_example.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,8 @@ def get_xaxis_transform(self, which='grid'):
192192
Returns a tuple of the form (transform, valign, halign)
193193
"""
194194
if which not in ['tick1', 'tick2', 'grid']:
195-
msg = "'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]"
196-
raise ValueError(msg)
195+
raise ValueError(
196+
"'which' must be one of 'tick1', 'tick2', or 'grid'")
197197
return self._xaxis_transform
198198

199199
def get_xaxis_text1_transform(self, pad):
@@ -214,8 +214,8 @@ def get_yaxis_transform(self, which='grid'):
214214
y-axis grid and ticks.
215215
"""
216216
if which not in ['tick1', 'tick2', 'grid']:
217-
msg = "'which' must be one of [ 'tick1' | 'tick2' | 'grid' ]"
218-
raise ValueError(msg)
217+
raise ValueError(
218+
"'which' must be one of 'tick1', 'tick2', or 'grid'")
219219
return self._yaxis_transform
220220

221221
def get_yaxis_text1_transform(self, pad):

lib/matplotlib/__init__.py

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1657,10 +1657,10 @@ def param(func):
16571657
# all to be replaced arguments are in the list
16581658
arg_names = _arg_names[1:]
16591659
else:
1660-
msg = ("Got unknown 'replace_names' and wrapped function "
1661-
"'%s' uses '*args', need "
1662-
"'positional_parameter_names'!")
1663-
raise AssertionError(msg % func.__name__)
1660+
raise AssertionError(
1661+
"Got unknown 'replace_names' and wrapped function "
1662+
"{!r} uses '*args', need 'positional_parameter_names'"
1663+
.format(func.__name__))
16641664
else:
16651665
if positional_parameter_names is not None:
16661666
if callable(positional_parameter_names):
@@ -1674,11 +1674,10 @@ def param(func):
16741674
if replace_all_args:
16751675
arg_names = []
16761676
else:
1677-
msg = ("Got 'replace_names' and wrapped function "
1678-
"'%s' uses *args, need "
1679-
"'positional_parameter_names' or "
1680-
"'replace_all_args'!")
1681-
raise AssertionError(msg % func.__name__)
1677+
raise AssertionError(
1678+
"Got 'replace_names' and wrapped function {!r} "
1679+
"uses *args, need 'positional_parameter_names' or "
1680+
"'replace_all_args'".format(func.__name__))
16821681

16831682
# compute the possible label_namer and label position in positional
16841683
# arguments
@@ -1697,13 +1696,13 @@ def param(func):
16971696
# which might surprise the user :-(
16981697
if label_namer and not arg_names_at_runtime and not _has_varkwargs:
16991698
if not arg_names:
1700-
msg = ("label_namer '%s' can't be found as the parameter "
1701-
"without 'positional_parameter_names'.")
1702-
raise AssertionError(msg % label_namer)
1699+
raise AssertionError(
1700+
"label_namer {!r} can't be found as the parameter without "
1701+
"'positional_parameter_names'".format(label_namer))
17031702
elif label_namer not in arg_names:
1704-
msg = ("label_namer '%s' can't be found in the parameter "
1705-
"names (known argnames: %s).")
1706-
raise AssertionError(msg % (label_namer, arg_names))
1703+
raise AssertionError(
1704+
"label_namer {!r} can't be found in the parameter names "
1705+
"(known argnames: %s).".format(label_namer, arg_names))
17071706
else:
17081707
# this is the case when the name is in arg_names
17091708
pass
@@ -1783,12 +1782,12 @@ def inner(ax, *args, **kwargs):
17831782
elif label_namer in kwargs:
17841783
kwargs['label'] = get_label(kwargs[label_namer], label)
17851784
else:
1786-
msg = ("Tried to set a label via parameter '%s' in "
1787-
"func '%s' but couldn't find such an argument. \n"
1788-
"(This is a programming error, please report to "
1789-
"the matplotlib list!)")
1790-
warnings.warn(msg % (label_namer, func.__name__),
1791-
RuntimeWarning, stacklevel=2)
1785+
warnings.warn(
1786+
"Tried to set a label via parameter %r in func %r but "
1787+
"couldn't find such an argument.\n"
1788+
"(This is a programming error, please report to "
1789+
"the Matplotlib list!)" % (label_namer, func.__name__),
1790+
RuntimeWarning, stacklevel=2)
17921791
return func(ax, *args, **kwargs)
17931792
pre_doc = inner.__doc__
17941793
if pre_doc is None:

lib/matplotlib/animation.py

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ def _adjust_frame_size(self):
326326
'from %s x %s to %s x %s', wo, ho, w, h)
327327
else:
328328
w, h = self.fig.get_size_inches()
329-
_log.debug('frame size in pixels is %s x %s' % self.frame_size)
329+
_log.debug('frame size in pixels is %s x %s', *self.frame_size)
330330
return w, h
331331

332332
def setup(self, fig, outfile, dpi=None):
@@ -409,10 +409,8 @@ def cleanup(self):
409409
'''Clean-up and collect the process used to write the movie file.'''
410410
out, err = self._proc.communicate()
411411
self._frame_sink().close()
412-
_log.debug('MovieWriter -- '
413-
'Command stdout:\n%s' % out)
414-
_log.debug('MovieWriter -- '
415-
'Command stderr:\n%s' % err)
412+
_log.debug('MovieWriter -- Command stdout:\n%s', out)
413+
_log.debug('MovieWriter -- Command stderr:\n%s', err)
416414

417415
@classmethod
418416
def bin_path(cls):
@@ -521,9 +519,8 @@ def _frame_sink(self):
521519

522520
# Save the filename so we can delete it later if necessary
523521
self._temp_names.append(fname)
524-
_log.debug(
525-
'FileMovieWriter.frame_sink: saving frame %d to fname=%s' %
526-
(self._frame_counter, fname))
522+
_log.debug('FileMovieWriter.frame_sink: saving frame %d to fname=%s',
523+
self._frame_counter, fname)
527524
self._frame_counter += 1 # Ensures each created name is 'unique'
528525

529526
# This file returned here will be closed once it's used by savefig()
@@ -567,18 +564,16 @@ def finish(self):
567564
_log.info("MovieWriter.finish: stderr: %s", stderr)
568565
except Exception as e:
569566
pass
570-
msg = ('Error creating movie, return code: ' +
571-
str(self._proc.returncode))
572-
raise RuntimeError(msg)
567+
raise RuntimeError('Error creating movie, return code: {}'
568+
.format(self._proc.returncode))
573569

574570
def cleanup(self):
575571
MovieWriter.cleanup(self)
576572

577573
# Delete temporary files
578574
if self.clear_temp:
579-
_log.debug(
580-
'MovieWriter: clearing temporary fnames=%s' %
581-
str(self._temp_names))
575+
_log.debug('MovieWriter: clearing temporary fnames=%s',
576+
self._temp_names)
582577
for fname in self._temp_names:
583578
os.remove(fname)
584579

@@ -960,13 +955,12 @@ def grab_frame(self, **savefig_kwargs):
960955
imgdata64 = encodebytes(f.getvalue()).decode('ascii')
961956
self._total_bytes += len(imgdata64)
962957
if self._total_bytes >= self._bytes_limit:
963-
_log.warning("Animation size has reached {0._total_bytes} "
964-
"bytes, exceeding the limit of "
965-
"{0._bytes_limit}. If you're sure you want "
966-
"a larger animation embedded, set the "
967-
"animation.embed_limit rc parameter to a "
968-
"larger value (in MB). This and further frames"
969-
" will be dropped.".format(self))
958+
_log.warning(
959+
"Animation size has reached %s bytes, exceeding the limit "
960+
"of %s. If you're sure you want a larger animation "
961+
"embedded, set the animation.embed_limit rc parameter to "
962+
"a larger value (in MB). This and further frames will be "
963+
"dropped.", self._total_bytes, self._bytes_limit)
970964
self._hit_limit = True
971965
else:
972966
self._saved_frames.append(imgdata64)
@@ -1211,16 +1205,16 @@ class to use, such as 'ffmpeg' or 'mencoder'. If ``None``,
12111205
extra_args=extra_args,
12121206
metadata=metadata)
12131207
else:
1214-
_log.warning("MovieWriter %s unavailable" % writer)
1208+
_log.warning("MovieWriter %s unavailable.", writer)
12151209

12161210
try:
12171211
writer = writers[writers.list()[0]](fps, codec, bitrate,
12181212
extra_args=extra_args,
12191213
metadata=metadata)
12201214
except IndexError:
12211215
raise ValueError("Cannot save animation: no writers are "
1222-
"available. Please install "
1223-
"ffmpeg to save animations.")
1216+
"available. Please install ffmpeg to "
1217+
"save animations.")
12241218
_log.info('Animation.save using %s', type(writer))
12251219

12261220
if 'bbox_inches' in savefig_kwargs:
@@ -1410,12 +1404,11 @@ def to_html5_video(self, embed_limit=None):
14101404
vid64 = encodebytes(video.read())
14111405
vid_len = len(vid64)
14121406
if vid_len >= embed_limit:
1413-
_log.warning("Animation movie is {} bytes, exceeding "
1414-
"the limit of {}. If you're sure you want a "
1415-
"large animation embedded, set the "
1416-
"animation.embed_limit rc parameter to a "
1417-
"larger value (in MB).".format(vid_len,
1418-
embed_limit))
1407+
_log.warning(
1408+
"Animation movie is %s bytes, exceeding the limit of "
1409+
"%s. If you're sure you want a large animation "
1410+
"embedded, set the animation.embed_limit rc parameter "
1411+
"to a larger value (in MB).", vid_len, embed_limit)
14191412
else:
14201413
self._base64_video = vid64.decode('ascii')
14211414
self._video_size = 'width="{}" height="{}"'.format(

lib/matplotlib/axes/_axes.py

Lines changed: 21 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,11 @@ def _plot_args_replacer(args, data):
7575
except ValueError:
7676
pass
7777
else:
78-
msg = "Second argument '{}' is ambiguous: could be a color spec " \
79-
"but is in data. Using as data.\nEither rename the " \
80-
"entry in data or use three arguments " \
81-
"to plot.".format(args[1])
82-
warnings.warn(msg, RuntimeWarning, stacklevel=3)
78+
warnings.warn(
79+
"Second argument {!r} is ambiguous: could be a color spec but "
80+
"is in data; using as data. Either rename the entry in data "
81+
"or use three arguments to plot.".format(args[1]),
82+
RuntimeWarning, stacklevel=3)
8383
return ["x", "y"]
8484
elif len(args) == 3:
8585
return ["x", "y", "c"]
@@ -2857,13 +2857,6 @@ def errorbar(self, x, y, yerr=None, xerr=None,
28572857
holdstate = self._hold
28582858
self._hold = True
28592859

2860-
if fmt is None:
2861-
fmt = 'none'
2862-
msg = ('Use of None object as fmt keyword argument to ' +
2863-
'suppress plotting of data values is deprecated ' +
2864-
'since 1.4; use the string "none" instead.')
2865-
warnings.warn(msg, mplDeprecation, stacklevel=1)
2866-
28672860
plot_line = (fmt.lower() != 'none')
28682861
label = kwargs.pop("label", None)
28692862

@@ -3398,8 +3391,7 @@ def _update_dict(dictionary, rc_name, properties):
33983391
if usermedians is not None:
33993392
if (len(np.ravel(usermedians)) != len(bxpstats) or
34003393
np.shape(usermedians)[0] != len(bxpstats)):
3401-
medmsg = 'usermedians length not compatible with x'
3402-
raise ValueError(medmsg)
3394+
raise ValueError('usermedians length not compatible with x')
34033395
else:
34043396
# reassign medians as necessary
34053397
for stats, med in zip(bxpstats, usermedians):
@@ -4039,9 +4031,9 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
40394031
colors = mcolors.to_rgba_array(c)
40404032
except ValueError:
40414033
# c not acceptable as PathCollection facecolor
4042-
msg = ("c of shape {0} not acceptable as a color sequence "
4043-
"for x with size {1}, y with size {2}")
4044-
raise ValueError(msg.format(c.shape, x.size, y.size))
4034+
raise ValueError("c of shape {} not acceptable as a color "
4035+
"sequence for x with size {}, y with size {}"
4036+
.format(c.shape, x.size, y.size))
40454037
else:
40464038
colors = None # use cmap, norm after collection is created
40474039

@@ -4089,8 +4081,8 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
40894081

40904082
if colors is None:
40914083
if norm is not None and not isinstance(norm, mcolors.Normalize):
4092-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
4093-
raise ValueError(msg)
4084+
raise ValueError(
4085+
"'norm' must be an instance of 'mcolors.Normalize'")
40944086
collection.set_array(np.asarray(c))
40954087
collection.set_cmap(cmap)
40964088
collection.set_norm(norm)
@@ -4448,8 +4440,8 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None,
44484440
accum = bins.searchsorted(accum)
44494441

44504442
if norm is not None and not isinstance(norm, mcolors.Normalize):
4451-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
4452-
raise ValueError(msg)
4443+
raise ValueError(
4444+
"'norm' must be an instance of 'mcolors.Normalize'")
44534445
collection.set_array(accum)
44544446
collection.set_cmap(cmap)
44554447
collection.set_norm(norm)
@@ -5191,8 +5183,8 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
51915183
self.cla()
51925184

51935185
if norm is not None and not isinstance(norm, mcolors.Normalize):
5194-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5195-
raise ValueError(msg)
5186+
raise ValueError(
5187+
"'norm' must be an instance of 'mcolors.Normalize'")
51965188
if aspect is None:
51975189
aspect = rcParams['image.aspect']
51985190
self.set_aspect(aspect)
@@ -5514,8 +5506,8 @@ def pcolor(self, *args, **kwargs):
55145506
collection.set_alpha(alpha)
55155507
collection.set_array(C)
55165508
if norm is not None and not isinstance(norm, mcolors.Normalize):
5517-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5518-
raise ValueError(msg)
5509+
raise ValueError(
5510+
"'norm' must be an instance of 'mcolors.Normalize'")
55195511
collection.set_cmap(cmap)
55205512
collection.set_norm(norm)
55215513
collection.set_clim(vmin, vmax)
@@ -5663,8 +5655,8 @@ def pcolormesh(self, *args, **kwargs):
56635655
collection.set_alpha(alpha)
56645656
collection.set_array(C)
56655657
if norm is not None and not isinstance(norm, mcolors.Normalize):
5666-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5667-
raise ValueError(msg)
5658+
raise ValueError(
5659+
"'norm' must be an instance of 'mcolors.Normalize'")
56685660
collection.set_cmap(cmap)
56695661
collection.set_norm(norm)
56705662
collection.set_clim(vmin, vmax)
@@ -5787,8 +5779,8 @@ def pcolorfast(self, *args, **kwargs):
57875779
vmin = kwargs.pop('vmin', None)
57885780
vmax = kwargs.pop('vmax', None)
57895781
if norm is not None and not isinstance(norm, mcolors.Normalize):
5790-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5791-
raise ValueError(msg)
5782+
raise ValueError(
5783+
"'norm' must be an instance of 'mcolors.Normalize'")
57925784

57935785
C = args[-1]
57945786
nr, nc = C.shape

lib/matplotlib/axes/_base.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2578,9 +2578,8 @@ def draw_artist(self, a):
25782578
data (axis ticks, labels, etc are not updated)
25792579
"""
25802580
if self._cachedRenderer is None:
2581-
msg = ('draw_artist can only be used after an initial draw which'
2582-
' caches the render')
2583-
raise AttributeError(msg)
2581+
raise AttributeError("draw_artist can only be used after an "
2582+
"initial draw which caches the renderer")
25842583
a.draw(self._cachedRenderer)
25852584

25862585
def redraw_in_frame(self):
@@ -2590,9 +2589,8 @@ def redraw_in_frame(self):
25902589
data (axis ticks, labels, etc are not updated)
25912590
"""
25922591
if self._cachedRenderer is None:
2593-
msg = ('redraw_in_frame can only be used after an initial draw'
2594-
' which caches the render')
2595-
raise AttributeError(msg)
2592+
raise AttributeError("redraw_in_frame can only be used after an "
2593+
"initial draw which caches the renderer")
25962594
self.draw(self._cachedRenderer, inframe=True)
25972595

25982596
def get_renderer_cache(self):

lib/matplotlib/axis.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1827,8 +1827,7 @@ def set_label_position(self, position):
18271827
elif position == 'bottom':
18281828
self.label.set_verticalalignment('top')
18291829
else:
1830-
msg = "Position accepts only [ 'top' | 'bottom' ]"
1831-
raise ValueError(msg)
1830+
raise ValueError("Position accepts only 'top' or 'bottom'")
18321831
self.label_position = position
18331832
self.stale = True
18341833

@@ -2173,8 +2172,7 @@ def set_label_position(self, position):
21732172
elif position == 'right':
21742173
self.label.set_verticalalignment('top')
21752174
else:
2176-
msg = "Position accepts only [ 'left' | 'right' ]"
2177-
raise ValueError(msg)
2175+
raise ValueError("Position accepts only 'left' or 'right'")
21782176
self.label_position = position
21792177
self.stale = True
21802178

lib/matplotlib/backend_bases.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1057,11 +1057,10 @@ def set_clip_path(self, path):
10571057
Set the clip path and transformation. Path should be a
10581058
:class:`~matplotlib.transforms.TransformedPath` instance.
10591059
"""
1060-
if path is not None and not isinstance(path,
1061-
transforms.TransformedPath):
1062-
msg = ("Path should be a matplotlib.transforms.TransformedPath"
1063-
"instance.")
1064-
raise ValueError(msg)
1060+
if (path is not None
1061+
and not isinstance(path, transforms.TransformedPath)):
1062+
raise ValueError("Path should be a "
1063+
"matplotlib.transforms.TransformedPath instance")
10651064
self._clippath = path
10661065

10671066
def set_dashes(self, dash_offset, dash_list):

lib/matplotlib/backends/backend_gtk.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1012,7 +1012,7 @@ def error_msg_gtk(msg, parent=None):
10121012
parent = None
10131013

10141014
if not isinstance(msg, six.string_types):
1015-
msg = ','.join(map(str,msg))
1015+
msg = ','.join(map(str, msg))
10161016

10171017
dialog = gtk.MessageDialog(
10181018
parent = parent,

0 commit comments

Comments
 (0)