Skip to content

Commit a8ae66e

Browse files
authored
Merge pull request #10096 from anntzer/logging-exception-cleanups
Logging and exception messages cleanup.
2 parents 96074c7 + 944a9e5 commit a8ae66e

34 files changed

+232
-289
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

@@ -881,13 +876,12 @@ def grab_frame(self, **savefig_kwargs):
881876
imgdata64 = encodebytes(f.getvalue()).decode('ascii')
882877
self._total_bytes += len(imgdata64)
883878
if self._total_bytes >= self._bytes_limit:
884-
_log.warning("Animation size has reached {0._total_bytes} "
885-
"bytes, exceeding the limit of "
886-
"{0._bytes_limit}. If you're sure you want "
887-
"a larger animation embedded, set the "
888-
"animation.embed_limit rc parameter to a "
889-
"larger value (in MB). This and further frames"
890-
" will be dropped.".format(self))
879+
_log.warning(
880+
"Animation size has reached %s bytes, exceeding the limit "
881+
"of %s. If you're sure you want a larger animation "
882+
"embedded, set the animation.embed_limit rc parameter to "
883+
"a larger value (in MB). This and further frames will be "
884+
"dropped.", self._total_bytes, self._bytes_limit)
891885
self._hit_limit = True
892886
else:
893887
self._saved_frames.append(imgdata64)
@@ -1132,16 +1126,16 @@ class to use, such as 'ffmpeg'. If ``None``, defaults to
11321126
extra_args=extra_args,
11331127
metadata=metadata)
11341128
else:
1135-
_log.warning("MovieWriter %s unavailable" % writer)
1129+
_log.warning("MovieWriter %s unavailable.", writer)
11361130

11371131
try:
11381132
writer = writers[writers.list()[0]](fps, codec, bitrate,
11391133
extra_args=extra_args,
11401134
metadata=metadata)
11411135
except IndexError:
11421136
raise ValueError("Cannot save animation: no writers are "
1143-
"available. Please install "
1144-
"ffmpeg to save animations.")
1137+
"available. Please install ffmpeg to "
1138+
"save animations.")
11451139
_log.info('Animation.save using %s', type(writer))
11461140

11471141
if 'bbox_inches' in savefig_kwargs:
@@ -1331,12 +1325,11 @@ def to_html5_video(self, embed_limit=None):
13311325
vid64 = encodebytes(video.read())
13321326
vid_len = len(vid64)
13331327
if vid_len >= embed_limit:
1334-
_log.warning("Animation movie is {} bytes, exceeding "
1335-
"the limit of {}. If you're sure you want a "
1336-
"large animation embedded, set the "
1337-
"animation.embed_limit rc parameter to a "
1338-
"larger value (in MB).".format(vid_len,
1339-
embed_limit))
1328+
_log.warning(
1329+
"Animation movie is %s bytes, exceeding the limit of "
1330+
"%s. If you're sure you want a large animation "
1331+
"embedded, set the animation.embed_limit rc parameter "
1332+
"to a larger value (in MB).", vid_len, embed_limit)
13401333
else:
13411334
self._base64_video = vid64.decode('ascii')
13421335
self._video_size = 'width="{}" height="{}"'.format(

lib/matplotlib/axes/_axes.py

Lines changed: 21 additions & 22 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"]
@@ -3391,8 +3391,7 @@ def _update_dict(dictionary, rc_name, properties):
33913391
if usermedians is not None:
33923392
if (len(np.ravel(usermedians)) != len(bxpstats) or
33933393
np.shape(usermedians)[0] != len(bxpstats)):
3394-
medmsg = 'usermedians length not compatible with x'
3395-
raise ValueError(medmsg)
3394+
raise ValueError('usermedians length not compatible with x')
33963395
else:
33973396
# reassign medians as necessary
33983397
for stats, med in zip(bxpstats, usermedians):
@@ -4032,9 +4031,9 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
40324031
colors = mcolors.to_rgba_array(c)
40334032
except ValueError:
40344033
# c not acceptable as PathCollection facecolor
4035-
msg = ("c of shape {0} not acceptable as a color sequence "
4036-
"for x with size {1}, y with size {2}")
4037-
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))
40384037
else:
40394038
colors = None # use cmap, norm after collection is created
40404039

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

