8000 fix #854: use f-string everywhere · larray-project/larray@85bd7ef · GitHub
[go: up one dir, main page]

Skip to content

Commit 85bd7ef

Browse files
committed
fix #854: use f-string everywhere
1 parent 4a8e390 commit 85bd7ef

25 files changed

+260
-258
lines changed

doc/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
# sys.path.insert(0, os.path.abspath('../../'))
2424

2525
import larray
26-
print("larray: {}, {}".format(larray.__version__, larray.__file__))
26+
print(f"larray: {larray.__version__}, {larray.__file__}")
2727

2828
# -- General configuration ------------------------------------------------
2929

larray/core/array.py

Lines changed: 47 additions & 46 deletions
Large diffs are not rendered by default.

larray/core/axis.py

Lines changed: 47 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,8 @@ def __init__(self, labels, name=None):
100100
if isinstance(name, str) and not name_is_python_str:
101101
name = str(name)
102102
if name is not None and not isinstance(name, (int, str)):
103-
raise TypeError("Axis name should be None, int or str but is: %s (%s)" % (name, type(name).__name__))
103+
nametype = type(name).__name__
104+
raise TypeError(f"Axis name should be None, int or str but is: {name} ({nametype})")
104105
self.name = name
105106
self._labels = None
106107
self.__mapping = None
@@ -349,12 +350,12 @@ def split(self, sep='_', names=None, regex=None, return_labels=False):
349350
if self.name is None:
350351
names = None
351352
elif sep not in self.name:
352-
raise ValueError('{} not found in self name ({})'.format(sep, self.name))
353+
raise ValueError(f'{sep} not found in self name ({self.name})')
353354
else:
354355
names = self.name.split(sep)
355356
elif isinstance(names, str):
356357
if sep not in names:
357-
raise ValueError('{} not found in names ({})'.format(sep, names))
358+
raise ValueError(f'{sep} not found in names ({names})')
358359
else:
359360
names = names.split(sep)
360361
else:
@@ -470,17 +471,19 @@ def _group(self, *args, **kwargs):
470471
"""
471472
name = kwargs.pop('name', None)
472473
if kwargs:
473-
raise ValueError("invalid keyword argument(s): %s" % list(kwargs.keys()))
474+
invalid_kwargs = list(kwargs.keys())
475+
raise ValueError(f"invalid keyword argument(s): {invalid_kwargs}")
474476
key = args[0] if len(args) == 1 else args
475477
return self[key] >> name if name else self[key]
476478

477479
def group(self, *args, **kwargs):
478480
group_name = kwargs.pop('name', None)
479481
key = args[0] if len(args) == 1 else args
480-
syntax = '{}[{}]'.format(self.name if self.name else 'axis', key)
482+
name = self.name if self.name else 'axis'
483+
syntax = f'{name}[{key}]'
481484
if group_name is not None:
482-
syntax += ' >> {}'.format(repr(group_name))
483-
raise NotImplementedError('Axis.group is deprecated. Use {} instead.'.format(syntax))
485+
syntax += f' >> {repr(group_name)}'
486+
raise NotImplementedError(f'Axis.group is deprecated. Use {syntax} instead.')
484487

485488
def all(self, name=None):
486489
r"""
@@ -493,8 +496,7 @@ def all(self, name=None):
493496
"""
494497
axis_name = self.name if self.name else 'axis'
495498
group_name = name if name else 'all'
496-
raise NotImplementedError('Axis.all is deprecated. Use {}[:] >> {} instead.'
497-
.format(axis_name, repr(group_name)))
499+
raise NotImplementedError(f'Axis.all is deprecated. Use {axis_name}[:] >> {repr(group_name)} instead.')
498500

499501
# TODO: make this method private
500502
def subaxis(self, key):
@@ -939,7 +941,7 @@ def index(self, key):
939941
else:
940942
# the first mapping[key] above will cover most cases.
941943
# This code path is only used if the key was g 10000 iven in "non normalized form"
942-
assert np.isscalar(key), "%s (%s) is not scalar" % (key, type(key))
944+
assert np.isscalar(key), f"{key} ({type(key)}) is not scalar"
943945
# key is scalar (integer, float, string, ...)
944946
if self._is_key_type_compatible(key):
945947
return mapping[key]
@@ -963,7 +965,7 @@ def __str__(self):
963965

964966
def __repr__(self):
965967
labels = len(self) if self.iswildcard else list(self.labels)
966-
return 'Axis(%r, %r)' % (labels, self.name)
968+
return f'Axis({labels!r}, {self.name!r})'
967969

968970
def labels_summary(self):
969971
r"""
@@ -983,7 +985,7 @@ def _binop(opname):
983985
r"""
984986
Method factory to create binary operators special methods.
985987
"""
986-
fullname = '__%s__' % opname
988+
fullname = f'__{opname}__'
987989

