From fb87d772b0b55d5d7a110dae44d3a691ebc2bf3e Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 4 Jan 2019 22:15:09 +0100 Subject: [PATCH] Remove some more 1-tuples. --- .flake8 | 1 - examples/units/basic_units.py | 11 +++---- lib/matplotlib/__init__.py | 4 +-- lib/matplotlib/axes/_base.py | 3 +- lib/matplotlib/axes/_subplots.py | 5 ++- lib/matplotlib/cbook/__init__.py | 2 +- lib/matplotlib/colorbar.py | 6 ++-- lib/matplotlib/container.py | 5 +-- lib/matplotlib/figure.py | 6 ++-- lib/matplotlib/lines.py | 33 ++++++++----------- .../testing/jpl_units/UnitDblConverter.py | 4 +-- lib/matplotlib/tests/test_rcparams.py | 4 +-- lib/matplotlib/text.py | 6 ++-- lib/mpl_toolkits/axes_grid1/axes_divider.py | 2 +- lib/mpl_toolkits/axes_grid1/mpl_axes.py | 3 +- lib/mpl_toolkits/mplot3d/axes3d.py | 3 +- .../tests/test_axisartist_angle_helper.py | 7 ++-- 17 files changed, 48 insertions(+), 57 deletions(-) diff --git a/.flake8 b/.flake8 index 4cb738b4b544..1fe0e6fcb55a 100644 --- a/.flake8 +++ b/.flake8 @@ -54,7 +54,6 @@ per-file-ignores = mpl_toolkits/axes_grid1/axes_size.py: E272, E501 mpl_toolkits/axes_grid1/colorbar.py: E225, E501 mpl_toolkits/axes_grid1/inset_locator.py: E501 - mpl_toolkits/axes_grid1/mpl_axes.py: E501 mpl_toolkits/axisartist/angle_helper.py: E221 mpl_toolkits/axisartist/clip_path.py: E225, E501 mpl_toolkits/axisartist/floating_axes.py: E225, E402, E501 diff --git a/examples/units/basic_units.py b/examples/units/basic_units.py index 49eb823ffbe2..50ca20675c5b 100644 --- a/examples/units/basic_units.py +++ b/examples/units/basic_units.py @@ -122,9 +122,8 @@ def __new__(cls, value, unit): # generate a new subclass for value value_class = type(value) try: - subcls = type('TaggedValue_of_%s' % (value_class.__name__), - tuple([cls, value_class]), - {}) + subcls = type(f'TaggedValue_of_{value_class.__name__}', + (cls, value_class), {}) if subcls not in units.registry: units.registry[subcls] = basicConverter return object.__new__(subcls) @@ -196,7 +195,7 @@ def __init__(self, name, fullname=None): self.conversions = dict() def __repr__(self): - return 'BasicUnit(%s)' % self.name + return f'BasicUnit({self.name})' def __str__(self): return self.fullname @@ -314,9 +313,9 @@ def rad_fn(x, pos=None): elif n == -2: return r'$-\pi$' elif n % 2 == 0: - return r'$%s\pi$' % (n//2,) + return fr'${n//2}\pi$' else: - return r'$%s\pi/2$' % (n,) + return fr'${n}\pi/2$' class BasicUnitConverter(units.ConversionInterface): diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 2eb1c7053650..660a35da3d4f 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -844,8 +844,8 @@ def __setitem__(self, key, val): dict.__setitem__(self, key, cval) except KeyError: raise KeyError( - '%s is not a valid rc parameter. See rcParams.keys() for a ' - 'list of valid parameters.' % (key,)) + f"{key} is not a valid rc parameter (see rcParams.keys() for " + f"a list of valid parameters)") def __getitem__(self, key): if key in _deprecated_map: diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index e94b396d2b2e..ecf44285786a 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -2291,8 +2291,7 @@ def margins(self, *margins, x=None, y=None, tight=True): if x is None and y is None: if tight is not True: - cbook._warn_external( - 'ignoring tight=%r in get mode' % (tight,)) + cbook._warn_external(f'ignoring tight={tight!r} in get mode') return self._xmargin, self._ymargin if x is not None: diff --git a/lib/matplotlib/axes/_subplots.py b/lib/matplotlib/axes/_subplots.py index 4ff7b44dcd12..b82f53663523 100644 --- a/lib/matplotlib/axes/_subplots.py +++ b/lib/matplotlib/axes/_subplots.py @@ -55,13 +55,12 @@ def __init__(self, fig, *args, **kwargs): else: if num < 1 or num > rows*cols: raise ValueError( - ("num must be 1 <= num <= {maxn}, not {num}" - ).format(maxn=rows*cols, num=num)) + f"num must be 1 <= num <= {rows*cols}, not {num}") self._subplotspec = GridSpec( rows, cols, figure=self.figure)[int(num) - 1] # num - 1 for converting from MATLAB to python indexing else: - raise ValueError('Illegal argument(s) to subplot: %s' % (args,)) + raise ValueError(f'Illegal argument(s) to subplot: {args}') self.update_params() diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 306cd6812b97..11d59efb2363 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -879,7 +879,7 @@ def recurse(obj, start, all, current_path): recurse(referent, start, all, current_path + [obj]) for obj in objects: - outstream.write("Examining: %r\n" % (obj,)) + outstream.write(f"Examining: {obj!r}\n") recurse(obj, obj, {}, []) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 9926bf6713f1..e26b19779514 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -638,10 +638,8 @@ def _set_label(self): self.stale = True def set_label(self, label, **kw): - ''' - Label the long axis of the colorbar - ''' - self._label = '%s' % (label, ) + """Label the long axis of the colorbar.""" + self._label = str(label) self._labelkw = kw self._set_label() diff --git a/lib/matplotlib/container.py b/lib/matplotlib/container.py index 552d6da5a761..570c1ca8c55b 100644 --- a/lib/matplotlib/container.py +++ b/lib/matplotlib/container.py @@ -52,10 +52,11 @@ def set_label(self, s): Parameters ---------- - s : string or anything printable with '%s' conversion. + s : object + Any object other than None gets converted to its `str`. """ if s is not None: - self._label = '%s' % (s, ) + self._label = str(s) else: self._label = None self.pchanged() diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 551129f82fad..92fda12b539a 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -1951,9 +1951,9 @@ def __setstate__(self, state): restore_to_pylab = state.pop('_restore_to_pylab', False) if version != _mpl_version: - cbook._warn_external("This figure was saved with matplotlib " - "version %s and is unlikely to function " - "correctly." % (version,)) + cbook._warn_external( + f"This figure was saved with matplotlib version {version} and " + f"is unlikely to function correctly.") self.__dict__ = state diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 149c5c09238d..4d8030d9de02 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -180,30 +180,26 @@ def _slice_or_none(in_v, slc): inds = inds.argmin(axis=1) inds = np.unique(inds) # return, we are done here - return Path(verts[inds], - _slice_or_none(codes, inds)) + return Path(verts[inds], _slice_or_none(codes, inds)) else: raise ValueError( - '`markevery` is a tuple with len 2, but its second element is ' - 'not an int or a float; markevery=%s' % (markevery,)) + f"markevery={markevery!r} is a tuple with len 2, but its " + f"second element is not an int or a float") elif isinstance(markevery, slice): # mazol tov, it's already a slice, just return return Path(verts[markevery], _slice_or_none(codes, markevery)) elif np.iterable(markevery): - #fancy indexing + # fancy indexing try: return Path(verts[markevery], _slice_or_none(codes, markevery)) - except (ValueError, IndexError): - raise ValueError('`markevery` is iterable but ' - 'not a valid form of numpy fancy indexing; ' - 'markevery=%s' % (markevery,)) + raise ValueError( + f"markevery={markevery!r} is iterable but not a valid numpy " + f"fancy index") else: - raise ValueError('Value of `markevery` is not ' - 'recognized; ' - 'markevery=%s' % (markevery,)) + raise ValueError(f"markevery={markevery!r} is not a recognized value") @cbook._define_aliases({ @@ -264,17 +260,16 @@ class Line2D(Artist): def __str__(self): if self._label != "": - return "Line2D(%s)" % (self._label) + return f"Line2D({self._label})" elif self._x is None: return "Line2D()" elif len(self._x) > 3: - return "Line2D((%g,%g),(%g,%g),...,(%g,%g))"\ - % (self._x[0], self._y[0], self._x[0], - self._y[0], self._x[-1], self._y[-1]) + return "Line2D((%g,%g),(%g,%g),...,(%g,%g))" % ( + self._x[0], self._y[0], self._x[0], + self._y[0], self._x[-1], self._y[-1]) else: - return "Line2D(%s)"\ - % (",".join(["(%g,%g)" % (x, y) for x, y - in zip(self._x, self._y)])) + return "Line2D(%s)" % ",".join( + map("({:g},{:g})".format, self._x, self._y)) def __init__(self, xdata, ydata, linewidth=None, # all Nones default to rc diff --git a/lib/matplotlib/testing/jpl_units/UnitDblConverter.py b/lib/matplotlib/testing/jpl_units/UnitDblConverter.py index 342ac00cc523..352c30b84413 100644 --- a/lib/matplotlib/testing/jpl_units/UnitDblConverter.py +++ b/lib/matplotlib/testing/jpl_units/UnitDblConverter.py @@ -21,9 +21,9 @@ def rad_fn(x, pos=None): elif n == 2: return r'$\pi$' elif n % 2 == 0: - return r'$%s\pi$' % (n/2,) + return fr'${n//2}\pi$' else: - return r'$%s\pi/2$' % (n,) + return fr'${n}\pi/2$' class UnitDblConverter(units.ConversionInterface): diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index aaf52b0246ca..6634481c49b4 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -163,8 +163,8 @@ def test_Bug_2543(): @pytest.mark.parametrize('color_type, param_dict, target', legend_color_tests, ids=legend_color_test_ids) def test_legend_colors(color_type, param_dict, target): - param_dict['legend.%scolor' % (color_type, )] = param_dict.pop('color') - get_func = 'get_%scolor' % (color_type, ) + param_dict[f'legend.{color_type}color'] = param_dict.pop('color') + get_func = f'get_{color_type}color' with mpl.rc_context(param_dict): _, ax = plt.subplots() diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index d09aa39742bf..37ca1286d9fa 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -1145,12 +1145,14 @@ def set_text(self, s): Parameters ---------- - s : string or object castable to string (but ``None`` becomes ``''``) + s : object + Any object gets converted to its `str`, except ``None`` which + becomes ``''``. """ if s is None: s = '' if s != self._text: - self._text = '%s' % (s,) + self._text = str(s) self.stale = True @staticmethod diff --git a/lib/mpl_toolkits/axes_grid1/axes_divider.py b/lib/mpl_toolkits/axes_grid1/axes_divider.py index a8616d7472b9..786d6096f513 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid1/axes_divider.py @@ -396,7 +396,7 @@ def __init__(self, fig, *args, horizontal=None, vertical=None, self._subplotspec = GridSpec(rows, cols)[int(num)-1] # num - 1 for converting from MATLAB to python indexing else: - raise ValueError('Illegal argument(s) to subplot: %s' % (args,)) + raise ValueError(f'Illegal argument(s) to subplot: {args}') # total = rows*cols # num -= 1 # convert from matlab to python indexing diff --git a/lib/mpl_toolkits/axes_grid1/mpl_axes.py b/lib/mpl_toolkits/axes_grid1/mpl_axes.py index 0f63ee5067ac..ba02eb5d0c31 100644 --- a/lib/mpl_toolkits/axes_grid1/mpl_axes.py +++ b/lib/mpl_toolkits/axes_grid1/mpl_axes.py @@ -70,7 +70,8 @@ def __init__(self, axis, axisnum, spine): elif isinstance(axis, YAxis): self._axis_direction = ["left", "right"][axisnum-1] else: - raise ValueError("axis must be instance of XAxis or YAxis : %s is provided" % (axis,)) + raise ValueError( + f"axis must be instance of XAxis or YAxis, but got {axis}") Artist.__init__(self) @property diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 1361c8cf154e..3d124cbd3f0c 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -435,8 +435,7 @@ def margins(self, *margins, x=None, y=None, z=None, tight=True): if x is None and y is None and z is None: if tight is not True: - cbook._warn_external( - 'ignoring tight=%r in get mode' % (tight,)) + cbook._warn_external(f'ignoring tight={tight!r} in get mode') return self._xmargin, self._ymargin, self._zmargin if x is not None: diff --git a/lib/mpl_toolkits/tests/test_axisartist_angle_helper.py b/lib/mpl_toolkits/tests/test_axisartist_angle_helper.py index f8e279b3fc7e..3156b33b69c4 100644 --- a/lib/mpl_toolkits/tests/test_axisartist_angle_helper.py +++ b/lib/mpl_toolkits/tests/test_axisartist_angle_helper.py @@ -118,12 +118,11 @@ def test_formatters(Formatter, regex, direction, factor, values): prev_degree = prev_minute = prev_second = None for tick, value in zip(result, values): m = regex.match(tick) - assert m is not None, '"%s" is not an expected tick format.' % (tick, ) + assert m is not None, f'{tick!r} is not an expected tick format.' sign = sum(m.group(sign + '_sign') is not None for sign in ('degree', 'minute', 'second')) - assert sign <= 1, \ - 'Only one element of tick "%s" may have a sign.' % (tick, ) + assert sign <= 1, f'Only one element of tick {tick!r} may have a sign.' sign = 1 if sign == 0 else -1 degree = float(m.group('degree') or prev_degree or 0) @@ -135,7 +134,7 @@ def test_formatters(Formatter, regex, direction, factor, values): else: expected_value = pytest.approx(value / factor) assert sign * dms2float(degree, minute, second) == expected_value, \ - '"%s" does not match expected tick value.' % (tick, ) + f'{tick!r} does not match expected tick value.' prev_degree = degree prev_minute = minute