From dda9fc7e53a0455e4291d23a90feed6f0d3c1274 Mon Sep 17 00:00:00 2001 From: zm711 <92116279+zm711@users.noreply.github.com> Date: Fri, 1 Mar 2024 15:41:24 -0500 Subject: [PATCH] switch to f-strings --- quantities/decorators.py | 10 +++++----- quantities/dimensionality.py | 31 ++++++++++++------------------- quantities/markup.py | 6 +++--- quantities/quantity.py | 24 +++++++++--------------- quantities/registry.py | 5 ++--- quantities/tests/common.py | 5 ++--- quantities/tests/test_units.py | 2 +- quantities/umath.py | 6 ++---- quantities/uncertainquantity.py | 6 +----- quantities/unitquantity.py | 29 +++++++++++++---------------- 10 files changed, 50 insertions(+), 74 deletions(-) diff --git a/quantities/decorators.py b/quantities/decorators.py index bd4d0e2..336a458 100644 --- a/quantities/decorators.py +++ b/quantities/decorators.py @@ -42,11 +42,11 @@ def __call__(self, new_method): header = self.header if original_doc and new_doc: - new_method.__doc__ = """ - {} - {} - {} - """.format(original_doc, header, new_doc) + new_method.__doc__ = f""" + {original_doc} + {header} + {new_doc} + """ elif original_doc: new_method.__doc__ = original_doc diff --git a/quantities/dimensionality.py b/quantities/dimensionality.py index c8d6002..52dfc65 100644 --- a/quantities/dimensionality.py +++ b/quantities/dimensionality.py @@ -69,8 +69,7 @@ def __add__(self, other): assert self == other except AssertionError: raise ValueError( - 'can not add units of %s and %s'\ - %(str(self), str(other)) + f'can not add units of {str(self)} and {str(other)}' ) return self.copy() @@ -82,8 +81,7 @@ def __iadd__(self, other): assert self == other except AssertionError: raise ValueError( - 'can not add units of %s and %s'\ - %(str(self), str(other)) + f'can not add units of {str(self)} and {str(other)}' ) return self @@ -93,8 +91,7 @@ def __sub__(self, other): assert self == other except AssertionError: raise ValueError( - 'can not subtract units of %s and %s'\ - %(str(self), str(other)) + f'can not subtract units of {str(self)} and {str(other)}' ) return self.copy() @@ -106,8 +103,7 @@ def __isub__(self, other): assert self == other except AssertionError: raise ValueError( - 'can not add units of %s and %s'\ - %(str(self), str(other)) + f'can not add units of {str(self)} and {str(other)}' ) return self @@ -161,7 +157,7 @@ def __pow__(self, other): try: assert np.isscalar(other) except AssertionError: - raise TypeError('exponent must be a scalar, got %r' % other) + raise TypeError(f'exponent must be a scalar, got {other!r}') if other == 0: return Dimensionality() new = Dimensionality(self) @@ -173,7 +169,7 @@ def __ipow__(self, other): try: assert np.isscalar(other) except AssertionError: - raise TypeError('exponent must be a scalar, got %r' % other) + raise TypeError(f'exponent must be a scalar, got {other!r}') if other == 0: self.clear() return self @@ -246,8 +242,7 @@ def _d_check_uniform(q1, q2, out=None): return q1.dimensionality except AssertionError: raise ValueError( - 'quantities must have identical units, got "%s" and "%s"' % - (q1.units, q2.units) + f'quantities must have identical units, got "{q1.units}" and "{q2.units}"' ) except AttributeError: try: @@ -265,8 +260,7 @@ def _d_check_uniform(q1, q2, out=None): raise ValueError except ValueError: raise ValueError( - 'quantities must have identical units, got "%s" and "%s"' % - (q1.units, q2.units) + f'quantities must have identical units, got "{q1.units}" and "{q2.units}"' ) p_dict[np.add] = _d_check_uniform @@ -288,8 +282,7 @@ def _d_arctan2(q1, q2, out=None): return Dimensionality() except AssertionError: raise ValueError( - 'quantities must have identical units, got "%s" and "%s"' % - (q1.units, q2.units) + f'quantities must have identical units, got "{q1.units}" and "{q2.units}"' ) p_dict[np.arctan2] = _d_arctan2 @@ -343,7 +336,7 @@ def _d_radians(q1, out=None): assert q1.units == unit_registry['degree'] except AssertionError: raise ValueError( - 'expected units of degrees, got "%s"' % q1._dimensionality + f'expected units of degrees, got "{q1._dimensionality}"' ) return unit_registry['radian'].dimensionality p_dict[np.radians] = _d_radians @@ -353,7 +346,7 @@ def _d_degrees(q1, out=None): assert q1.units == unit_registry['radian'] except AssertionError: raise ValueError( - 'expected units of radians, got "%s"' % q1._dimensionality + f'expected units of radians, got "{q1._dimensionality}"' ) return unit_registry['degree'].dimensionality p_dict[np.degrees] = _d_degrees @@ -377,7 +370,7 @@ def _d_trig(q1, out=None): assert q1.units == unit_registry['radian'] except AssertionError: raise ValueError( - 'expected units of radians, got "%s"' % q1._dimensionality + f'expected units of radians, got "{q1._dimensionality}"' ) return Dimensionality() p_dict[np.sin] = _d_trig diff --git a/quantities/markup.py b/quantities/markup.py index d8d4284..ffee851 100644 --- a/quantities/markup.py +++ b/quantities/markup.py @@ -61,12 +61,12 @@ def format_units(udict): u = key.symbol if d>0: if d != 1: - u = u + ('**%s'%d).rstrip('0').rstrip('.') + u = u + f'**{d}'.rstrip('0').rstrip('.') num.append(u) elif d<0: d = -d if d != 1: - u = u + ('**%s'%d).rstrip('0').rstrip('.') + u = u + f'**{d}'.rstrip('0').rstrip('.') den.append(u) res = '*'.join(num) if len(den): @@ -156,6 +156,6 @@ def format_units_html(udict,font='%s',mult=r'⋅',paren=False): # Remove multiplication signs res = re.sub(r'\*',mult,res) if paren and not compound: - res = '(%s)' % res + res = f'({res})' res = font % res return res diff --git a/quantities/quantity.py b/quantities/quantity.py index 612992e..c17001f 100644 --- a/quantities/quantity.py +++ b/quantities/quantity.py @@ -22,8 +22,7 @@ def validate_unit_quantity(value): assert value.magnitude == 1 except AssertionError: raise ValueError( - 'units must be a scalar Quantity with unit magnitude, got %s'\ - %value + f'units must be a scalar Quantity with unit magnitude, got {value}' ) return value @@ -40,8 +39,7 @@ def validate_dimensionality(value): return value.copy() else: raise TypeError( - 'units must be a quantity, string, or dimensionality, got %s'\ - %type(value) + f'units must be a quantity, string, or dimensionality, got {type(value)}' ) def get_conversion_factor(from_u, to_u): @@ -187,8 +185,7 @@ def units(self, units): cf = get_conversion_factor(from_u, to_u) except AssertionError: raise ValueError( - 'Unable to convert between units of "%s" and "%s"' - %(from_u._dimensionality, to_u._dimensionality) + f'Unable to convert between units of "{from_u._dimensionality}" and "{to_u._dimensionality}"' ) mag = self.magnitude mag *= cf @@ -204,7 +201,7 @@ def rescale(self, units=None, dtype=None): try: return self.rescale_preferred() except Exception as e: - raise Exception('No argument passed to `.rescale` and %s' % e) + raise Exception(f'No argument passed to `.rescale` and {e}') to_dims = validate_dimensionality(units) if dtype is None: dtype = self.dtype @@ -216,8 +213,7 @@ def rescale(self, units=None, dtype=None): cf = get_conversion_factor(from_u, to_u) except AssertionError: raise ValueError( - 'Unable to convert between units of "%s" and "%s"' - %(from_u._dimensionality, to_u._dimensionality) + f'Unable to convert between units of "{from_u._dimensionality}" and "{to_u._dimensionality}"' ) new_magnitude = cf*self.magnitude dtype = np.result_type(dtype, new_magnitude) @@ -277,9 +273,9 @@ def __array_prepare__(self, obj, context=None): res._dimensionality = p_dict[uf](*objs) except KeyError: raise ValueError( - """ufunc %r not supported by quantities + f"""ufunc {uf!r} not supported by quantities please file a bug report at https://github.com/python-quantities - """ % uf + """ ) return res @@ -367,9 +363,7 @@ def __round__(self, decimals=0): @with_doc(np.ndarray.__repr__) def __repr__(self): - return '%s * %s'%( - repr(self.magnitude), self.dimensionality.string - ) + return f'{repr(self.magnitude)} * {self.dimensionality.string}' @with_doc(np.ndarray.__str__) def __str__(self): @@ -377,7 +371,7 @@ def __str__(self): dims = self.dimensionality.unicode else: dims = self.dimensionality.string - return '%s %s'%(str(self.magnitude), dims) + return f'{str(self.magnitude)} {dims}' if tuple(map(int, np.__version__.split('.')[:2])) >= (1, 14): # in numpy 1.14 the formatting of scalar values was changed diff --git a/quantities/registry.py b/quantities/registry.py index ec520e8..e728b75 100644 --- a/quantities/registry.py +++ b/quantities/registry.py @@ -21,7 +21,7 @@ def __getitem__(self, string): except NameError: # could return self['UnitQuantity'](string) raise LookupError( - 'Unable to parse units: "%s"'%string + f'Unable to parse units: "{string}"' ) def __setitem__(self, string, val): @@ -32,8 +32,7 @@ def __setitem__(self, string, val): if val == self.__context[string]: return raise KeyError( - '%s has already been registered for %s' - % (string, self.__context[string]) + f'{string} has already been registered for {self.__context[string]}' ) self.__context[string] = val diff --git a/quantities/tests/common.py b/quantities/tests/common.py index fb5d974..d42bb09 100644 --- a/quantities/tests/common.py +++ b/quantities/tests/common.py @@ -20,7 +20,7 @@ def assertQuantityEqual(self, q1, q2, msg=None, delta=None): precision. """ delta = 1e-5 if delta is None else delta - msg = '' if msg is None else ' (%s)' % msg + msg = '' if msg is None else f' ({msg})' q1 = Quantity(q1) q2 = Quantity(q2) @@ -30,8 +30,7 @@ def assertQuantityEqual(self, q1, q2, msg=None, delta=None): ) if not np.all(np.abs(q1.magnitude - q2.magnitude) < delta): raise self.failureException( - "Magnitudes differ by more than %g (%s vs %s)%s" - % (delta, q1.magnitude, q2.magnitude, msg) + f"Magnitudes differ by more than {delta:g} ({q1.magnitude} vs {q2.magnitude}){msg}" ) d1 = getattr(q1, '_dimensionality', None) diff --git a/quantities/tests/test_units.py b/quantities/tests/test_units.py index 2bbbf93..6abacb6 100644 --- a/quantities/tests/test_units.py +++ b/quantities/tests/test_units.py @@ -17,7 +17,7 @@ def setunits(u, v): u.units = v def inplace(op, u, val): - getattr(u, '__i%s__'%op)(val) + getattr(u, f'__i{op}__')(val) self.assertRaises(AttributeError, setunits, pq.m, pq.ft) self.assertRaises(TypeError, inplace, 'add', pq.m, pq.m) diff --git a/quantities/umath.py b/quantities/umath.py index 16bc412..260b5cc 100644 --- a/quantities/umath.py +++ b/quantities/umath.py @@ -344,8 +344,7 @@ def arctan2(x1, x2, out=None): if x1._dimensionality.simplified != x2._dimensionality.simplified: raise ValueError( - 'x1 and x2 must have identical units, got "%s" and "%s"'\ - % (str(x1._dimensionality), str(x2._dimensionality)) + f'x1 and x2 must have identical units, got "{str(x1._dimensionality)}" and "{str(x2._dimensionality)}"' ) return Quantity( @@ -369,8 +368,7 @@ def hypot(x1, x2, out = None): if x1._dimensionality != x2._dimensionality: raise ValueError( - 'x1 and x2 must have identical units, got "%s" and "%s"'\ - % (str(x1._dimensionality), str(x2._dimensionality)) + f'x1 and x2 must have identical units, got "{str(x1._dimensionality)}" and "{str(x2._dimensionality)}"' ) return Quantity( diff --git a/quantities/uncertainquantity.py b/quantities/uncertainquantity.py index ad6d4c8..d1d6c32 100644 --- a/quantities/uncertainquantity.py +++ b/quantities/uncertainquantity.py @@ -184,11 +184,7 @@ def __str__(self): dims = self.dimensionality.unicode else: dims = self.dimensionality.string - s = '%s %s\n+/-%s (1 sigma)'%( - str(self.magnitude), - dims, - str(self.uncertainty) - ) + s = f'{str(self.magnitude)} {dims}\n+/-{str(self.uncertainty)} (1 sigma)' if markup.config.use_unicode: return s.replace('+/-', '±').replace(' sigma', 'σ') return s diff --git a/quantities/unitquantity.py b/quantities/unitquantity.py index d5487fc..e8023eb 100644 --- a/quantities/unitquantity.py +++ b/quantities/unitquantity.py @@ -35,13 +35,12 @@ def __new__( try: assert isinstance(name, str) except AssertionError: - raise TypeError('name must be a string, got %s (not unicode)'%name) + raise TypeError(f'name must be a string, got {name} (not unicode)') try: assert symbol is None or isinstance(symbol, str) except AssertionError: raise TypeError( - 'symbol must be a string, ' - 'got %s (u_symbol can be unicode)'%symbol + f'symbol must be a string, got {symbol} (u_symbol can be unicode)' ) ret = numpy.array(1, dtype='d').view(cls) @@ -139,29 +138,27 @@ def units(self, units): def __repr__(self): ref = self._definition if ref: - ref = ', %s * %s'%(str(ref.magnitude), ref.dimensionality.string) + ref = f', {str(ref.magnitude)} * {ref.dimensionality.string}' else: ref = '' symbol = self._symbol - symbol = ', %s'%(repr(symbol)) if symbol else '' + symbol = f', {repr(symbol)}' if symbol else '' if markup.config.use_unicode: u_symbol = self._u_symbol - u_symbol = ', %s'%(repr(u_symbol)) if u_symbol else '' + u_symbol = f', {repr(u_symbol)}' if u_symbol else '' else: u_symbol = '' - return '%s(%s%s%s%s)'%( - self.__class__.__name__, repr(self.name), ref, symbol, u_symbol - ) + return f'{self.__class__.__name__}({repr(self.name)}{ref}{symbol}{u_symbol})' @with_doc(Quantity.__str__, use_header=False) def __str__(self): if self.u_symbol != self.name: if markup.config.use_unicode: - s = '1 %s (%s)'%(self.u_symbol, self.name) + s = f'1 {self.u_symbol} ({self.name})' else: - s = '1 %s (%s)'%(self.symbol, self.name) + s = f'1 {self.symbol} ({self.name})' else: - s = '1 %s'%self.name + s = f'1 {self.name}' return s @@ -381,14 +378,14 @@ def __init__(self, name): @with_doc(UnitQuantity.__add__, use_header=False) def __repr__(self): - return '1 %s'%self.name + return f'1 {self.name}' @property def name(self): if markup.config.use_unicode: - return '(%s)'%(markup.superscript(self._name)) + return f'({markup.superscript(self._name)})' else: - return '(%s)'%self._name + return f'({self._name})' def __reduce__(self): """ @@ -476,7 +473,7 @@ def set_default_units( try: assert system in ('si', 'cgs') except AssertionError: - raise ValueError('system must be "SI" or "cgs", got "%s"' % system) + raise ValueError(f'system must be "SI" or "cgs", got "{system}"') if system == 'si': UnitCurrent.set_default_unit('A') UnitLength.set_default_unit('m')