988990
def opmethod(self, other):
989991
# give a chance to AxisCollection.__rXXX__ ops to trigger
@@ -1089,13 +1091,13 @@ def replace(self, old, new=None):
10891091
new = list(old.values())
10901092
old = list(old.keys())
10911093
elif np.isscalar(old):
1092-
assert new is not None and np.isscalar(new), "%s is not a scalar but a %s" % (new, type(new).__name__)
1094+
assert new is not None and np.isscalar(new), f"{new} is not a scalar but a {type(new).__name__}"
10931095
old = [old]
10941096
new = [new]
10951097
else:
10961098
seq = (tuple, list, np.ndarray)
1097-
assert isinstance(old, seq), "%s is not a sequence but a %s" % (old, type(old).__name__)
1098-
assert isinstance(new, seq), "%s is not a sequence but a %s" % (new, type(new).__name__)
1099+
assert isinstance(old, seq), f"{old} is not a sequence but a {type(old).__name__}"
1100+
assert isinstance(new, seq), f"{new} is not a sequence but a {type(new).__name__}"
10991101
assert len(old) == len(new)
11001102
# using object dtype because new labels length can be larger than the fixed str length in the self.labels array
11011103
labels = self.labels.astype(object)
@@ -1470,9 +1472,9 @@ def __init__(self, axes=None):
14701472
dupe_axes = list(duplicates(axes))
14711473
if dupe_axes:
14721474
axis = dupe_axes[0]
1473-
raise ValueError("Cannot have multiple occurrences of the same axis object in a collection ('%s' -- %s "
1474-
"with id %d). Several axes with the same name are allowed though (but not recommended)."
1475-
% (axis.name, axis.labels_summary(), id(axis)))
1475+
raise ValueError(f"Cannot have multiple occurrences of the same axis object in a collection ('{axis.name}'"
1476+
f" -- {axis.labels_summary()} with id {id(axis):d}). Several axes with the same name are "
1477+
f"allowed though (but not recommended).")
14761478
self._list = axes
14771479
self._map = {axis.name: axis for axis in axes if axis.name is not None}
14781480

@@ -1592,7 +1594,7 @@ def __getitem__(self, key):
15921594
# transform ValueError to KeyError
15931595
except ValueError:
15941596
if key.name is None:
1595-
raise KeyError("axis '%s' not found in %s" % (key, self))
1597+
raise KeyError(f"axis '{key}' not found in {self}")
15961598
else:
15971599
# we should NOT check that the object is the same, so that we can use AxisReference objects to
15981600
# target real axes
@@ -1616,13 +1618,13 @@ def __getitem__(self, key):
16161618
elif isinstance(key, slice):
16171619
return AxisCollection(self._list[key])
16181620
elif key is None:
1619-
raise KeyError("axis '%s' not found in %s" % (key, self))
1621+
raise KeyError(f"axis '{key}' not found in {self}")
16201622
else:
16211623
assert isinstance(key, str), type(key)
16221624
if key in self._map:
16231625
return self._map[key]
16241626
else:
1625-
raise KeyError("axis '%s' not found in %s" % (key, self))
1627+
raise KeyError(f"axis '{key}' not found in {self}")
16261628

