Skip to content

Commit 6ce5540

Browse files
authored
Replace all %-substitution and .format() calls with f-strings (#506)
Eliminate all old-style string replacement (`%` substitutions) and explicit `.format()` calls, in favor of equivalent f-strings.
1 parent 2c67877 commit 6ce5540

18 files changed

+57
-65
lines changed

doc/intro.rst

+5-5
Original file line numberDiff line numberDiff line change
@@ -333,11 +333,11 @@ Handlers are given a `progress` object containing a number of useful fields.
333333
For example::
334334

335335
def eval_handler(image, progress):
336-
print('run time so far (secs) = {}'.format(progress.run))
337-
print('estimated time of arrival (secs) = {}'.format(progress.eta))
338-
print('total number of pels to process = {}'.format(progress.tpels))
339-
print('number of pels processed so far = {}'.format(progress.npels))
340-
print('percent complete = {}'.format(progress.percent))
336+
print(f' run = {progress.run} (seconds of run time)')
337+
print(f' eta = {progress.eta} (estimated seconds left)')
338+
print(f' tpels = {progress.tpels} (total number of pels)')
339+
print(f' npels = {progress.npels} (number of pels computed so far)')
340+
print(f' percent = {progress.percent} (percent complete)')
341341

342342
Use :meth:`.Image.set_kill` on the image to stop computation early.
343343

examples/pil-numpy-pyvips.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import numpy as np
99

1010
if len(sys.argv) != 3:
11-
print('usage: {0} input-filename output-filename'.format(sys.argv[0]))
11+
print(f'usage: {sys.argv[0]} input-filename output-filename')
1212
sys.exit(-1)
1313

1414

examples/progress.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55

66
def progress_print(name, progress):
7-
print(f'signal {name}:'.format(name))
7+
print(f'signal {name}:')
88
print(f' run = {progress.run} (seconds of run time)')
99
print(f' eta = {progress.eta} (estimated seconds left)')
1010
print(f' tpels = {progress.tpels} (total number of pels)')

examples/soak-test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
pyvips.cache_set_max(0)
88

99
for i in range(1000):
10-
print("loop {0} ...".format(i))
10+
print(f"loop {i} ...")
1111
im = pyvips.Image.new_from_file(sys.argv[1])
1212
im = im.embed(100, 100, 3000, 3000, extend="mirror")
1313
im.write_to_file("x.v")

examples/try5.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
def should_equal(test, a, b):
1313
if abs(a - b) > 0.01:
14-
print('%s: seen %g and %g' % (test, a, b))
14+
print(f'{test}: seen {a:g} and {b:g}')
1515
sys.exit(1)
1616

1717

pyvips/__init__.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,16 @@
3232
lib_minor = vips_lib.vips_version(1)
3333
wrap_major = vips_lib.VIPS_MAJOR_VERSION
3434
wrap_minor = vips_lib.VIPS_MINOR_VERSION
35-
logger.debug('Module generated for libvips %s.%s' %
36-
(wrap_major, wrap_minor))
37-
logger.debug('Linked to libvips %s.%s' % (lib_major, lib_minor))
35+
logger.debug(f'Module generated for libvips {wrap_major}.{wrap_minor}')
36+
logger.debug(f'Linked to libvips {lib_major}.{lib_minor}')
3837

3938
if wrap_major != lib_major or wrap_minor != lib_minor:
4039
raise Exception('bad wrapper version')
4140

4241
API_mode = True
4342

4443
except Exception as e:
45-
logger.debug('Binary module load failed: %s' % e)
44+
logger.debug(f'Binary module load failed: {e}')
4645
logger.debug('Falling back to ABI mode')
4746

4847
from cffi import FFI
@@ -141,14 +140,14 @@ class GLogLevelFlags(object):
141140
@ffi.def_extern()
142141
def _log_handler_callback(domain, level, message, user_data):
143142
logger.log(GLogLevelFlags.LEVEL_TO_LOGGER[level],
144-
'{0}: {1}'.format(_to_string(domain), _to_string(message)))
143+
f'{_to_string(domain)}: {_to_string(message)}')
145144

146145
# keep a ref to the cb to stop it being GCd
147146
_log_handler_cb = glib_lib._log_handler_callback
148147
else:
149148
def _log_handler_callback(domain, level, message, user_data):
150149
logger.log(GLogLevelFlags.LEVEL_TO_LOGGER[level],
151-
'{0}: {1}'.format(_to_string(domain), _to_string(message)))
150+
f'{_to_string(domain)}: {_to_string(message)}')
152151

153152
# keep a ref to the cb to stop it being GCd
154153
_log_handler_cb = ffi.callback('GLogFunc', _log_handler_callback)

pyvips/error.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def __init__(self, message, detail=None):
6868
logger.debug('Error %s %s', self.message, self.detail)
6969

7070
def __str__(self):
71-
return '{0}\n {1}'.format(self.message, self.detail)
71+
return f'{self.message}\n {self.detail}'
7272

7373

7474
__all__ = [

pyvips/gobject.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def new_pointer_from_gtype(gtype):
159159

160160
pointer = gobject_lib.g_object_new(gtype, ffi.NULL)
161161
if pointer == ffi.NULL:
162-
raise Error("can't create {0}".format(type_name(gtype)))
162+
raise Error(f"can't create {type_name(gtype)}")
163163

164164
return pointer
165165

@@ -176,7 +176,7 @@ def signal_connect(self, name, callback):
176176
"""
177177

178178
if name not in _marshalers:
179-
raise Error('unsupported signal "{0}"'.format(name))
179+
raise Error(f'unsupported signal "{name}"')
180180

181181
go = ffi.cast('GObject *', self.pointer)
182182
handle = ffi.new_handle(callback)

pyvips/gvalue.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def gtype_to_python(gtype):
8484
name = type_name(gtype)
8585
if name.startswith('Vips'):
8686
name = name[4:]
87-
return "Union[str, %s]" % name
87+
return f"Union[str, {name}]"
8888
if gtype in GValue._gtype_to_python:
8989
return GValue._gtype_to_python[gtype]
9090
if fundamental in GValue._gtype_to_python:

pyvips/pyvips_build.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,10 @@
3232
''' if major == 8 and minor < 6 else ''
3333

3434
ffibuilder.set_source("_libvips",
35-
r"""
35+
f"""
3636
#include <vips/vips.h>
37-
""" + compat,
37+
{compat}
38+
""",
3839
**pkgconfig.parse('vips'))
3940

4041
features = {

pyvips/vdecls.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ def cdefs(features):
472472

473473
# add contents of features as a comment ... handy for debugging
474474
for key, value in features.items():
475-
code += '//%s = %s\n' % (key, value)
475+
code += f'//{key} = {value}\n'
476476

477477
return code
478478

pyvips/vimage.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def _guess_interpretation(bands, format):
181181
"""
182182

183183
if format not in FORMAT_TO_TYPESTR:
184-
raise ValueError('Unknown format: {}'.format(format))
184+
raise ValueError(f'Unknown format: {format}')
185185
if not isinstance(bands, int) or bands < 1:
186186
raise ValueError('Number of bands must be a positive integer.')
187187

@@ -323,7 +323,7 @@ def new_from_file(vips_filename, **kwargs):
323323

324324
pointer = vips_lib.vips_foreign_find_load(vips_filename)
325325
if pointer == ffi.NULL:
326-
raise Error('unable to load from file {0}'.format(vips_filename))
326+
raise Error(f'unable to load from file {vips_filename}')
327327
name = _to_string(pointer)
328328

329329
return pyvips.Operation.call(name, filename,
@@ -493,8 +493,7 @@ def new_from_array(cls, obj, scale=1.0, offset=0.0, interpretation=None):
493493
if ndim > 3:
494494
raise ValueError('array has more than 3 dimensions')
495495
if typestr not in TYPESTR_TO_FORMAT:
496-
raise ValueError('conversion from {0} not supported'
497-
.format(typestr))
496+
raise ValueError(f'conversion from {typestr} not supported')
498497

499498
if ndim == 0:
500499
width = 1
@@ -776,7 +775,7 @@ def write_to_file(self, vips_filename, **kwargs):
776775

777776
pointer = vips_lib.vips_foreign_find_save(vips_filename)
778777
if pointer == ffi.NULL:
779-
raise Error('unable to write to file {0}'.format(vips_filename))
778+
raise Error(f'unable to write to file {vips_filename}')
780779
name = _to_string(pointer)
781780

782781
return pyvips.Operation.call(name, self, filename,
@@ -1038,7 +1037,7 @@ def get(self, name):
10381037
result = vips_lib.vips_image_get(self.pointer, _to_bytes(name),
10391038
gv.pointer)
10401039
if result != 0:
1041-
raise Error('unable to get {0}'.format(name))
1040+
raise Error(f'unable to get {name}')
10421041

10431042
return gv.get()
10441043

@@ -1107,8 +1106,8 @@ def set(self, name, value):
11071106
"""
11081107
gtype = self.get_typeof(name)
11091108
if gtype == 0:
1110-
raise Error('metadata item {0} does not exist - '
1111-
'use set_type() to create and set'.format(name))
1109+
raise Error(f'metadata item {name} does not exist -'
1110+
' use set_type() to create and set')
11121111
self.set_type(gtype, name, value)
11131112

11141113
def remove(self, name):
@@ -1143,7 +1142,7 @@ def tolist(self):
11431142

11441143
row_els = self.width if not is_complex else 2 * self.width
11451144

1146-
rowfmt = '{0}{1}'.format(row_els, FORMAT_TO_PYFORMAT[self.format])
1145+
rowfmt = f'{row_els}{FORMAT_TO_PYFORMAT[self.format]}'
11471146
buf = self.write_to_memory()
11481147

11491148
lst = [list(row) for row in struct.iter_unpack(rowfmt, buf)]
@@ -1261,9 +1260,8 @@ def __repr__(self):
12611260
array = self.tolist()
12621261
return repr(array)
12631262
else:
1264-
return ('<pyvips.Image {0}x{1} {2}, {3} bands, {4}>'.
1265-
format(self.width, self.height, self.format, self.bands,
1266-
self.interpretation))
1263+
return (f'<pyvips.Image {self.width}x{self.height} {self.format}, '
1264+
f'{self.bands} bands, {self.interpretation}>')
12671265

12681266
def __getattr__(self, name):
12691267
"""Divert unknown names to libvips.

pyvips/vinterpolate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def new(name):
3535

3636
vi = vips_lib.vips_interpolate_new(_to_bytes(name))
3737
if vi == ffi.NULL:
38-
raise Error('no such interpolator {0}'.format(name))
38+
raise Error(f'no such interpolator {name}')
3939

4040
return Interpolate(vi)
4141

pyvips/voperation.py

+16-19
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ def __init__(self, pointer):
188188
def new_from_name(operation_name):
189189
vop = vips_lib.vips_operation_new(_to_bytes(operation_name))
190190
if vop == ffi.NULL:
191-
raise Error('no such operation {0}'.format(operation_name))
191+
raise Error(f'no such operation {operation_name}')
192192
return Operation(vop)
193193

194194
def set(self, name, flags, match_image, value):
@@ -232,18 +232,16 @@ def call(operation_name, *args, **kwargs):
232232
intro = Introspect.get(operation_name)
233233

234234
if len(intro.required_input) != len(args):
235-
raise Error('{0} needs {1} arguments, but {2} given'
236-
.format(operation_name,
237-
len(intro.required_input),
238-
len(args)))
235+
raise Error(f'{operation_name} needs {len(intro.required_input)} '
236+
f'arguments, but {len(args)} given')
239237

240238
op = Operation.new_from_name(operation_name)
241239

242240
# set any string options before any args so they can't be
243241
# overridden
244242
string_options = kwargs.pop('string_options', '')
245243
if not op.set_string(string_options):
246-
raise Error('unable to call {0}'.format(operation_name))
244+
raise Error(f'unable to call {operation_name}')
247245

248246
# the first image argument is the thing we expand constants to
249247
# match ... look inside tables for images, since we may be passing
@@ -283,8 +281,8 @@ def add_reference(x):
283281
for name in kwargs:
284282
if (name not in intro.optional_input and
285283
name not in intro.optional_output):
286-
raise Error('{0} does not support optional argument {1}'
287-
.format(operation_name, name))
284+
raise Error(f'{operation_name} does not support optional '
285+
f'argument {name}')
288286

289287
value = kwargs[name]
290288
details = intro.details[name]
@@ -300,7 +298,7 @@ def add_reference(x):
300298
vop = vips_lib.vips_cache_operation_build(op.pointer)
301299
if vop == ffi.NULL:
302300
vips_lib.vips_object_unref_outputs(op.vobject)
303-
raise Error('unable to call {0}'.format(operation_name))
301+
raise Error(f'unable to call {operation_name}')
304302
op = Operation(vop)
305303

306304
# attach all input refs to output x
@@ -353,7 +351,7 @@ def generate_docstring(operation_name):
353351
intro = Introspect.get(operation_name)
354352
if (intro.flags & _OPERATION_DEPRECATED) != 0:
355353
raise Error('No such operator.',
356-
'operator "{0}" is deprecated'.format(operation_name))
354+
f'operator "{operation_name}" is deprecated')
357355

358356
result = intro.description[0].upper() + intro.description[1:] + '.\n\n'
359357
result += 'Example:\n'
@@ -417,7 +415,7 @@ def generate_sphinx(operation_name):
417415
intro = Introspect.get(operation_name)
418416
if (intro.flags & _OPERATION_DEPRECATED) != 0:
419417
raise Error('No such operator.',
420-
'operator "{0}" is deprecated'.format(operation_name))
418+
f'operator "{operation_name}" is deprecated')
421419

422420
if intro.member_x is not None:
423421
result = '.. method:: '
@@ -451,14 +449,13 @@ def generate_sphinx(operation_name):
451449

452450
for name in intro.method_args + intro.doc_optional_input:
453451
details = intro.details[name]
454-
result += (':param {0}: {1}\n'.
455-
format(name, details['blurb']))
456-
result += (':type {0}: {1}\n'.
457-
format(name, GValue.gtype_to_python(details['type'])))
452+
result += f':param {name}: {details["blurb"]}\n'
453+
result += (f':type {name}: '
454+
f'{GValue.gtype_to_python(details["type"])}\n')
458455
for name in intro.doc_optional_output:
459-
result += (':param {0}: enable output: {1}\n'.
460-
format(name, intro.details[name]['blurb']))
461-
result += (':type {0}: bool\n'.format(name))
456+
result += (f':param {name}: '
457+
f'enable output: {intro.details[name]["blurb"]}\n')
458+
result += f':type {name}: bool\n'
462459

463460
output_types = [GValue.gtype_to_python(intro.details[name]['type'])
464461
for name in intro.required_output]
@@ -532,7 +529,7 @@ def add_name(gtype, a, b):
532529
print(' .. autosummary::')
533530
print(' :nosignatures:\n')
534531
for name in all_names:
535-
print(' ~{0}'.format(name))
532+
print(f' ~{name}')
536533
print()
537534

538535
# Output docs

pyvips/vsource.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@ def new_from_descriptor(descriptor):
3535
# sources are mutable, so we can't use the cache
3636
pointer = vips_lib.vips_source_new_from_descriptor(descriptor)
3737
if pointer == ffi.NULL:
38-
raise Error("can't create source from descriptor {0}"
39-
.format(descriptor))
38+
raise Error(f"can't create source from descriptor {descriptor}")
4039

4140
return Source(pointer)
4241

@@ -57,8 +56,7 @@ def new_from_file(filename):
5756

5857
pointer = vips_lib.vips_source_new_from_file(_to_bytes(filename))
5958
if pointer == ffi.NULL:
60-
raise Error("can't create source from filename {0}"
61-
.format(filename))
59+
raise Error(f"can't create source from filename {filename}")
6260

6361
return Source(pointer)
6462

pyvips/vtarget.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ def new_to_descriptor(descriptor):
3636
# targets are mutable, so we can't use the cache
3737
pointer = vips_lib.vips_target_new_to_descriptor(descriptor)
3838
if pointer == ffi.NULL:
39-
raise Error("can't create output target from descriptor {0}"
40-
.format(descriptor))
39+
raise Error(f"can't create output target from descriptor "
40+
f'{descriptor}')
4141

4242
return Target(pointer)
4343

@@ -57,8 +57,7 @@ def new_to_file(filename):
5757

5858
pointer = vips_lib.vips_target_new_to_file(_to_bytes(filename))
5959
if pointer == ffi.NULL:
60-
raise Error("can't create output target from filename {0}"
61-
.format(filename))
60+
raise Error(f"can't create output target from filename {filename}")
6261

6362
return Target(pointer)
6463

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,5 @@
1818
try:
1919
setup(cffi_modules=['pyvips/pyvips_build.py:ffibuilder'])
2020
except Exception as e:
21-
print('Falling back to ABI mode. Details: {0}'.format(e))
21+
print(f'Falling back to ABI mode. Details: {e}')
2222
setup()

tests/helpers/helpers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,14 @@ def run_fn2(fn, x, y):
7474

7575
# test a pair of things which can be lists for approx. equality
7676
def assert_almost_equal_objects(a, b, threshold=0.0001, msg=''):
77-
# print 'assertAlmostEqualObjects %s = %s' % (a, b)
77+
# print(f'assertAlmostEqualObjects {a} = {b}')
7878
assert all([pytest.approx(x, abs=threshold) == y
7979
for x, y in zip_expand(a, b)]), msg
8080

8181

8282
# test a pair of things which can be lists for equality
8383
def assert_equal_objects(a, b, msg=''):
84-
# print 'assertEqualObjects %s = %s' % (a, b)
84+
# print(f'assertEqualObjects {a} = {b}')
8585
assert all([x == y for x, y in zip_expand(a, b)]), msg
8686

8787

0 commit comments

Comments
 (0)