40834082
if colors is None:
40844083
if norm is not None and not isinstance(norm, mcolors.Normalize):
4085-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
4086-
raise ValueError(msg)
4084+
raise ValueError(
4085+
"'norm' must be an instance of 'mcolors.Normalize'")
40874086
collection.set_array(np.asarray(c))
40884087
collection.set_cmap(cmap)
40894088
collection.set_norm(norm)
@@ -4441,8 +4440,8 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None,
44414440
accum = bins.searchsorted(accum)
44424441

44434442
if norm is not None and not isinstance(norm, mcolors.Normalize):
4444-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
4445-
raise ValueError(msg)
4443+
raise ValueError(
4444+
"'norm' must be an instance of 'mcolors.Normalize'")
44464445
collection.set_array(accum)
44474446
collection.set_cmap(cmap)
44484447
collection.set_norm(norm)
@@ -5184,8 +5183,8 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
51845183
self.cla()
51855184

51865185
if norm is not None and not isinstance(norm, mcolors.Normalize):
5187-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5188-
raise ValueError(msg)
5186+
raise ValueError(
5187+
"'norm' must be an instance of 'mcolors.Normalize'")
51895188
if aspect is None:
51905189
aspect = rcParams['image.aspect']
51915190
self.set_aspect(aspect)
@@ -5507,8 +5506,8 @@ def pcolor(self, *args, **kwargs):
55075506
collection.set_alpha(alpha)
55085507
collection.set_array(C)
55095508
if norm is not None and not isinstance(norm, mcolors.Normalize):
5510-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5511-
raise ValueError(msg)
5509+
raise ValueError(
5510+
"'norm' must be an instance of 'mcolors.Normalize'")
55125511
collection.set_cmap(cmap)
55135512
collection.set_norm(norm)
55145513
collection.set_clim(vmin, vmax)
@@ -5656,8 +5655,8 @@ def pcolormesh(self, *args, **kwargs):
56565655
collection.set_alpha(alpha)
56575656
collection.set_array(C)
56585657
if norm is not None and not isinstance(norm, mcolors.Normalize):
5659-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5660-
raise ValueError(msg)
5658+
raise ValueError(
5659+
"'norm' must be an instance of 'mcolors.Normalize'")
56615660
collection.set_cmap(cmap)
56625661
collection.set_norm(norm)
56635662
collection.set_clim(vmin, vmax)
@@ -5780,8 +5779,8 @@ def pcolorfast(self, *args, **kwargs):
57805779
vmin = kwargs.pop('vmin', None)
57815780
vmax = kwargs.pop('vmax', None)
57825781
if norm is not None and not isinstance(norm, mcolors.Normalize):
5783-
msg = "'norm' must be an instance of 'mcolors.Normalize'"
5784-
raise ValueError(msg)
5782+
raise ValueError(
5783+
"'norm' must be an instance of 'mcolors.Normalize'")
57855784

57865785
C = args[-1]
57875786
nr, nc = C.shape

lib/matplotlib/axes/_base.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2555,9 +2555,8 @@ def draw_artist(self, a):
25552555
data (axis ticks, labels, etc are not updated)
25562556
"""
25572557
if self._cachedRenderer is None:
2558-
msg = ('draw_artist can only be used after an initial draw which'
2559-
' caches the render')
2560-
raise AttributeError(msg)
2558+
raise AttributeError("draw_artist can only be used after an "
2559+
"initial draw which caches the renderer")
25612560
a.draw(self._cachedRenderer)
25622561

25632562
def redraw_in_frame(self):
@@ -2567,9 +2566,8 @@ def redraw_in_frame(self):
25672566
data (axis ticks, labels, etc are not updated)
25682567
"""
25692568
if self._cachedRenderer is None:
2570-
msg = ('redraw_in_frame can only be used after an initial draw'
2571-
' which caches the render')
2572-
raise AttributeError(msg)
2569+
raise AttributeError("redraw_in_frame can only be used after an "
2570+
"initial draw which caches the renderer")
25732571
self.draw(self._cachedRenderer, inframe=True)
25742572

25752573
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy