Skip to content

Logging and exception messages cleanup. #10096

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 26, 2017
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
8 changes: 4 additions & 4 deletions examples/api/custom_projection_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ def get_xaxis_transform(self, which='grid'):
Returns a tuple of the form (transform, valign, halign)
"""
if which not in ['tick1', 'tick2', 'grid']:
msg = "'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]"
raise ValueError(msg)
raise ValueError(
"'which' must be one of 'tick1', 'tick2', or 'grid'")
return self._xaxis_transform

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

def get_yaxis_text1_transform(self, pad):
Expand Down
41 changes: 20 additions & 21 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1657,10 +1657,10 @@ def param(func):
# all to be replaced arguments are in the list
arg_names = _arg_names[1:]
else:
msg = ("Got unknown 'replace_names' and wrapped function "
"'%s' uses '*args', need "
"'positional_parameter_names'!")
raise AssertionError(msg % func.__name__)
raise AssertionError(
"Got unknown 'replace_names' and wrapped function "
"{!r} uses '*args', need 'positional_parameter_names'"
.format(func.__name__))
else:
if positional_parameter_names is not None:
if callable(positional_parameter_names):
Expand All @@ -1674,11 +1674,10 @@ def param(func):
if replace_all_args:
arg_names = []
else:
msg = ("Got 'replace_names' and wrapped function "
"'%s' uses *args, need "
"'positional_parameter_names' or "
"'replace_all_args'!")
raise AssertionError(msg % func.__name__)
raise AssertionError(
"Got 'replace_names' and wrapped function {!r} "
"uses *args, need 'positional_parameter_names' or "
"'replace_all_args'".format(func.__name__))

# compute the possible label_namer and label position in positional
# arguments
Expand All @@ -1697,13 +1696,13 @@ def param(func):
# which might surprise the user :-(
if label_namer and not arg_names_at_runtime and not _has_varkwargs:
if not arg_names:
msg = ("label_namer '%s' can't be found as the parameter "
"without 'positional_parameter_names'.")
raise AssertionError(msg % label_namer)
raise AssertionError(
"label_namer {!r} can't be found as the parameter without "
"'positional_parameter_names'".format(label_namer))
elif label_namer not in arg_names:
msg = ("label_namer '%s' can't be found in the parameter "
"names (known argnames: %s).")
raise AssertionError(msg % (label_namer, arg_names))
raise AssertionError(
"label_namer {!r} can't be found in the parameter names "
"(known argnames: %s).".format(label_namer, arg_names))
else:
# this is the case when the name is in arg_names
pass
Expand Down Expand Up @@ -1783,12 +1782,12 @@ def inner(ax, *args, **kwargs):
elif label_namer in kwargs:
kwargs['label'] = get_label(kwargs[label_namer], label)
else:
msg = ("Tried to set a label via parameter '%s' in "
"func '%s' but couldn't find such an argument. \n"
"(This is a programming error, please report to "
"the matplotlib list!)")
warnings.warn(msg % (label_namer, func.__name__),
RuntimeWarning, stacklevel=2)
warnings.warn(
"Tried to set a label via parameter %r in func %r but "
"couldn't find such an argument.\n"
"(This is a programming error, please report to "
"the Matplotlib list!)" % (label_namer, func.__name__),
RuntimeWarning, stacklevel=2)
return func(ax, *args, **kwargs)
pre_doc = inner.__doc__
if pre_doc is None:
Expand Down
53 changes: 23 additions & 30 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ def _adjust_frame_size(self):
'from %s x %s to %s x %s', wo, ho, w, h)
else:
w, h = self.fig.get_size_inches()
_log.debug('frame size in pixels is %s x %s' % self.frame_size)
_log.debug('frame size in pixels is %s x %s', *self.frame_size)
return w, h

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

@classmethod
def bin_path(cls):
Expand Down Expand Up @@ -521,9 +519,8 @@ def _frame_sink(self):

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

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

def cleanup(self):
MovieWriter.cleanup(self)

# Delete temporary files
if self.clear_temp:
_log.debug(
'MovieWriter: clearing temporary fnames=%s' %
str(self._temp_names))
_log.debug('MovieWriter: clearing temporary fnames=%s',
self._temp_names)
for fname in self._temp_names:
os.remove(fname)

Expand Down Expand Up @@ -960,13 +955,12 @@ def grab_frame(self, **savefig_kwargs):
imgdata64 = encodebytes(f.getvalue()).decode('ascii')
self._total_bytes += len(imgdata64)
if self._total_bytes >= self._bytes_limit:
_log.warning("Animation size has reached {0._total_bytes} "
"bytes, exceeding the limit of "
"{0._bytes_limit}. If you're sure you want "
"a larger animation embedded, set the "
"animation.embed_limit rc parameter to a "
"larger value (in MB). This and further frames"
" will be dropped.".format(self))
_log.warning(
"Animation size has reached %s bytes, exceeding the limit "
"of %s. If you're sure you want a larger animation "
"embedded, set the animation.embed_limit rc parameter to "
"a larger value (in MB). This and further frames will be "
"dropped.", self._total_bytes, self._bytes_limit)
self._hit_limit = True
else:
self._saved_frames.append(imgdata64)
Expand Down Expand Up @@ -1211,16 +1205,16 @@ class to use, such as 'ffmpeg' or 'mencoder'. If ``None``,
extra_args=extra_args,
metadata=metadata)
else:
_log.warning("MovieWriter %s unavailable" % writer)
_log.warning("MovieWriter %s unavailable.", writer)

try:
writer = writers[writers.list()[0]](fps, codec, bitrate,
extra_args=extra_args,
metadata=metadata)
except IndexError:
raise ValueError("Cannot save animation: no writers are "
"available. Please install "
"ffmpeg to save animations.")
"available. Please install ffmpeg to "
"save animations.")
_log.info('Animation.save using %s', type(writer))

if 'bbox_inches' in savefig_kwargs:
Expand Down Expand Up @@ -1410,12 +1404,11 @@ def to_html5_video(self, embed_limit=None):
vid64 = encodebytes(video.read())
vid_len = len(vid64)
if vid_len >= embed_limit:
_log.warning("Animation movie is {} bytes, exceeding "
"the limit of {}. If you're sure you want a "
"large animation embedded, set the "
"animation.embed_limit rc parameter to a "
"larger value (in MB).".format(vid_len,
embed_limit))
_log.warning(
"Animation movie is %s bytes, exceeding the limit of "
"%s. If you're sure you want a large animation "
"embedded, set the animation.embed_limit rc parameter "
"to a larger value (in MB).", vid_len, embed_limit)
else:
self._base64_video = vid64.decode('ascii')
self._video_size = 'width="{}" height="{}"'.format(
Expand Down
50 changes: 21 additions & 29 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ def _plot_args_replacer(args, data):
except ValueError:
pass
else:
msg = "Second argument '{}' is ambiguous: could be a color spec " \
"but is in data. Using as data.\nEither rename the " \
"entry in data or use three arguments " \
"to plot.".format(args[1])
warnings.warn(msg, RuntimeWarning, stacklevel=3)
warnings.warn(
"Second argument {!r} is ambiguous: could be a color spec but "
"is in data; using as data. Either rename the entry in data "
"or use three arguments to plot.".format(args[1]),
RuntimeWarning, stacklevel=3)
return ["x", "y"]
elif len(args) == 3:
return ["x", "y", "c"]
Expand Down Expand Up @@ -2857,13 +2857,6 @@ def errorbar(self, x, y, yerr=None, xerr=None,
holdstate = self._hold
self._hold = True

if fmt is None:
fmt = 'none'
msg = ('Use of None object as fmt keyword argument to ' +
'suppress plotting of data values is deprecated ' +
'since 1.4; use the string "none" instead.')
warnings.warn(msg, mplDeprecation, stacklevel=1)

plot_line = (fmt.lower() != 'none')
label = kwargs.pop("label", None)

Expand Down Expand Up @@ -3398,8 +3391,7 @@ def _update_dict(dictionary, rc_name, properties):
if usermedians is not None:
if (len(np.ravel(usermedians)) != len(bxpstats) or
np.shape(usermedians)[0] != len(bxpstats)):
medmsg = 'usermedians length not compatible with x'
raise ValueError(medmsg)
raise ValueError('usermedians length not compatible with x')
else:
# reassign medians as necessary
for stats, med in zip(bxpstats, usermedians):
Expand Down Expand Up @@ -4039,9 +4031,9 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
colors = mcolors.to_rgba_array(c)
except ValueError:
# c not acceptable as PathCollection facecolor
msg = ("c of shape {0} not acceptable as a color sequence "
"for x with size {1}, y with size {2}")
raise ValueError(msg.format(c.shape, x.size, y.size))
raise ValueError("c of shape {} not acceptable as a color "
"sequence for x with size {}, y with size {}"
.format(c.shape, x.size, y.size))
else:
colors = None # use cmap, norm after collection is created

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

if colors is None:
if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_array(np.asarray(c))
collection.set_cmap(cmap)
collection.set_norm(norm)
Expand Down Expand Up @@ -4448,8 +4440,8 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None,
accum = bins.searchsorted(accum)

if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_array(accum)
collection.set_cmap(cmap)
collection.set_norm(norm)
Expand Down Expand Up @@ -5191,8 +5183,8 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
self.cla()

if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)
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 @@ -5514,8 +5506,8 @@ def pcolor(self, *args, **kwargs):
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)
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 @@ -5663,8 +5655,8 @@ def pcolormesh(self, *args, **kwargs):
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)
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 @@ -5787,8 +5779,8 @@ def pcolorfast(self, *args, **kwargs):
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
if norm is not None and not isinstance(norm, mcolors.Normalize):
msg = "'norm' must be an instance of 'mcolors.Normalize'"
raise ValueError(msg)
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")

C = args[-1]
nr, nc = C.shape
Expand Down
10 changes: 4 additions & 6 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2578,9 +2578,8 @@ def draw_artist(self, a):
data (axis ticks, labels, etc are not updated)
"""
if self._cachedRenderer is None:
msg = ('draw_artist can only be used after an initial draw which'
' caches the render')
raise AttributeError(msg)
raise AttributeError("draw_artist can only be used after an "
"initial draw which caches the renderer")
a.draw(self._cachedRenderer)

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