16271629
def _ipython_key_completions_(self):
16281630
return list(self._map.keys())
@@ -1664,9 +1666,9 @@ def get_by_pos(self, key, i):
16641666
if res.iscompatible(key):
16651667
return res
16661668
else:
1667-
raise ValueError("axis %s is not compatible with %s" % (res, key))
1669+
raise ValueError(f"axis {res} is not compatible with {key}")
16681670
# XXX: KeyError instead?
1669-
raise ValueError("axis %s not found in %s" % (key, self))
1671+
raise ValueError(f"axis {key} not found in {self}")
16701672
else:
16711673
return self[key]
16721674

@@ -1827,15 +1829,17 @@ def __len__(self):
18271829
ndim = property(__len__)
18281830

18291831
def __str__(self):
1830-
return "{%s}" % ', '.join(self.display_names)
1832+
names = ', '.join(self.display_names)
1833+
return f"{{{names}}}"
18311834

18321835
def __repr__(self):
18331836
if len(self):
18341837
repr_per_axis = [repr(axis) for axis in self._list]
1835-
axes_repr = "\n {}\n".format(',\n '.join(repr_per_axis))
1838+
axes_repr = ',\n '.join(repr_per_axis)
1839+
axes_repr = f"\n {axes_repr}\n"
18361840
else:
18371841
axes_repr = ""
1838-
return "AxisCollection([{}])".format(axes_repr)
1842+
return f"AxisCollection([{axes_repr}])"
18391843

18401844
# TODO: kill name argument (does not seem to be used anywhere
18411845
def get(self, key, default=None, name=None):
@@ -2006,7 +2010,7 @@ def check_compatible(self, axes):
20062010
for i, axis in enumerate(axes):
20072011
local_axis = self.get_by_pos(axis, i)
20082012
if not local_axis.iscompatible(axis):
2009-
raise ValueError("incompatible axes:\n{!r}\nvs\n{!r}".format(axis, local_axis))
2013+
raise ValueError(f"incompatible axes:\n{axis!r}\nvs\n{local_axis!r}")
20102014

