Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b5d11ae

Browse files
authored
Merge pull request #2706 from devitocodes/modernize-string-formatting
misc: switch to f-string throughout
2 parents cfc5a08 + c8c2ccf commit b5d11ae

File tree

12 files changed

+100
-102
lines changed

12 files changed

+100
-102
lines changed

devito/arch/compiler.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -681,8 +681,9 @@ def __init_finalize__(self, **kwargs):
681681
proc_link_flags.extend(['-Xcompiler', '-pthread'])
682682
elif i.startswith('-Wl'):
683683
# E.g., `-Wl,-rpath` -> `-Xcompiler "-Wl\,-rpath"`
684+
escaped_i = i.replace(",", r"\\,")
684685
proc_link_flags.extend([
685-
'-Xcompiler', '"%s"' % i.replace(',', r'\,')
686+
'-Xcompiler', f'"{escaped_i}"'
686687
])
687688
else:
688689
proc_link_flags.append(i)

devito/data/allocators.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def alloc(self, shape, dtype, padding=0):
103103

104104
padleft_pointer, memfree_args = self._alloc_C_libcall(size, ctype)
105105
if padleft_pointer is None:
106-
raise RuntimeError("Unable to allocate %d elements in memory" % size)
106+
raise RuntimeError(f"Unable to allocate {size} elements in memory")
107107

108108
# Compute the pointer to the user data
109109
padleft_bytes = padleft * ctypes.sizeof(ctype)
@@ -375,11 +375,11 @@ def __init__(self, numpy_array):
375375

376376
def alloc(self, shape, dtype, padding=0):
377377
assert shape == self.numpy_array.shape, \
378-
"Provided array has shape %s. Expected %s" %\
379-
(str(self.numpy_array.shape), str(shape))
378+
(f"Provided array has shape {str(self.numpy_array.shape)}. "
379+
f"Expected {str(shape)}")
380380
assert dtype == self.numpy_array.dtype, \
381-
"Provided array has dtype %s. Expected %s" %\
382-
(str(self.numpy_array.dtype), str(dtype))
381+
(f"Provided array has dtype {str(self.numpy_array.dtype)}. "
382+
f"Expected {str(dtype)}")
383383

384384
return (self.numpy_array, None)
385385

@@ -405,11 +405,11 @@ def register_allocator(name, allocator):
405405
Register a custom MemoryAllocator.
406406
"""
407407
if not isinstance(name, str):
408-
raise TypeError("name must be a str, not `%s`" % type(name))
408+
raise TypeError(f"name must be a str, not `{type(name)}`)")
409409
if name in custom_allocators:
410-
raise ValueError("A MemoryAllocator for `%s` already exists" % name)
410+
raise ValueError(f"A MemoryAllocator for `{name}` already exists")
411411
if not isinstance(allocator, AbstractMemoryAllocator):
412-
raise TypeError("Expected a MemoryAllocator, not `%s`" % type(allocator))
412+
raise TypeError(f"Expected a MemoryAllocator, not `{type(allocator)}`")
413413

414414
custom_allocators[name] = allocator
415415

devito/data/data.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def _global(self, glb_idx, decomposition):
157157
if self._is_decomposed:
158158
raise ValueError("Cannot derive a decomposed view from a decomposed Data")
159159
if len(decomposition) != self.ndim:
160-
raise ValueError("`decomposition` should have ndim=%d entries" % self.ndim)
160+
raise ValueError(f"`decomposition` should have ndim={self.ndim} entries")
161161
ret = self[glb_idx]
162162
ret._decomposition = decomposition
163163
ret._is_distributed = any(i is not None for i in decomposition)
@@ -407,7 +407,7 @@ def __setitem__(self, glb_idx, val, comm_type):
407407
"other data ")
408408
super().__setitem__(glb_idx, val)
409409
else:
410-
raise ValueError("Cannot insert obj of type `%s` into a Data" % type(val))
410+
raise ValueError(f"Cannot insert obj of type `{type(val)}` into a Data")
411411

412412
def _normalize_index(self, idx):
413413
if isinstance(idx, np.ndarray):

devito/finite_differences/differentiable.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def __getattr__(self, name):
189189
"""
190190
if name in self._fd:
191191
return self._fd[name][0](self)
192-
raise AttributeError("%r object has no attribute %r" % (self.__class__, name))
192+
raise AttributeError(f"{self.__class__!r} object has no attribute {name!r}")
193193

