Skip to content

Commit 47468fc

Browse files
committed
Use f-strings where relevant
1 parent 3969ccc commit 47468fc

File tree

13 files changed

+49
-56
lines changed

13 files changed

+49
-56
lines changed

stagpy/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,7 @@ def load_mplstyle():
8686
try:
8787
plt.style.use(style)
8888
except OSError:
89-
print('Cannot import style {}.'.format(style),
90-
file=sys.stderr)
89+
print(f'Cannot import style {style}.', file=sys.stderr)
9190
conf.plot.mplstyle = ''
9291
if conf.plot.xkcd:
9392
plt.xkcd()

stagpy/_step.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,8 +229,8 @@ def __getitem__(self, name):
229229
else:
230230
raise error.UnknownFieldVarError(name)
231231
if parsed_data is None:
232-
raise error.MissingDataError('Missing field {} in step {}'
233-
.format(name, self.step.istep))
232+
raise error.MissingDataError(
233+
f'Missing field {name} in step {self.step.istep}')
234234
header, fields = parsed_data
235235
self._header = header
236236
for fld_name, fld in zip(fld_names, fields):
@@ -405,8 +405,8 @@ def _rprofs(self):
405405
step = self.step
406406
self._data = step.sdat._rprof_and_times[0].get(step.istep)
407407
if self._data is None:
408-
raise error.MissingDataError('No rprof data in step {} of {}'
409-
.format(step.istep, step.sdat))
408+
raise error.MissingDataError(
409+
f'No rprof data in step {step.istep} of {step.sdat}')
410410
return self._data
411411

412412
def __getitem__(self, name):