20112015
# XXX: deprecate method (functionality is duplicated in union)?
20122016
# I am not so sure anymore we need to actually deprecate the method: having both methods with the same
@@ -2046,7 +2050,7 @@ def extend(self, axes, validate=True, replace_wildcards=False):
20462050
"""
20472051
# axes should be a sequence
20482052
if not isinstance(axes, (tuple, list, AxisCollection)):
2049-
raise TypeError("AxisCollection can only be extended by a sequence of Axis, not %s" % type(axes).__name__)
2053+
raise TypeError(f"AxisCollection can only be extended by a sequence of Axis, not {type(axes).__name__}")
20502054
# check that common axes are the same
20512055
# if validate:
20522056
# self.check_compatible(axes)
@@ -2070,7 +2074,7 @@ def get_axis(col, i, axis):
20702074
else:
20712075
# check that common axes are the same
20722076
if validate and not old_axis.iscompatible(axis):
2073-
raise ValueError("incompatible axes:\n%r\nvs\n%r" % (axis, old_axis))
2077+
raise ValueError(f"incompatible axes:\n{axis!r}\nvs\n{old_axis!r}")
20742078
if replace_wildcards and old_axis.iswildcard:
20752079
self[old_axis] = axis
20762080

@@ -2115,7 +2119,7 @@ def index(self, axis, compatible=False):
21152119
if -len(self) <= axis < len(self):
21162120
return axis
21172121
else:
2118-
raise ValueError("axis %d is not in collection" % axis)
2122+
raise ValueError(f"axis {axis} is not in collection")
21192123
elif isinstance(axis, Axis):
21202124
try:
21212125
# 1) first look for that particular axis object
@@ -2146,7 +2150,7 @@ def index(self, axis, compatible=False):
21462150
else:
21472151
name = axis
21482152
if name is None:
2149-
raise ValueError("%r is not in collection" % axis)
2153+
raise ValueError(f"{axis!r} is not in collection")
21502154
return self.names.index(name)
21512155

21522156
# XXX: we might want to return a new AxisCollection (same question for other inplace operations:
@@ -2327,7 +2331,7 @@ def replace(self, axes_to_replace=None, new_axis=None, inplace=False, **kwargs):
23272331
if isinstance(axes_to_replace, (list, AxisCollection)) and \
23282332
all([isinstance(axis, Axis) for axis in axes_to_replace]):
23292333
if len(axes_to_replace) != len(self):
2330-
raise ValueError('{} axes given as argument, expected {}'.format(len(axes_to_replace), len(self)))
2334+
raise ValueError(f'{len(axes_to_replace)} axes given as argument, expected {len(self)}')
23312335
axes = axes_to_replace
23322336
else:
23332337
axes = self if inplace else self[:]
@@ -2372,11 +2376,11 @@ def _guess_axis(self, axis_key):
23722376
except KeyError:
23732377
continue
23742378
if not valid_axes:
2375-
raise ValueError("%s is not a valid label for any axis" % axis_key)
2379+
raise ValueError(f"{axis_key} is not a valid label for any axis")
23762380
elif len(valid_axes) > 1:
2377-
valid_axes = ', '.join(a.name if a.name is not None else '{{{}}}'.format(self.axes.index(a))
2381+
valid_axes = ', '.join(a.name if a.name is not None else f'{{{self.axes.index(a)}}}'
23782382
for a in valid_axes)
2379-
raise ValueError('%s is ambiguous (valid in %s)' % (axis_key, valid_axes))
2383+
raise ValueError(f'{axis_key} is ambiguous (valid in {valid_axes})')
23802384
return valid_axes[0][axis_key]
23812385

23822386
def set_labels(self, axis=None, labels=None, inplace=False, **kwargs):
@@ -2616,7 +2620,7 @@ def _translate_axis_key_chunk(self, axis_key):
26162620
try:
26172621
axis_pos_key = real_axis.index(axis_key)
26182622
except KeyError:
2619-
raise ValueError("%r is not a valid label for any axis" % axis_key)
2623+
raise ValueError(f"{axis_key!r} is not a valid label for any axis")
26202624
return real_axis.i[axis_pos_key]
26212625
except KeyError:
26222626
# axis associated with axis_key may not belong to self.
@@ -2636,13 +2640,13 @@ def _translate_axis_key_chunk(self, axis_key):
26362640
except KeyError:
26372641
continue
26382642
if not valid_axes:
2639-
raise ValueError("%r is not a valid label for any axis" % axis_key)
2643+
raise ValueError(f"{axis_key!r} is not a valid label for any axis")
26402644
elif len(valid_axes) > 1:
26412645
# TODO: make an AxisCollection.display_name(axis) method out of this
26422646
# valid_axes = ', '.join(self.display_name(axis) for a in valid_axes)
2643-
valid_axes = ', '.join(a.name if a.name is not None else '{{{}}}'.format(self.index(a))
2647+
valid_axes = ', '.join(a.name if a.name is not None else f'{{{self.index(a)}}}'
26442648
for a in valid_axes)
2645-
raise ValueError('%s is ambiguous (valid in %s)' % (axis_key, valid_axes))
2649+
raise ValueError(f'{axis_key} is ambiguous (valid in {valid_axes})')
26462650
return valid_axes[0].i[axis_pos_key]
26472651

26482652
def _translate_axis_key(self, axis_key):
@@ -2755,8 +2759,7 @@ def _key_to_igroups(self, key):
27552759
if isinstance(axis_key, Array) and np.issubdtype(axis_key.dtype, np.bool_):
27562760
extra_key_axes = axis_key.axes - self
27572761
if extra_key_axes:
2758-
raise ValueError("boolean subset key contains more axes ({}) than array ({})"
2759-
.format(axis_key.axes, self))
2762+
raise ValueError(f"boolean subset key contains more axes ({axis_key.axes}) than array ({self})")
27602763
# nonzero (currently) returns a tuple of IGroups containing 1D Arrays (one IGroup per axis)
27612764
nonboolkey.extend(axis_key.nonzero())
27622765
else:
@@ -2997,7 +3000,7 @@ def display_names(self):
29973000
['a', 'b*', '{2}', '{3}*']
29983001
"""
29993002
def display_name(i, axis):
3000-
name = axis.name if axis.name is not None else '{%d}' % i
3003+
name = axis.name if axis.name is not None else f'{{{i}}}'
30013004
return (name + '*') if axis.iswildcard else name
30023005