194194
# Override SymPy arithmetic operators
195195
@call_highest_priority('__radd__')
@@ -324,7 +324,7 @@ def laplacian(self, shift=None, order=None, method='FD', **kwargs):
324324
order = order or self.space_order
325325
space_dims = self.root_dimensions
326326
shift_x0 = make_shift_x0(shift, (len(space_dims),))
327-
derivs = tuple('d%s2' % d.name for d in space_dims)
327+
derivs = tuple(f'd{d.name}2' for d in space_dims)
328328
return Add(*[getattr(self, d)(x0=shift_x0(shift, space_dims[i], None, i),
329329
method=method, fd_order=order, w=w)
330330
for i, d in enumerate(derivs)])
@@ -352,8 +352,8 @@ def div(self, shift=None, order=None, method='FD', **kwargs):
352352
space_dims = self.root_dimensions
353353
shift_x0 = make_shift_x0(shift, (len(space_dims),))
354354
order = order or self.space_order
355-
return Add(*[getattr(self, 'd%s' % d.name)(x0=shift_x0(shift, d, None, i),
356-
fd_order=order, method=method, w=w)
355+
return Add(*[getattr(self, f'd{d.name}')(x0=shift_x0(shift, d, None, i),
356+
fd_order=order, method=method, w=w)
357357
for i, d in enumerate(space_dims)])
358358

359359
def grad(self, shift=None, order=None, method='FD', **kwargs):
@@ -380,11 +380,11 @@ def grad(self, shift=None, order=None, method='FD', **kwargs):
380380
shift_x0 = make_shift_x0(shift, (len(space_dims),))
381381
order = order or self.space_order
382382
w = kwargs.get('weights', kwargs.get('w'))
383-
comps = [getattr(self, 'd%s' % d.name)(x0=shift_x0(shift, d, None, i),
384-
fd_order=order, method=method, w=w)
383+
comps = [getattr(self, f'd{d.name}')(x0=shift_x0(shift, d, None, i),
384+
fd_order=order, method=method, w=w)
385385
for i, d in enumerate(space_dims)]
386386
vec_func = VectorTimeFunction if self.is_TimeDependent else VectorFunction
387-
return vec_func(name='grad_%s' % self.name, time_order=self.time_order,
387+
return vec_func(name=f'grad_{self.name}', time_order=self.time_order,
388388
space_order=self.space_order, components=comps, grid=self.grid)
389389

390390
def biharmonic(self, weight=1):
@@ -393,7 +393,7 @@ def biharmonic(self, weight=1):
393393
all spatial Dimensions Laplace(weight * Laplace (self))
394394
"""
395395
space_dims = self.root_dimensions
396-
derivs = tuple('d%s2' % d.name for d in space_dims)
396+
derivs = tuple(f'd{d.name}2' for d in space_dims)
397397
return Add(*[getattr(self.laplace * weight, d) for d in derivs])
398398

399399
def diff(self, *symbols, **assumptions):

devito/ir/support/basic.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def __init__(self, access, mode, timestamp, ispace=null_ispace):
232232

233233
def __repr__(self):
234234
mode = '\033[1;37;31mW\033[0m' if self.is_write else '\033[1;37;32mR\033[0m'
235-
return "%s<%s,[%s]>" % (mode, self.name, ', '.join(str(i) for i in self))
235+
return f"{mode}<{self.name},[{', '.join(str(i) for i in self)}]>"
236236

237237
def __eq__(self, other):
238238
if not isinstance(other, TimedAccess):
@@ -295,7 +295,7 @@ def is_regular(self):
295295

296296
def __lt__(self, other):
297297
if not isinstance(other, TimedAccess):
298-
raise TypeError("Cannot compare with object of type %s" % type(other))
298+
raise TypeError(f"Cannot compare with object of type {type(other)}")
299299
if self.directions != other.directions:
300300
raise TypeError("Cannot compare due to mismatching `direction`")
301301
if self.intervals != other.intervals:
@@ -529,7 +529,7 @@ def __init__(self, source, sink):
529529
self.sink = sink
530530

531531
def __repr__(self):
532-
return "%s -- %s" % (self.source, self.sink)
532+
return f"{self.source} -- {self.sink}"
533533

534534
def __eq__(self, other):
535535
# If the timestamps are equal in `self` (ie, an inplace dependence) then
@@ -639,7 +639,7 @@ class Dependence(Relation, CacheInstances):
639639
"""
640640

641641
def __repr__(self):
642-
return "%s -> %s" % (self.source, self.sink)
642+
return f"{self.source} -> {self.sink}"
643643

644644
@cached_property
645645
def cause(self):
@@ -1042,26 +1042,27 @@ def __repr__(self):
10421042
tracked = filter_sorted(set(self.reads) | set(self.writes),
10431043
key=lambda i: i.name)
10441044
maxlen = max(1, max([len(i.name) for i in tracked]))
1045-
out = "{:>%d} => W : {}\n{:>%d} R : {}" % (maxlen, maxlen)
1045+
out = f"{{:>{maxlen}}} => W : {{}}\n{{:>{maxlen}}} R : {{}}"
10461046
pad = " "*(maxlen + 9)
10471047
reads = [self.getreads(i) for i in tracked]
10481048
for i, r in enumerate(list(reads)):
10491049
if not r:
10501050
reads[i] = ''
10511051
continue
1052-
first = "%s" % tuple.__repr__(r[0])
1053-
shifted = "\n".join("%s%s" % (pad, tuple.__repr__(j)) for j in r[1:])
1054-
shifted = "%s%s" % ("\n" if shifted else "", shifted)
1052+
first = f"{tuple.__repr__(r[0])}"
1053+
shifted = "\n".join(f"{pad}{tuple.__repr__(j)}" for j in r[1:])
1054+
newline_prefix = '\n' if shifted else ''
1055+
shifted = f"{newline_prefix}{shifted}"
10551056
reads[i] = first + shifted
10561057
writes = [self.getwrites(i) for i in tracked]
10571058
for i, w in enumerate(list(writes)):
10581059
if not w:
10591060
writes[i] = ''
10601061
continue
1061-
first = "%s" % tuple.__repr__(w[0])
1062-
shifted = "\n".join("%s%s" % (pad, tuple.__repr__(j)) for j in w[1:])
1063-
shifted = "%s%s" % ("\n" if shifted else "", shifted)
1064-
writes[i] = '\033[1;37;31m%s\033[0m' % (first + shifted)
1062+
first = f"{tuple.__repr__(w[0])}"
1063+
shifted = "\n".join(f"{pad}{tuple.__repr__(j)}" for j in w[1:])
1064+
shifted = f"{chr(10) if shifted else ''}{shifted}"
1065+
writes[i] = f'\033[1;37;31m{first + shifted}\033[0m'
10651066
return "\n".join([out.format(i.name, w, '', r)
10661067
for i, r, w in zip(tracked, reads, writes)])
10671068

@@ -1264,7 +1265,7 @@ def __init__(self, expr, indexeds=None, bases=None, offsets=None):
12641265
self.offsets = offsets
12651266

12661267
def __repr__(self):
1267-
return "ExprGeometry(expr=%s)" % self.expr
1268+
return f"ExprGeometry(expr={self.expr})"
12681269

12691270
def translated(self, other, dims=None):
12701271
"""

devito/logger.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def _set_log_level(level):
5656
Set the level of the Devito logger.
5757
"""
5858
if level not in logger_registry:
59-
raise ValueError("Illegal logging level %s" % level)
59+
raise ValueError(f"Illegal logging level {level}")
6060

6161
logger.setLevel(level)
6262

@@ -150,7 +150,7 @@ def perf(msg, *args, **kwargs):
150150

151151

152152
def hint(msg, *args, **kwargs):
153-
log("Hint: %s" % msg, PERF, *args, **kwargs)
153+
log(f"Hint: {msg}", PERF, *args, **kwargs)
154154

155155

156156
def warning(msg, *args, **kwargs):

devito/operations/interpolators.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def wrapper(interp, *args, **kwargs):
2828
funcs = set().union(*[retrieve_functions(a) for a in args])
2929
so = min({f.space_order for f in funcs if not f.is_SparseFunction} or {r})
3030
if so < r:
31-
raise ValueError("Space order %d too small for interpolation r %d" % (so, r))
31+
raise ValueError(f"Space order {so} too small for interpolation r {r}")
3232
return func(interp, *args, **kwargs)
3333
return wrapper
3434

@@ -122,8 +122,8 @@ def operation(self, **kwargs):
122122
implicit_dims=self.implicit_dims)
123123

124124
def __repr__(self):
125-
return "Interpolation(%s into %s)" % (repr(self.expr),
126-
repr(self.interpolator.sfunction))
125+
return (f"Interpolation({repr(self.expr)} into "
126+
f"{repr(self.interpolator.sfunction)})")
127127

128128

129129
class Injection(UnevaluatedSparseOperation):
@@ -150,7 +150,7 @@ def operation(self, **kwargs):
150150
implicit_dims=self.implicit_dims)
151151

152152
def __repr__(self):
153-
return "Injection(%s into %s)" % (repr(self.expr), repr(self.field))
153+
return f"Injection({repr(self.expr)} into {repr(self.field)})"
154154

155155

156156
class GenericInterpolator(ABC):
@@ -210,7 +210,7 @@ def _gdims(self):
210210
def _cdim(self):
211211
"""Base CustomDimensions used to construct _rdim"""
212212
parent = self.sfunction._sparse_dim
213-
dims = [CustomDimension("r%s%s" % (self.sfunction.name, d.name),
213+
dims = [CustomDimension(f"r{self.sfunction.name}{d.name}",
214214
-self.r+1, self.r, 2*self.r, parent)
215215
for d in self._gdims]
216216
return dims
@@ -552,7 +552,7 @@ def interpolation_coeffs(self):
552552
shape = (self.sfunction.npoint, 2 * self.r)
553553
for r in self._cdim:
554554
dimensions = (self.sfunction._sparse_dim, r)
555-
sf = SubFunction(name="wsinc%s" % r.name, dtype=self.sfunction.dtype,
555+
sf = SubFunction(name=f"wsinc{r.name}", dtype=self.sfunction.dtype,
556556
shape=shape, dimensions=dimensions,
557557
space_order=0, alias=self.sfunction.alias,
558558
parent=None)

devito/operator/profiling.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,9 +393,9 @@ def instrument(self, iet, timer):
393393
if i.dim.is_Time:
394394
# The calls to Advisor's Collection Control API are only for Operators
395395
# with a time loop
396-
mapper[i] = List(header=c.Statement('%s()' % self._api_resume),
396+
mapper[i] = List(header=c.Statement(f'{self._api_resume}()'),
397397
body=i,
398-
footer=c.Statement('%s()' % self._api_pause))
398+
footer=c.Statement(f'{self._api_pause}()'))
399399
return Transformer(mapper).visit(iet)
400400

401401
# Return the IET intact if no time loop is found

devito/parameters.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,16 @@ def wrapper(self, key, value):
4848
if accepted is not None:
4949
tocheck = list(value) if isinstance(value, dict) else [value]
5050
if any(i not in accepted for i in tocheck):
51-
raise ValueError("Illegal configuration parameter (%s, %s). "
52-
"Accepted: %s" % (key, value, str(accepted)))
51+
raise ValueError(f"Illegal configuration parameter ({key}, {value}). "
52+
f"Accepted: {str(accepted)}")
5353
return func(self, key, value)
5454
return wrapper
5555

5656
def _check_key_deprecation(func):
5757
def wrapper(self, key, value=None):
5858
if key in self._deprecated:
59-
warning("Trying to access deprecated config `%s`. Using `%s` instead"
60-
% (key, self._deprecated[key]))
59+
warning(f"Trying to access deprecated config `{key}`. "
60+
f"Using `{self._deprecated[key]}` instead")
6161
key = self._deprecated[key]
6262
return func(self, key, value)
6363
return wrapper
@@ -182,11 +182,11 @@ def init_configuration(configuration=configuration, env_vars_mapper=env_vars_map
182182
mapper = dict(queue)
183183
for k, (v, msg) in env_vars_deprecated.items():
184184
if environ.get(k):
185-
warning("`%s` is deprecated. %s" % (k, msg))
185+
warning(f"`{k}` is deprecated. {msg}")
186186
if environ.get(v):
187-
warning("Both `%s` and `%s` set. Ignoring `%s`" % (k, v, k))
187+
warning(f"Both `{k}` and `{v}` set. Ignoring `{k}`")
188188
else:
189-
warning("Setting `%s=%s`" % (v, environ[k]))
189+
warning(f"Setting `{v}={environ[k]}`")
190190
unprocessed[mapper[v]] = environ[k]
191191
else:
192192
# Attempt reading from the specified configuration file
@@ -264,11 +264,10 @@ def print_defaults():
264264
"""Print the environment variables accepted by Devito, their default value,
265265
as well as all of the accepted values."""
266266
for k, v in env_vars_mapper.items():
267-
info('%s: %s. Default: %s' % (k, configuration._accepted[v],
268-
configuration._defaults[v]))
267+
info(f'{k}: {configuration._accepted[v]}. Default: {configuration._defaults[v]}')
269268

270269

271270
def print_state():
272271
"""Print the current configuration state."""
273272
for k, v in configuration.items():
274-
info('%s: %s' % (k, v))
273+
info(f'{k}: {v}')

devito/types/basic.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -777,7 +777,7 @@ def __init__(self, *args, **kwargs):
777777
pass
778778

779779
def __str__(self):
780-
return "%s(%s)" % (self.name, ', '.join(str(i) for i in self.indices))
780+
return f"{self.name}({', '.join(str(i) for i in self.indices)})"
781781

782782
__repr__ = __str__
783783

@@ -1107,7 +1107,7 @@ def dmap(self):
11071107
return None.
11081108
"""
11091109
if self._mem_mapped:
1110-
return DeviceMap('d_%s' % self.name, shape=self._shape,
1110+
return DeviceMap(f'd_{self.name}', shape=self._shape,
11111111
function=self.function)
11121112
elif self._mem_local:
11131113
return self.indexed
@@ -1175,7 +1175,7 @@ def space(self):
11751175

11761176
@property
11771177
def _C_name(self):
1178-
return "%s_vec" % self.name
1178+
return f"{self.name}_vec"
11791179

11801180
@cached_property
11811181
def _C_symbol(self):

0 commit comments

Comments
 (0)