stagpy/commands.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def info_cmd():
2525
sdat = stagyydata.StagyyData()
2626
lsnap = sdat.snaps[-1]
2727
lstep = sdat.steps[-1]
28-
print('StagYY run in {}'.format(sdat.path))
28+
print(f'StagYY run in {sdat.path}')
2929
if lsnap.geom.threed:
3030
dimension = '{} x {} x {}'.format(lsnap.geom.nxtot,
3131
lsnap.geom.nytot,
@@ -45,9 +45,9 @@ def info_cmd():
4545
print()
4646
for step in sdat.walk:
4747
is_snap = step.isnap is not None
48-
print('Step {}/{}'.format(step.istep, lstep.istep), end='')
48+
print(f'Step {step.istep}/{lstep.istep}', end='')
4949
if is_snap:
50-
print(', snapshot {}/{}'.format(step.isnap, lsnap.isnap))
50+
print(f', snapshot {step.isnap}/{lsnap.isnap}')
5151
else:
5252
print()
5353
series = step.timeinfo.loc[varlist]
@@ -95,7 +95,7 @@ def _pretty_print(key_val, sep=': ', min_col_width=39, text_width=None):
9595
wrapper.subsequent_indent = ' '
9696
else:
9797
wrapper.subsequent_indent = ' ' * (len(key) + len(sep))
98-
lines.extend(wrapper.wrap('{}{}{}'.format(key, sep, val)))
98+
lines.extend(wrapper.wrap(f'{key}{sep}{val}'))
9999

100100
chunks = []
101101
for rem_col in range(ncols, 1, -1):
@@ -107,7 +107,7 @@ def _pretty_print(key_val, sep=': ', min_col_width=39, text_width=None):
107107
chunks.append(lines)
108108
lines = zip_longest(*chunks, fillvalue='')
109109

110-
fmt = '|'.join(['{{:{}}}'.format(colw)] * (ncols - 1))
110+
fmt = '|'.join([f'{{:{colw}}}'] * (ncols - 1))
111111
fmt += '|{}' if ncols > 1 else '{}'
112112
print(*(fmt.format(*line) for line in lines), sep='\n')
113113

@@ -157,7 +157,7 @@ def version_cmd():
157157
158158
Use :data:`stagpy.__version__` to obtain the version in a script.
159159
"""
160-
print('stagpy version: {}'.format(__version__))
160+
print(f'stagpy version: {__version__}')
161161

162162

163163
def report_parsing_problems(parsing_out):
@@ -191,7 +191,7 @@ def config_pp(subs):
191191
opt += ' (c)' if meta.cmd_arg else ' (f)'
192192
hlp_lst.append((opt, meta.help))
193193
if hlp_lst:
194-
print('{}:'.format(sub))
194+
print(f'{sub}:')
195195
_pretty_print(hlp_lst, sep=' -- ',
196196
text_width=min(get_terminal_size().columns, 100))
197197
print()

stagpy/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def _actual_index(arg):
1616
if ':' in arg:
1717
idxs = arg.split(':')
1818
if len(idxs) > 3:
19-
raise ValueError('{} is an invalid slice'.format(arg))
19+
raise ValueError(f'{arg} is an invalid slice')
2020
idxs[0] = int(idxs[0]) if idxs[0] else None
2121
idxs[1] = int(idxs[1]) if idxs[1] else None
2222
if len(idxs) == 3:

stagpy/error.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class NoSnapshotError(StagpyError):
2727

2828
def __init__(self, sdat):
2929
self.sdat = sdat
30-
super().__init__('no snapshot found for {}'.format(sdat))
30+
super().__init__(f'no snapshot found for {sdat}')
3131

3232

3333
class NoParFileError(StagpyError):
@@ -43,7 +43,7 @@ class NoParFileError(StagpyError):
4343

4444
def __init__(self, parfile):
4545
self.parfile = parfile
46-
super().__init__('{} file not found'.format(parfile))
46+
super().__init__(f'{parfile} file not found')
4747

4848

4949
class NotAvailableError(StagpyError):
@@ -130,8 +130,7 @@ class InvalidTimeFractionError(StagpyError):
130130

131131
def __init__(self, fraction):
132132
self.fraction = fraction
133-
super().__init__('Fraction should be in (0,1] (received {})'
134-
.format(fraction))
133+
super().__init__(f'Fraction should be in (0,1] (received {fraction})')
135134

136135

137136
class InvalidNfieldsError(StagpyError):
@@ -146,8 +145,7 @@ class InvalidNfieldsError(StagpyError):
146145

147146
def __init__(self, nfields):
148147
self.nfields = nfields
149-
super().__init__('nfields_max should be >5 (received {})'
150-
.format(nfields))
148+
super().__init__(f'nfields_max should be >5 (received {nfields})')
151149

152150

153151
class InvalidZoomError(StagpyError):
@@ -162,8 +160,7 @@ class InvalidZoomError(StagpyError):
162160

163161
def __init__(self, zoom):
164162
self.zoom = zoom
165-
super().__init__('Zoom angle should be in [0,360] (received {})'
166-
.format(zoom))
163+
super().__init__(f'Zoom angle should be in [0,360] (received {zoom})')
167164

168165

169166
class StagnantLidError(StagpyError):
@@ -180,7 +177,7 @@ class StagnantLidError(StagpyError):
180177

181178
def __init__(self, sdat):
182179
self.sdat = sdat
183-
super().__init__('Stagnant lid regime for {}'.format(sdat))
180+
super().__init__(f'Stagnant lid regime for {sdat}')
184181

185182

186183
class MissingDataError(StagpyError, KeyError):

stagpy/field.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ def plot_scalar(step, var, field=None, axis=None, **extra):
203203
cbar = plt.colorbar(surf, cax=cax)
204204
cbar.set_label(meta.description +
205205
(' pert.' if conf.field.perturbation else '') +
206-
(' ({})'.format(unit) if unit else ''))
206+
(f' ({unit})' if unit else ''))
207207
if step.geom.spherical or conf.plot.ratio is None:
208208
axis.set_aspect('equal')
209209
axis.set_axis_off()
@@ -309,8 +309,7 @@ def cmd():
309309
figsize=(9 * len(vfig), 6))
310310
for axis, var in zip(axes[0], vfig):
311311
if var[0] not in step.fields:
312-
print("'{}' field on snap {} not found".format(var[0],
313-
step.isnap))
312+
print(f"{var[0]!r} field on snap {step.isnap} not found")
314313
continue
315314
opts = {}
316315
if var[0] in minmax:
@@ -324,7 +323,7 @@ def cmd():
324323
if conf.field.timelabel:
325324
time, unit = sdat.scale(step.timeinfo['t'], 's')
326325
time = misc.scilabel(time)
327-
axes[0, 0].text(0.02, 1.02, '$t={}$ {}'.format(time, unit),
326+
axes[0, 0].text(0.02, 1.02, f'$t={time}$ {unit}',
328327
transform=axes[0, 0].transAxes)
329328
oname = '_'.join(chain.from_iterable(vfig))
330329
plt.tight_layout(w_pad=3)

stagpy/misc.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,10 @@ def scilabel(value, precision=2):
4545
Returns:
4646
str: the scientific notation the specified value.
4747
"""
48-
fmt = '{{:.{}e}}'.format(precision)
48+
fmt = f'{{:.{precision}e}}'
4949
man, exp = fmt.format(value).split('e')
5050
exp = int(exp)
51-
return r'{}\times 10^{{{}}}'.format(man, exp)
51+
return fr'{man}\times 10^{{{exp}}}'
5252

5353

5454
def saveplot(fig, *name_args, close=True, **name_kwargs):
@@ -64,7 +64,7 @@ def saveplot(fig, *name_args, close=True, **name_kwargs):
6464
name_kwargs: keyword arguments passed on to :func:`out_name`.
6565
"""
6666
oname = out_name(*name_args, **name_kwargs)
67-
fig.savefig('{}.{}'.format(oname, conf.plot.format),
67+
fig.savefig(f'{oname}.{conf.plot.format}',
6868
format=conf.plot.format, bbox_inches='tight')
6969
if close:
7070
plt.close(fig)
@@ -160,7 +160,7 @@ class InchoateFiles:
160160
"""
161161

162162
def __init__(self, nfiles=1, tmp_prefix=None):
163-
self._fnames = ['inchoate{}'.format(i) for i in range(nfiles)]
163+
self._fnames = [f'inchoate{i}' for i in range(nfiles)]
164164
self._tmpprefix = tmp_prefix
165165
self._fids = []
166166

stagpy/plates.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -480,7 +480,7 @@ def plot_plates(step, time, vrms_surface, trench, ridge, agetrench,
480480

481481
def io_surface(timestep, time, fid, fld):
482482
"""Output surface files."""
483-
fid.write("{} {}".format(timestep, time))
483+
fid.write(f"{timestep} {time}")
484484
fid.writelines(["%10.2e" % item for item in fld[:]])
485485
fid.writelines(["\n"])
486486

@@ -839,4 +839,4 @@ def cmd():
839839
plt.plot(time, nb_plates)
840840
plt.subplot(122)
841841
plt.plot(time, ch2o)
842-
misc.saveplot(figt, 'plates_{}_{}'.format(istart, iend))
842+
misc.saveplot(figt, f'plates_{istart}_{iend}')

stagpy/refstate.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ def plot_ref(sdat, var):
1717
fig, axis = plt.subplots()
1818
adbts = sdat.refstate.adiabats
1919
if len(adbts) > 2:
20-
for iad, adia in enumerate(adbts[:-1]):
20+
for iad, adia in enumerate(adbts[:-1], 1):
2121
axis.plot(adia[var], adia['z'],
2222
conf.refstate.style,
23-
label='System {}'.format(iad + 1))
23+
label=f'System {iad}')
2424
axis.plot(adbts[-1][var], adbts[-1]['z'],
2525
conf.refstate.style, color='k',
2626
label='Combined profile')
@@ -30,7 +30,7 @@ def plot_ref(sdat, var):
3030
axis.set_ylabel('z Position')
3131
if len(adbts) > 2:
3232
axis.legend()
33-
misc.saveplot(fig, 'refstate_{}'.format(var))
33+
misc.saveplot(fig, f'refstate_{var}')
3434

3535

3636
def cmd():

stagpy/rprof.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def _plot_rprof_list(sdat, lovs, rprofs, stepstr):
3636
if xlabel:
3737
_, unit = sdat.scale(1, meta.dim)
3838
if unit:
39-
xlabel += ' ({})'.format(unit)
39+
xlabel += f' ({unit})'
4040
axes[iplt].set_xlabel(xlabel)
4141
if vplt[0][:3] == 'eta': # list of log variables
4242
axes[iplt].set_xscale('log')
@@ -46,7 +46,7 @@ def _plot_rprof_list(sdat, lovs, rprofs, stepstr):
4646
ylabel = 'Depth' if conf.rprof.depth else 'Radius'
4747
_, unit = sdat.scale(1, 'm')
4848
if unit:
49-
ylabel += ' ({})'.format(unit)
49+
ylabel += f' ({unit})'
5050
axes[0].set_ylabel(ylabel)
5151
misc.saveplot(fig, fname + stepstr)
5252

@@ -63,7 +63,7 @@ def plot_grid(step):
6363
drad, rad, _ = step.rprofs['dr']
6464
_, unit = step.sdat.scale(1, 'm')
6565
if unit:
66-
unit = ' ({})'.format(unit)
66+
unit = f' ({unit})'
6767
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
6868
ax1.plot(rad, '-ko')
6969
ax1.set_ylabel('$r$' + unit)
@@ -119,7 +119,7 @@ def plot_average(sdat, lovs):
119119
rprof_averaged['bounds'] = (step.sdat.scale(rcmb, 'm')[0],
120120
step.sdat.scale(rsurf, 'm')[0])
121121

122-
stepstr = '{}_{}'.format(istart, ilast)
122+
stepstr = f'{istart}_{ilast}'
123123

124124
_plot_rprof_list(sdat, lovs, rprof_averaged, stepstr)
125125

0 commit comments

Comments
 (0)