30033006
return [display_name(i, axis) for i, axis in enumerate(self._list)]
@@ -3114,7 +3117,7 @@ def info(self):
31143117
sex [2]: 'M' 'F'
31153118
time [4]: 2007 2008 2009 2010
31163119
"""
3117-
lines = [" %s [%d]: %s" % (name, len(axis), axis.labels_summary())
3120+
lines = [f" {name} [{len(axis)}]: {axis.labels_summary()}"
31183121
for name, axis in zip(self.display_names, self._list)]
31193122
shape = " x ".join(str(s) for s in self.shape)
31203123
return ReprString('\n'.join([shape] + lines))
@@ -3576,7 +3579,7 @@ def index(self, key):
35763579
raise NotImplementedError("an AxisReference (X.) cannot translate labels")
35773580

35783581
def __repr__(self):
3579-
return 'AxisReference(%r)' % self.name
3582+
return f'AxisReference({self.name!r})'
35803583

35813584
def evaluate(self, context):
35823585
r"""

larray/core/expr.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def _binop(opname):
77
def opmethod(self, other):
88
return BinaryOp(opname, self, other)
99

10-
opmethod.__name__ = '__{}__'.format(opname)
10+
opmethod.__name__ = f'__{opname}__'
1111
return opmethod
1212

1313
__matmul__ = _binop('matmul')
@@ -51,7 +51,7 @@ def _unaryop(opname):
5151
def opmethod(self):
5252
return UnaryOp(opname, self)
5353

54-
opmethod.__name__ = '__{}__'.format(opname)
54+
opmethod.__name__ = f'__{opname}__'
5555
return opmethod
5656

5757
# unary ops do not need broadcasting so do not need to be overridden
@@ -71,23 +71,23 @@ def expr_eval(expr, context):
7171

7272
class BinaryOp(ExprNode):
7373
def __init__(self, op, expr1, expr2):
74-
self.op = op
74+
self.opname = f'__{op}__'
7575
self.expr1 = expr1
7676
self.expr2 = expr2
7777

7878
def evaluate(self, context):
7979
# TODO: implement eval via numexpr
8080
expr1 = expr_eval(self.expr1, context)
8181
expr2 = expr_eval(self.expr2, context)
82-
return getattr(expr1, '__{}__'.format(self.op))(expr2)
82+
return getattr(expr1, self.opname)(expr2)
8383

8484

8585
class UnaryOp(ExprNode):
8686
def __init__(self, op, expr):
87-
self.op = op
87+
self.opname = f'__{op}__'
8888
self.expr = expr
8989

9090
def evaluate(self, context):
9191
# TODO: implement eval via numexpr
9292
expr = expr_eval(self.expr, context)
93-
return getattr(expr, '__{}__'.format(self.op))()
93+
return getattr(expr, self.opname)()

0 commit comments

Comments
 (0)
0