diff --git a/examples/api/custom_projection_example.py b/examples/api/custom_projection_example.py index 0277ec2019a2..c446120bb89d 100644 --- a/examples/api/custom_projection_example.py +++ b/examples/api/custom_projection_example.py @@ -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): @@ -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): diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index ceba78400b23..6e4e10c871fa 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -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): @@ -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 @@ -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 @@ -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: diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index ddd337dccd84..581227f5bb28 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -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): @@ -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): @@ -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() @@ -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) @@ -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) @@ -1211,7 +1205,7 @@ 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, @@ -1219,8 +1213,8 @@ class to use, such as 'ffmpeg' or 'mencoder'. If ``None``, 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: @@ -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( diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index f83663273c64..b7df8f4cc31e 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -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"] @@ -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) @@ -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): @@ -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 @@ -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) @@ -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) @@ -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) @@ -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) @@ -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) @@ -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 diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index d08f2cdf0907..5d4eb223d545 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -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): @@ -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): diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 948e3ae1386f..e72df192bfb2 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -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 @@ -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 diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index cfd98db38f4d..4a67df8ac492 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -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): diff --git a/lib/matplotlib/backends/backend_gtk.py b/lib/matplotlib/backends/backend_gtk.py index ba62b1c4e208..0ffe6ec01f3e 100644 --- a/lib/matplotlib/backends/backend_gtk.py +++ b/lib/matplotlib/backends/backend_gtk.py @@ -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, diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index f84b3d539afd..85de1d016b59 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -229,8 +229,8 @@ def pdfRepr(obj): return fill([pdfRepr(val) for val in obj.bounds]) else: - msg = "Don't know a PDF representation for %s objects." % type(obj) - raise TypeError(msg) + raise TypeError("Don't know a PDF representation for {} objects" + .format(type(obj))) class Reference(object): @@ -661,7 +661,7 @@ def fontName(self, fontprop): Fx = Name('F%d' % self.nextFont) self.fontNames[filename] = Fx self.nextFont += 1 - _log.debug('Assigning font %s = %r' % (Fx, filename)) + _log.debug('Assigning font %s = %r', Fx, filename) return Fx @@ -695,8 +695,7 @@ def dviFontName(self, dvifont): pdfname = Name('F%d' % self.nextFont) self.nextFont += 1 - _log.debug('Assigning font {0} = {1} (dvi)'.format(pdfname, - dvifont.texname)) + _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname) self.dviFontInfo[dvifont.texname] = Bunch( dvifont=dvifont, pdfname=pdfname, @@ -710,18 +709,18 @@ def writeFonts(self): fonts = {} for dviname, info in sorted(self.dviFontInfo.items()): Fx = info.pdfname - _log.debug('Embedding Type-1 font %s from dvi' % dviname) + _log.debug('Embedding Type-1 font %s from dvi.', dviname) fonts[Fx] = self._embedTeXFont(info) for filename in sorted(self.fontNames): Fx = self.fontNames[filename] - _log.debug('Embedding font %s' % filename) + _log.debug('Embedding font %s.', filename) if filename.endswith('.afm'): # from pdf.use14corefonts - _log.debug('Writing AFM font') + _log.debug('Writing AFM font.') fonts[Fx] = self._write_afm_font(filename) else: # a normal TrueType font - _log.debug('Writing TrueType font') + _log.debug('Writing TrueType font.') realpath, stat_key = get_realpath_and_stat(filename) chars = self.used_characters.get(stat_key) if chars is not None and len(chars[1]): @@ -741,9 +740,8 @@ def _write_afm_font(self, filename): return fontdictObject def _embedTeXFont(self, fontinfo): - msg = ('Embedding TeX font {0} - fontinfo={1}' - .format(fontinfo.dvifont.texname, fontinfo.__dict__)) - _log.debug(msg) + _log.debug('Embedding TeX font %s - fontinfo=%s', + fontinfo.dvifont.texname, fontinfo.__dict__) # Widths widthsObject = self.reserveObject('font widths') @@ -770,12 +768,12 @@ def _embedTeXFont(self, fontinfo): # If no file is specified, stop short if fontinfo.fontfile is None: - msg = ('Because of TeX configuration (pdftex.map, see updmap ' - 'option pdftexDownloadBase14) the font {0} is not ' - 'embedded. This is deprecated as of PDF 1.5 and it may ' - 'cause the consumer application to show something that ' - 'was not intended.').format(fontinfo.basefont) - warnings.warn(msg) + _log.warning( + "Because of TeX configuration (pdftex.map, see updmap option " + "pdftexDownloadBase14) the font %s is not embedded. This is " + "deprecated as of PDF 1.5 and it may cause the consumer " + "application to show something that was not intended.", + fontinfo.basefont) fontdict['BaseFont'] = Name(fontinfo.basefont) self.writeObject(fontdictObject, fontdict) return fontdictObject @@ -1195,9 +1193,9 @@ def embedTTFType42(font, characters, descriptor): # save as a (non-subsetted) Type 42 font instead. if is_opentype_cff_font(filename): fonttype = 42 - msg = ("'%s' can not be subsetted into a Type 3 font. " - "The entire font will be embedded in the output.") - warnings.warn(msg % os.path.basename(filename)) + _log.warning("%r can not be subsetted into a Type 3 font. The " + "entire font will be embedded in the output.", + os.path.basename(filename)) if fonttype == 3: return embedTTFType3(font, characters, descriptor) @@ -1205,7 +1203,7 @@ def embedTTFType42(font, characters, descriptor): return embedTTFType42(font, characters, descriptor) def alphaState(self, alpha): - """Return name of an ExtGState that sets alpha to the given value""" + """Return name of an ExtGState that sets alpha to the given value.""" state = self.alphaStates.get(alpha, None) if state is not None: diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index e75c08f8bd74..cbe19b04f02e 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -369,8 +369,8 @@ def get_width_height_descent(self, text, prop): try: self._expect_prompt() except LatexError as e: - msg = "Error processing '%s'\nLaTeX Output:\n%s" - raise ValueError(msg % (text, e.latex_output)) + raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" + .format(text, e.latex_output)) # typeout width, height and text offset of the last textbox self._stdin_writeln(r"\typeout{\the\wd0,\the\ht0,\the\dp0}") @@ -378,15 +378,15 @@ def get_width_height_descent(self, text, prop): try: answer = self._expect_prompt() except LatexError as e: - msg = "Error processing '%s'\nLaTeX Output:\n%s" - raise ValueError(msg % (text, e.latex_output)) + raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" + .format(text, e.latex_output)) # parse metrics from the answer string try: width, height, offset = answer.splitlines()[0].split(",") except: - msg = "Error processing '%s'\nLaTeX Output:\n%s" % (text, answer) - raise ValueError(msg) + raise ValueError("Error processing '{}'\nLaTeX Output:\n{}" + .format(text, answer)) w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2]) # the height returned from LaTeX goes from base to top. diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index a2bb35d3e5bc..fb0b27c5f70a 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1104,11 +1104,10 @@ def print_figure_impl(fh): # STIX fonts). This will simply turn that off to avoid # errors. if is_opentype_cff_font(font_filename): - msg = ("OpenType CFF fonts can not be saved " - "using the internal Postscript backend " - "at this time.\nConsider using the " - "Cairo backend.") - raise RuntimeError(msg) + raise RuntimeError( + "OpenType CFF fonts can not be saved using " + "the internal Postscript backend at this " + "time; consider using the Cairo backend") else: fh.flush() convert_ttf_to_ps( diff --git a/lib/matplotlib/backends/backend_wx.py b/lib/matplotlib/backends/backend_wx.py index 7be2117f483e..363321ab2934 100644 --- a/lib/matplotlib/backends/backend_wx.py +++ b/lib/matplotlib/backends/backend_wx.py @@ -112,7 +112,7 @@ def error_msg_wx(msg, parent=None): def raise_msg_to_str(msg): - """msg is a return arg from a raise. Join with new lines""" + """msg is a return arg from a raise. Join with new lines.""" if not isinstance(msg, six.string_types): msg = '\n'.join(map(str, msg)) return msg diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index eb2bdfad4de7..e371aaa61563 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -1846,9 +1846,8 @@ def _compute_conf_interval(data, med, iqr, bootstrap): loval = np.min(x) hival = np.max(x) else: - whismsg = ('whis must be a float, valid string, or ' - 'list of percentiles') - raise ValueError(whismsg) + raise ValueError('whis must be a float, valid string, or list ' + 'of percentiles') else: loval = np.percentile(x, whis[0]) hival = np.percentile(x, whis[1]) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 6cb68eaea6f4..5d57533cc1ee 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1081,10 +1081,9 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, ''' locations = ["left", "right", "top", "bottom"] if orientation is not None and location is not None: - msg = ('position and orientation are mutually exclusive. ' - 'Consider setting the position to any of ' - '{0}'.format(', '.join(locations))) - raise TypeError(msg) + raise TypeError('position and orientation are mutually exclusive. ' + 'Consider setting the position to any of {}' + .format(', '.join(locations))) # provide a default location if location is None and orientation is None: diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index d37055fc05ed..b21db8e59235 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -1820,8 +1820,8 @@ def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv', try: blend = blend_mode(rgb, intensity, **kwargs) except TypeError: - msg = '"blend_mode" must be callable or one of {0}' - raise ValueError(msg.format(lookup.keys)) + raise ValueError('"blend_mode" must be callable or one of {}' + .format(lookup.keys)) # Only apply result where hillshade intensity isn't masked if hasattr(intensity, 'mask'): diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 7678623ca40a..82ef6731d184 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -176,10 +176,8 @@ def clabel(self, *args, **kwargs): indices.append(i) levels.append(lev) if len(levels) < len(levlabs): - msg = "Specified levels " + str(levlabs) - msg += "\n don't match available levels " - msg += str(self.levels) - raise ValueError(msg) + raise ValueError("Specified levels {} don't match available " + "levels {}".format(levlabs, self.levels)) else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.labelLevelList = levels diff --git a/lib/matplotlib/dviread.py b/lib/matplotlib/dviread.py index 4bc254c79f3c..aae80eeacd90 100644 --- a/lib/matplotlib/dviread.py +++ b/lib/matplotlib/dviread.py @@ -207,7 +207,7 @@ def __init__(self, filename, dpi): *dpi* only sets the units and does not limit the resolution. Use None to return TeX's internal units. """ - _log.debug('Dvi: ' + filename) + _log.debug('Dvi: %s', filename) self.file = open(filename, 'rb') self.dpi = dpi self.fonts = {} @@ -454,10 +454,9 @@ def _xxx(self, datalen): def chr_(x): return x _log.debug( - 'Dvi._xxx: encountered special: %s' - % ''.join([(32 <= ord(ch) < 127) and chr_(ch) - or '<%02x>' % ord(ch) - for ch in special])) + 'Dvi._xxx: encountered special: %s', + ''.join([chr_(ch) if 32 <= ord(ch) < 127 else '<%02x>' % ord(ch) + for ch in special])) @dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1')) def _fnt_def(self, k, c, s, d, a, l): @@ -582,8 +581,7 @@ def _width_of(self, char): width = self._tfm.width.get(char, None) if width is not None: return _mul2012(width, self._scale) - _log.debug( - 'No width for char %d in font %s' % (char, self.texname)) + _log.debug('No width for char %d in font %s.', char, self.texname) return 0 def _height_depth_of(self, char): @@ -596,9 +594,8 @@ def _height_depth_of(self, char): (self._tfm.depth, "depth")): value = metric.get(char, None) if value is None: - _log.debug( - 'No %s for char %d in font %s' % ( - name, char, self.texname)) + _log.debug('No %s for char %d in font %s', + name, char, self.texname) result.append(0) else: result.append(_mul2012(value, self._scale)) @@ -711,7 +708,7 @@ def _pre(self, i, x, cs, ds): if i != 202: raise ValueError("Unknown vf format %d" % i) if len(x): - _log.debug('vf file comment: ' + x) + _log.debug('vf file comment: %s', x) self.state = _dvistate.outer # cs = checksum, ds = design size @@ -759,14 +756,13 @@ class Tfm(object): __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth') def __init__(self, filename): - _log.debug('opening tfm file ' + filename) + _log.debug('opening tfm file %s', filename) with open(filename, 'rb') as file: header1 = file.read(24) lh, bc, ec, nw, nh, nd = \ struct.unpack('!6H', header1[2:14]) - _log.debug( - 'lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d' % ( - lh, bc, ec, nw, nh, nd)) + _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d', + lh, bc, ec, nw, nh, nd) header2 = file.read(4*lh) self.checksum, self.design_size = \ struct.unpack('!2I', header2[:8]) @@ -936,9 +932,8 @@ def _parse(self, file): w.group('enc2') or w.group('enc1')) if enc: if encoding is not None: - _log.debug( - 'Multiple encodings for %s = %s' - % (texname, psname)) + _log.debug('Multiple encodings for %s = %s', + texname, psname) encoding = enc continue # File names are probably unquoted: @@ -981,9 +976,9 @@ class Encoding(object): def __init__(self, filename): with open(filename, 'rb') as file: - _log.debug('Parsing TeX encoding ' + filename) + _log.debug('Parsing TeX encoding %s', filename) self.encoding = self._parse(file) - _log.debug('Result: ' + repr(self.encoding)) + _log.debug('Result: %s', self.encoding) def __iter__(self): for name in self.encoding: @@ -1043,8 +1038,7 @@ def find_tex_file(filename, format=None): if format is not None: cmd += ['--format=' + format] cmd += [filename] - _log.debug('find_tex_file(%s): %s' - % (filename, cmd)) + _log.debug('find_tex_file(%s): %s', filename, cmd) # stderr is unused, but reading it avoids a subprocess optimization # that breaks EINTR handling in some Python versions: # http://bugs.python.org/issue12493 @@ -1052,7 +1046,7 @@ def find_tex_file(filename, format=None): pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = pipe.communicate()[0].rstrip() - _log.debug('find_tex_file result: %s' % result) + _log.debug('find_tex_file result: %s', result) return result.decode('ascii') diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 6764d4b51276..91878860bfd7 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -979,8 +979,8 @@ def add_axes(self, *args, **kwargs): if isinstance(args[0], Axes): a = args[0] if a.get_figure() is not self: - msg = "The Axes must have been created in the present figure" - raise ValueError(msg) + raise ValueError( + "The Axes must have been created in the present figure") else: rect = args[0] if not np.isfinite(rect).all(): @@ -1075,9 +1075,8 @@ def add_subplot(self, *args, **kwargs): a = args[0] if a.get_figure() is not self: - msg = ("The Subplot must have been created in the present " - "figure") - raise ValueError(msg) + raise ValueError( + "The Subplot must have been created in the present figure") # make a key for the subplot (which includes the axes object id # in the hash) key = self._make_key(*args, **kwargs) @@ -1341,9 +1340,8 @@ def draw_artist(self, a): this is available only after the figure is drawn """ 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 get_axes(self): diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index 67d2a4f8bb1d..df2fe1d1bb88 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -545,7 +545,7 @@ def createFontList(fontfiles, fontext='ttf'): # Add fonts from list of known font files. seen = set() for fpath in fontfiles: - _log.debug('createFontDict: %s' % (fpath)) + _log.debug('createFontDict: %s', fpath) fname = os.path.split(fpath)[1] if fname in seen: continue @@ -1058,7 +1058,7 @@ def __init__(self, size=None, weight='normal'): self.defaultFont = {} for fname in self.ttffiles: - _log.debug('trying fontname %s' % fname) + _log.debug('trying fontname %s', fname) if fname.lower().find('DejaVuSans.ttf')>=0: self.defaultFont['ttf'] = fname break @@ -1068,8 +1068,8 @@ def __init__(self, size=None, weight='normal'): self.ttflist = createFontList(self.ttffiles) - self.afmfiles = findSystemFonts(paths, fontext='afm') + \ - findSystemFonts(fontext='afm') + self.afmfiles = (findSystemFonts(paths, fontext='afm') + + findSystemFonts(fontext='afm')) self.afmlist = createFontList(self.afmfiles, fontext='afm') if len(self.afmfiles): self.defaultFont['afm'] = self.afmfiles[0] @@ -1280,7 +1280,7 @@ def _findfont_cached(self, prop, fontext, directory, fallback_to_default, fname = prop.get_file() if fname is not None: - _log.debug('findfont returning %s'%fname) + _log.debug('findfont returning %s', fname) return fname if fontext == 'afm': diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 4293a913aa02..0b420f2b4c53 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -2522,9 +2522,8 @@ def key_desc(name): dt2 = r2.dtype[name] if dt1 != dt2: - msg = "The '{0}' fields in arrays 'r1' and 'r2' must have the same" - msg += " dtype." - raise ValueError(msg.format(name)) + raise ValueError("The '{}' fields in arrays 'r1' and 'r2' must " + "have the same dtype".format(name)) if dt1.num > dt2.num: return (name, dt1.descr[0][1]) else: @@ -3653,9 +3652,8 @@ def __init__(self, dataset, bw_method=None): self._bw_method = bw_method self.covariance_factor = lambda: self._bw_method(self) else: - msg = "`bw_method` should be 'scott', 'silverman', a scalar " \ - "or a callable." - raise ValueError(msg) + raise ValueError("`bw_method` should be 'scott', 'silverman', a " + "scalar or a callable") # Computes the covariance matrix for each Gaussian kernel using # covariance_factor(). @@ -3710,9 +3708,8 @@ def evaluate(self, points): dim, num_m = np.array(points).shape if dim != self.dim: - msg = "points have dimension %s, dataset has dimension %s" % ( - dim, self.dim) - raise ValueError(msg) + raise ValueError("points have dimension {}, dataset has dimension " + "{}".format(dim, self.dim)) result = np.zeros((num_m,), dtype=float) diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index c6390a371c89..8437338ddde6 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -2021,7 +2021,6 @@ def __call__(self, x0, y0, width, height, mutation_size, def __reduce__(self): # because we have decided to nest thes classes, we need to # add some more information to allow instance pickling. - import matplotlib.cbook as cbook return (cbook._NestedClassGetter(), (BoxStyle, self.__class__.__name__), self.__dict__ @@ -2808,7 +2807,6 @@ def __call__(self, posA, posB, def __reduce__(self): # because we have decided to nest these classes, we need to # add some more information to allow instance pickling. - import matplotlib.cbook as cbook return (cbook._NestedClassGetter(), (ConnectionStyle, self.__class__.__name__), self.__dict__ @@ -3198,9 +3196,6 @@ class is not an artist and actual drawing of the fancy arrow is # w/o arguments, i.e., all its argument (except self) must have # the default values. - def __init__(self): - super(ArrowStyle._Base, self).__init__() - @staticmethod def ensure_quadratic_bezier(path): """ Some ArrowStyle class only wokrs with a simple @@ -3210,10 +3205,10 @@ def ensure_quadratic_bezier(path): its control points if true. """ segments = list(path.iter_segments()) - if ((len(segments) != 2) or (segments[0][1] != Path.MOVETO) or - (segments[1][1] != Path.CURVE3)): - msg = "'path' it's not a valid quadratic bezier curve" - raise ValueError(msg) + if (len(segments) != 2 or segments[0][1] != Path.MOVETO or + segments[1][1] != Path.CURVE3): + raise ValueError( + "'path' it's not a valid quadratic Bezier curve") return list(segments[0][0]) + list(segments[1][0]) @@ -3269,7 +3264,6 @@ def __call__(self, path, mutation_size, linewidth, def __reduce__(self): # because we have decided to nest thes classes, we need to # add some more information to allow instance pickling. - import matplotlib.cbook as cbook return (cbook._NestedClassGetter(), (ArrowStyle, self.__class__.__name__), self.__dict__ diff --git a/lib/matplotlib/path.py b/lib/matplotlib/path.py index df4d1e8f38cf..c0153401ecb9 100644 --- a/lib/matplotlib/path.py +++ b/lib/matplotlib/path.py @@ -135,19 +135,17 @@ def __init__(self, vertices, codes=None, _interpolation_steps=1, """ vertices = _to_unmasked_float_array(vertices) if (vertices.ndim != 2) or (vertices.shape[1] != 2): - msg = "'vertices' must be a 2D list or array with shape Nx2" - raise ValueError(msg) + raise ValueError( + "'vertices' must be a 2D list or array with shape Nx2") if codes is not None: codes = np.asarray(codes, self.code_type) if (codes.ndim != 1) or len(codes) != len(vertices): - msg = ("'codes' must be a 1D list or array with the same" - " length of 'vertices'") - raise ValueError(msg) + raise ValueError("'codes' must be a 1D list or array with the " + "same length of 'vertices'") if len(codes) and codes[0] != self.MOVETO: - msg = ("The first element of 'code' must be equal to 'MOVETO':" - " {0}") - raise ValueError(msg.format(self.MOVETO)) + raise ValueError("The first element of 'code' must be equal " + "to 'MOVETO' ({})".format(self.MOVETO)) elif closed: codes = np.empty(len(vertices), dtype=self.code_type) codes[0] = self.MOVETO diff --git a/lib/matplotlib/projections/geo.py b/lib/matplotlib/projections/geo.py index cb2c581fb5fe..0cd6ee785b26 100644 --- a/lib/matplotlib/projections/geo.py +++ b/lib/matplotlib/projections/geo.py @@ -127,9 +127,9 @@ def _get_affine_transform(self): .translate(0.5, 0.5) def get_xaxis_transform(self,which='grid'): - if which not in ['tick1','tick2','grid']: - msg = "'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]" - raise ValueError(msg) + if which not in ['tick1', 'tick2', 'grid']: + raise ValueError( + "'which' must be one of 'tick1', 'tick2', or 'grid'") return self._xaxis_transform def get_xaxis_text1_transform(self, pad): @@ -139,9 +139,9 @@ def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'top', 'center' def get_yaxis_transform(self,which='grid'): - if which not in ['tick1','tick2','grid']: - msg = "'which' must be one of [ 'tick1' | 'tick2' | 'grid' ]" - raise ValueError(msg) + if which not in ['tick1', 'tick2', 'grid']: + raise ValueError( + "'which' must be one of 'tick1', 'tick2', or 'grid'") return self._yaxis_transform def get_yaxis_text1_transform(self, pad): diff --git a/lib/matplotlib/projections/polar.py b/lib/matplotlib/projections/polar.py index fe9f3e536171..610053315c8b 100644 --- a/lib/matplotlib/projections/polar.py +++ b/lib/matplotlib/projections/polar.py @@ -971,8 +971,8 @@ def _set_lim_and_transforms(self): def get_xaxis_transform(self, which='grid'): 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._xaxis_transform def get_xaxis_text1_transform(self, pad): @@ -987,8 +987,8 @@ def get_yaxis_transform(self, which='grid'): elif which == 'grid': return self._yaxis_transform else: - msg = "'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]" - raise ValueError(msg) + raise ValueError( + "'which' must be one of 'tick1', 'tick2', or 'grid'") def get_yaxis_text1_transform(self, pad): thetamin, thetamax = self._realViewLim.intervalx diff --git a/lib/matplotlib/spines.py b/lib/matplotlib/spines.py index d8f98fa13c0f..3c3a115ffbee 100644 --- a/lib/matplotlib/spines.py +++ b/lib/matplotlib/spines.py @@ -73,8 +73,8 @@ def __init__(self, axes, spine_type, path, **kwargs): # them pass through the spines machinery without errors.) self._position = None if not isinstance(path, matplotlib.path.Path): - msg = "'path' must be an instance of 'matplotlib.path.Path'" - raise ValueError(msg) + raise ValueError( + "'path' must be an instance of 'matplotlib.path.Path'") self._path = path # To support drawing both linear and circular spines, this @@ -420,9 +420,8 @@ def set_position(self, position): if len(position) != 2: raise ValueError("position should be 'center' or 2-tuple") if position[0] not in ['outward', 'axes', 'data']: - msg = ("position[0] should be in [ 'outward' | 'axes' |" - " 'data' ]") - raise ValueError(msg) + raise ValueError("position[0] should be one of 'outward', " + "'axes', or 'data' ") self._position = position self._calc_offset_transform() diff --git a/lib/matplotlib/streamplot.py b/lib/matplotlib/streamplot.py index a9c5c276a2d3..9f3097d386bf 100644 --- a/lib/matplotlib/streamplot.py +++ b/lib/matplotlib/streamplot.py @@ -112,8 +112,8 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, use_multicolor_lines = isinstance(color, np.ndarray) if use_multicolor_lines: if color.shape != grid.shape: - msg = "If 'color' is given, must have the shape of 'Grid(x,y)'" - raise ValueError(msg) + raise ValueError( + "If 'color' is given, must have the shape of 'Grid(x,y)'") line_colors = [] color = np.ma.masked_invalid(color) else: @@ -122,8 +122,8 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, if isinstance(linewidth, np.ndarray): if linewidth.shape != grid.shape: - msg = "If 'linewidth' is given, must have the shape of 'Grid(x,y)'" - raise ValueError(msg) + raise ValueError( + "If 'linewidth' is given, must have the shape of 'Grid(x,y)'") line_kw['linewidth'] = [] else: line_kw['linewidth'] = linewidth @@ -133,9 +133,8 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, arrow_kw['zorder'] = zorder ## Sanity checks. - if (u.shape != grid.shape) or (v.shape != grid.shape): - msg = "'u' and 'v' must be of shape 'Grid(x,y)'" - raise ValueError(msg) + if u.shape != grid.shape or v.shape != grid.shape: + raise ValueError("'u' and 'v' must be of shape 'Grid(x,y)'") u = np.ma.masked_invalid(u) v = np.ma.masked_invalid(v) diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index bd35f902eab2..66164ac7ae2b 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -112,10 +112,10 @@ def use(style): rc = rc_params_from_file(style, use_default_template=False) _apply_style(rc) except IOError: - msg = ("'%s' not found in the style library and input is " - "not a valid URL or path. See `style.available` for " - "list of available styles.") - raise IOError(msg % style) + raise IOError( + "{!r} not found in the style library and input is not a " + "valid URL or path; see `style.available` for list of " + "available styles".format(style)) @contextlib.contextmanager diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index 80c17cfb92b4..08f1a5fe89bb 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -181,13 +181,11 @@ def visible_edges(self, value): else: for edge in value: if edge not in self._edges: - msg = ('Invalid edge param {0}, must only be one of' - ' {1} or string of {2}.').format( - value, - ", ".join(self._edge_aliases), - ", ".join(self._edges), - ) - raise ValueError(msg) + raise ValueError('Invalid edge param {}, must only be one ' + 'of {} or string of {}'.format( + value, + ", ".join(self._edge_aliases), + ", ".join(self._edges))) self._visible_edges = value self.stale = True @@ -585,16 +583,16 @@ def table(ax, cols = len(cellText[0]) for row in cellText: if len(row) != cols: - msg = "Each row in 'cellText' must have {0} columns" - raise ValueError(msg.format(cols)) + raise ValueError("Each row in 'cellText' must have {} columns" + .format(cols)) if cellColours is not None: if len(cellColours) != rows: - raise ValueError("'cellColours' must have {0} rows".format(rows)) + raise ValueError("'cellColours' must have {} rows".format(rows)) for row in cellColours: if len(row) != cols: - msg = "Each row in 'cellColours' must have {0} columns" - raise ValueError(msg.format(cols)) + raise ValueError("Each row in 'cellColours' must have {} " + "columns".format(cols)) else: cellColours = ['w' * cols] * rows diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 978f1abac005..b11be51c312c 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -23,8 +23,8 @@ from matplotlib import ticker from matplotlib import pyplot as plt from matplotlib import ft2font -from matplotlib.testing.compare import comparable_formats, compare_images, \ - make_test_filename +from matplotlib.testing.compare import ( + comparable_formats, compare_images, make_test_filename) from . import _copy_metadata, is_called_from_pytest from .exceptions import ImageComparisonFailure diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index c6c813e1b6d5..5cd78f0e620c 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -1459,10 +1459,9 @@ def raise_if_exceeds(self, locs): """raise a RuntimeError if Locator attempts to create more than MAXTICKS locs""" if len(locs) >= self.MAXTICKS: - msg = ('Locator attempting to generate %d ticks from %s to %s: ' + - 'exceeds Locator.MAXTICKS') % (len(locs), locs[0], locs[-1]) - raise RuntimeError(msg) - + raise RuntimeError("Locator attempting to generate {} ticks from " + "{} to {}: exceeds Locator.MAXTICKS".format( + len(locs), locs[0], locs[-1])) return locs def view_limits(self, vmin, vmax): diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index 3676b278e512..6d67bf1399c3 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -1045,12 +1045,11 @@ def __init__(self, bbox, transform, **kwargs): if not bbox.is_bbox: raise ValueError("'bbox' is not a bbox") if not isinstance(transform, Transform): - msg = ("'transform' must be an instance of" - " 'matplotlib.transform.Transform'") - raise ValueError(msg) + raise ValueError("'transform' must be an instance of " + "'matplotlib.transform.Transform'") if transform.input_dims != 2 or transform.output_dims != 2: - msg = "The input and output dimensions of 'transform' must be 2" - raise ValueError(msg) + raise ValueError( + "The input and output dimensions of 'transform' must be 2") BboxBase.__init__(self, **kwargs) self._bbox = bbox @@ -1529,8 +1528,7 @@ def transform_point(self, point): :attr:`output_dims`. """ if len(point) != self.input_dims: - msg = "The length of 'point' must be 'self.input_dims'" - raise ValueError(msg) + raise ValueError("The length of 'point' must be 'self.input_dims'") return self.transform(np.asarray([point]))[0] def transform_path(self, path): @@ -1604,9 +1602,8 @@ def transform_angles(self, angles, pts, radians=False, pushoff=1e-5): raise ValueError("'pts' must be array with 2 columns for x,y") if angles.ndim != 1 or angles.shape[0] != pts.shape[0]: - msg = "'angles' must be a column vector and have same number of" - msg += " rows as 'pts'" - raise ValueError(msg) + raise ValueError("'angles' must be a column vector and have same " + "number of rows as 'pts'") # Convert to radians if desired if not radians: @@ -1667,9 +1664,8 @@ def __init__(self, child): be replaced with :meth:`set`. """ if not isinstance(child, Transform): - msg = ("'child' must be an instance of" - " 'matplotlib.transform.Transform'") - raise ValueError(msg) + raise ValueError("'child' must be an instance of " + "'matplotlib.transform.Transform'") self._init(child) self.set_children(child) @@ -1743,9 +1739,9 @@ def set(self, child): """ if (child.input_dims != self.input_dims or child.output_dims != self.output_dims): - msg = ("The new child must have the same number of input and" - " output dimensions as the current child.") - raise ValueError(msg) + raise ValueError( + "The new child must have the same number of input and output " + "dimensions as the current child") self.set_children(child) self._set(child) @@ -1991,9 +1987,8 @@ def set(self, other): :class:`Affine2DBase` object. """ if not isinstance(other, Affine2DBase): - msg = ("'other' must be an instance of" - " 'matplotlib.transform.Affine2DBase'") - raise ValueError(msg) + raise ValueError("'other' must be an instance of " + "'matplotlib.transform.Affine2DBase'") self._mtx = other.get_matrix() self.invalidate() @@ -2332,9 +2327,8 @@ def __init__(self, x_transform, y_transform, **kwargs): is_separable = x_transform.is_separable and y_transform.is_separable is_correct = is_affine and is_separable if not is_correct: - msg = ("Both *x_transform* and *y_transform* must be 2D affine" - " transforms.") - raise ValueError(msg) + raise ValueError("Both *x_transform* and *y_transform* must be 2D " + "affine transforms") Transform.__init__(self, **kwargs) self._x = x_transform @@ -2417,9 +2411,8 @@ def __init__(self, a, b, **kwargs): transform instance to create. """ if a.output_dims != b.input_dims: - msg = ("The output dimension of 'a' must be equal to the input" - " dimensions of 'b'") - raise ValueError(msg) + raise ValueError("The output dimension of 'a' must be equal to " + "the input dimensions of 'b'") self.input_dims = a.input_dims self.output_dims = b.output_dims @@ -2548,9 +2541,8 @@ def __init__(self, a, b, **kwargs): if not a.is_affine or not b.is_affine: raise ValueError("'a' and 'b' must be affine transforms") if a.output_dims != b.input_dims: - msg = ("The output dimension of 'a' must be equal to the input" - " dimensions of 'b'") - raise ValueError(msg) + raise ValueError("The output dimension of 'a' must be equal to " + "the input dimensions of 'b'") self.input_dims = a.input_dims self.output_dims = b.output_dims @@ -2629,8 +2621,7 @@ def __init__(self, boxin, boxout, **kwargs): points from *boxin* to *boxout*. """ if not boxin.is_bbox or not boxout.is_bbox: - msg = "'boxin' and 'boxout' must be bbox" - raise ValueError(msg) + raise ValueError("'boxin' and 'boxout' must be bbox") Affine2DBase.__init__(self, **kwargs) self._boxin = boxin @@ -2820,9 +2811,8 @@ def __init__(self, path, transform): :class:`~matplotlib.path.Path` and :class:`Transform`. """ if not isinstance(transform, Transform): - msg = ("'transform' must be an instance of" - " 'matplotlib.transform.Transform'") - raise ValueError(msg) + raise ValueError("'transform' must be an instance of " + "'matplotlib.transform.Transform'") TransformNode.__init__(self) self._path = path diff --git a/lib/matplotlib/tri/tripcolor.py b/lib/matplotlib/tri/tripcolor.py index ce48e5b39b39..1da789a0774e 100644 --- a/lib/matplotlib/tri/tripcolor.py +++ b/lib/matplotlib/tri/tripcolor.py @@ -133,10 +133,8 @@ def tripcolor(ax, *args, **kwargs): collection.set_alpha(alpha) collection.set_array(C) - if norm is not None: - if not isinstance(norm, Normalize): - msg = "'norm' must be an instance of 'Normalize'" - raise ValueError(msg) + if norm is not None and not isinstance(norm, Normalize): + raise ValueError("'norm' must be an instance of 'Normalize'") collection.set_cmap(cmap) collection.set_norm(norm) if vmin is not None or vmax is not None: diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py index f551abad778c..f74040270bcd 100644 --- a/lib/matplotlib/widgets.py +++ b/lib/matplotlib/widgets.py @@ -1751,8 +1751,7 @@ def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops['animated'] = self.useblit if direction not in ['horizontal', 'vertical']: - msg = "direction must be in [ 'horizontal' | 'vertical' ]" - raise ValueError(msg) + raise ValueError("direction must be 'horizontal' or 'vertical'") self.direction = direction self.rect = None @@ -2092,8 +2091,7 @@ def __init__(self, ax, onselect, drawtype='box', self.minspany = minspany if spancoords not in ('data', 'pixels'): - msg = "'spancoords' must be one of [ 'data' | 'pixels' ]" - raise ValueError(msg) + raise ValueError("'spancoords' must be 'data' or 'pixels'") self.spancoords = spancoords self.drawtype = drawtype diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 73385ec91256..51e4851d228d 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -1059,7 +1059,9 @@ def mouse_init(self, rotate_btn=1, zoom_btn=3): c3 = canv.mpl_connect('button_release_event', self._button_release) self._cids = [c1, c2, c3] else: - warnings.warn('Axes3D.figure.canvas is \'None\', mouse rotation disabled. Set canvas then call Axes3D.mouse_init().') + warnings.warn( + "Axes3D.figure.canvas is 'None', mouse rotation disabled. " + "Set canvas then call Axes3D.mouse_init().") # coerce scalars into array-like, then convert into # a regular list to avoid comparisons against None 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