def get_renderer_cache(self):
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1827,8 +1827,7 @@ def set_label_position(self, position):
elif position == 'bottom':
self.label.set_verticalalignment('top')
else:
msg = "Position accepts only [ 'top' | 'bottom' ]"
raise ValueError(msg)
raise ValueError("Position accepts only 'top' or 'bottom'")
self.label_position = position
self.stale = True

Expand Down Expand Up @@ -2173,8 +2172,7 @@ def set_label_position(self, position):
elif position == 'right':
self.label.set_verticalalignment('top')
else:
msg = "Position accepts only [ 'left' | 'right' ]"
raise ValueError(msg)
raise ValueError("Position accepts only 'left' or 'right'")
self.label_position = position
self.stale = True

Expand Down
9 changes: 4 additions & 5 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,11 +1057,10 @@ def set_clip_path(self, path):
Set the clip path and transformation. Path should be a
:class:`~matplotlib.transforms.TransformedPath` instance.
"""
if path is not None and not isinstance(path,
transforms.TransformedPath):
msg = ("Path should be a matplotlib.transforms.TransformedPath"
"instance.")
raise ValueError(msg)
if (path is not None
and not isinstance(path, transforms.TransformedPath)):
raise ValueError("Path should be a "
"matplotlib.transforms.TransformedPath instance")
self._clippath = path

def set_dashes(self, dash_offset, dash_list):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_gtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -1012,7 +1012,7 @@ def error_msg_gtk(msg, parent=None):
parent = None

if not isinstance(msg, six.string_types):
msg = ','.join(map(str,msg))
msg = ','.join(map(str, msg))

dialog = gtk.MessageDialog(
parent = parent,
Expand Down
Loading
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