Skip to content
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

Switch quantities over to f-strings #230

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions quantities/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 12 additions & 19 deletions quantities/dimensionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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

Expand All @@ -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()

Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions quantities/markup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -156,6 +156,6 @@ def format_units_html(udict,font='%s',mult=r'&sdot;',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
24 changes: 9 additions & 15 deletions quantities/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -367,17 +363,15 @@ 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):
if markup.config.use_unicode:
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
Expand Down
5 changes: 2 additions & 3 deletions quantities/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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

Expand Down
5 changes: 2 additions & 3 deletions quantities/tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion quantities/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 2 additions & 4 deletions quantities/umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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(
Expand Down
6 changes: 1 addition & 5 deletions quantities/uncertainquantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 13 additions & 16 deletions quantities/unitquantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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')
Expand Down