Skip to content

Commit 7a7e861

Browse files
authored
Fix pylint 2.11 consider-using-f-string checker errors (#1517)
* Use f-strings throughout the project * Fix C0201 consider-iterating-dictionary * Fix W1514 unspecified-encoding
1 parent 0327262 commit 7a7e861

14 files changed

+69
-107
lines changed

doc/conf.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,9 @@
127127
release = __version__
128128

129129
# These enable substitutions using |variable| in the rst files
130-
rst_epilog = """
130+
rst_epilog = f"""
131131
.. |year| replace:: {year}
132-
""".format(
133-
year=year
134-
)
132+
"""
135133

136134
html_last_updated_fmt = "%b %d, %Y"
137135
html_title = "PyGMT"

pygmt/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def print_clib_info():
7777
lines = ["GMT library information:"]
7878
with Session() as ses:
7979
for key in sorted(ses.info):
80-
lines.append(" {}: {}".format(key, ses.info[key]))
80+
lines.append(f" {key}: {ses.info[key]}")
8181
print("\n".join(lines))
8282

8383

@@ -212,7 +212,7 @@ def test(doctest=True, verbose=True, coverage=False, figures=True):
212212
if verbose:
213213
args.append("-vv")
214214
if coverage:
215-
args.append("--cov={}".format(package))
215+
args.append(f"--cov={package}")
216216
args.append("--cov-report=term-missing")
217217
if doctest:
218218
args.append("--doctest-modules")

pygmt/clib/session.py

Lines changed: 21 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,7 @@ class Session:
113113
... with GMTTempFile() as fout:
114114
... # Call the grdinfo module with the virtual file as input
115115
... # and the temp file as output.
116-
... ses.call_module(
117-
... "grdinfo", "{} -C ->{}".format(fin, fout.name)
118-
... )
116+
... ses.call_module("grdinfo", f"{fin} -C ->{fout.name}")
119117
... # Read the contents of the temp file before it's deleted.
120118
... print(fout.read().strip())
121119
...
@@ -189,9 +187,8 @@ def __enter__(self):
189187
if Version(version) < Version(self.required_version):
190188
self.destroy()
191189
raise GMTVersionError(
192-
"Using an incompatible GMT version {}. Must be equal or newer than {}.".format(
193-
version, self.required_version
194-
)
190+
f"Using an incompatible GMT version {version}. "
191+
f"Must be equal or newer than {self.required_version}."
195192
)
196193
return self
197194

@@ -366,7 +363,7 @@ def print_func(file_pointer, message): # pylint: disable=unused-argument
366363

367364
if session is None:
368365
raise GMTCLibError(
369-
"Failed to create a GMT API session:\n{}".format(self._error_message)
366+
f"Failed to create a GMT API session:\n{self._error_message}"
370367
)
371368

372369
self.session_pointer = session
@@ -412,7 +409,7 @@ def destroy(self):
412409
status = c_destroy_session(self.session_pointer)
413410
if status:
414411
raise GMTCLibError(
415-
"Failed to destroy GMT API session:\n{}".format(self._error_message)
412+
f"Failed to destroy GMT API session:\n{self._error_message}"
416413
)
417414

418415
self.session_pointer = None
@@ -462,9 +459,7 @@ def get_default(self, name):
462459

463460
if status != 0:
464461
raise GMTCLibError(
465-
"Error getting default value for '{}' (error code {}).".format(
466-
name, status
467-
)
462+
f"Error getting default value for '{name}' (error code {status})."
468463
)
469464

470465
return value.value.decode()
@@ -503,9 +498,7 @@ def call_module(self, module, args):
503498
)
504499
if status != 0:
505500
raise GMTCLibError(
506-
"Module '{}' failed with status code {}:\n{}".format(
507-
module, status, self._error_message
508-
)
501+
f"Module '{module}' failed with status code {status}:\n{self._error_message}"
509502
)
510503

511504
def create_data(self, family, geometry, mode, **kwargs):
@@ -650,30 +643,24 @@ def _parse_constant(self, constant, valid, valid_modifiers=None):
650643
nmodifiers = len(parts) - 1
651644
if nmodifiers > 1:
652645
raise GMTInvalidInput(
653-
"Only one modifier is allowed in constants, {} given: '{}'".format(
654-
nmodifiers, constant
655-
)
646+
f"Only one modifier is allowed in constants, {nmodifiers} given: '{constant}'"
656647
)
657648
if nmodifiers > 0 and valid_modifiers is None:
658649
raise GMTInvalidInput(
659650
"Constant modifiers not allowed since valid values were not "
660-
+ "given: '{}'".format(constant)
651+
+ f"given: '{constant}'"
661652
)
662653
if name not in valid:
663654
raise GMTInvalidInput(
664-
"Invalid constant argument '{}'. Must be one of {}.".format(
665-
name, str(valid)
666-
)
655+
f"Invalid constant argument '{name}'. Must be one of {str(valid)}."
667656
)
668657
if (
669658
nmodifiers > 0
670659
and valid_modifiers is not None
671660
and parts[1] not in valid_modifiers
672661
):
673662
raise GMTInvalidInput(
674-
"Invalid constant modifier '{}'. Must be one of {}.".format(
675-
parts[1], str(valid_modifiers)
676-
)
663+
f"Invalid constant modifier '{parts[1]}'. Must be one of {str(valid_modifiers)}."
677664
)
678665
integer_value = sum(self[part] for part in parts)
679666
return integer_value
@@ -905,7 +892,7 @@ def put_matrix(self, dataset, matrix, pad=0):
905892
self.session_pointer, dataset, gmt_type, pad, matrix_pointer
906893
)
907894
if status != 0:
908-
raise GMTCLibError("Failed to put matrix of type {}.".format(matrix.dtype))
895+
raise GMTCLibError(f"Failed to put matrix of type {matrix.dtype}.")
909896

910897
def write_data(self, family, geometry, mode, wesn, output, data):
911898
"""
@@ -974,7 +961,7 @@ def write_data(self, family, geometry, mode, wesn, output, data):
974961
data,
975962
)
976963
if status != 0:
977-
raise GMTCLibError("Failed to write dataset to '{}'".format(output))
964+
raise GMTCLibError(f"Failed to write dataset to '{output}'")
978965

979966
@contextmanager
980967
def open_virtual_file(self, family, geometry, direction, data):
@@ -1036,7 +1023,7 @@ def open_virtual_file(self, family, geometry, direction, data):
10361023
... with lib.open_virtual_file(*vfargs) as vfile:
10371024
... # Send the output to a temp file so that we can read it
10381025
... with GMTTempFile() as ofile:
1039-
... args = "{} ->{}".format(vfile, ofile.name)
1026+
... args = f"{vfile} ->{ofile.name}"
10401027
... lib.call_module("info", args)
10411028
... print(ofile.read().strip())
10421029
...
@@ -1083,7 +1070,7 @@ def open_virtual_file(self, family, geometry, direction, data):
10831070
finally:
10841071
status = c_close_virtualfile(self.session_pointer, vfname.encode())
10851072
if status != 0:
1086-
raise GMTCLibError("Failed to close virtual file '{}'.".format(vfname))
1073+
raise GMTCLibError(f"Failed to close virtual file '{vfname}'.")
10871074

10881075
@contextmanager
10891076
def virtualfile_from_vectors(self, *vectors):
@@ -1131,9 +1118,7 @@ def virtualfile_from_vectors(self, *vectors):
11311118
... with ses.virtualfile_from_vectors(x, y, z) as fin:
11321119
... # Send the output to a file so that we can read it
11331120
... with GMTTempFile() as fout:
1134-
... ses.call_module(
1135-
... "info", "{} ->{}".format(fin, fout.name)
1136-
... )
1121+
... ses.call_module("info", f"{fin} ->{fout.name}")
11371122
... print(fout.read().strip())
11381123
...
11391124
<vector memory>: N = 3 <1/3> <4/6> <7/9>
@@ -1244,9 +1229,7 @@ def virtualfile_from_matrix(self, matrix):
12441229
... with ses.virtualfile_from_matrix(data) as fin:
12451230
... # Send the output to a file so that we can read it
12461231
... with GMTTempFile() as fout:
1247-
... ses.call_module(
1248-
... "info", "{} ->{}".format(fin, fout.name)
1249-
... )
1232+
... ses.call_module("info", f"{fin} ->{fout.name}")
12501233
... print(fout.read().strip())
12511234
...
12521235
<matrix memory>: N = 4 <0/9> <1/10> <2/11>
@@ -1327,7 +1310,7 @@ def virtualfile_from_grid(self, grid):
13271310
... with ses.virtualfile_from_grid(data) as fin:
13281311
... # Send the output to a file so that we can read it
13291312
... with GMTTempFile() as fout:
1330-
... args = "{} -L0 -Cn ->{}".format(fin, fout.name)
1313+
... args = f"{fin} -L0 -Cn ->{fout.name}"
13311314
... ses.call_module("grdinfo", args)
13321315
... print(fout.read().strip())
13331316
...
@@ -1508,7 +1491,7 @@ def extract_region(self):
15081491
>>> with Session() as lib:
15091492
... wesn = lib.extract_region()
15101493
...
1511-
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
1494+
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
15121495
0.00, 10.00, -20.00, -10.00
15131496
15141497
Using ISO country codes for the regions (for example ``'US.HI'`` for
@@ -1521,7 +1504,7 @@ def extract_region(self):
15211504
>>> with Session() as lib:
15221505
... wesn = lib.extract_region()
15231506
...
1524-
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
1507+
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
15251508
-164.71, -154.81, 18.91, 23.58
15261509
15271510
The country codes can have an extra argument that rounds the region a
@@ -1535,7 +1518,7 @@ def extract_region(self):
15351518
>>> with Session() as lib:
15361519
... wesn = lib.extract_region()
15371520
...
1538-
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
1521+
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
15391522
-165.00, -150.00, 15.00, 25.00
15401523
"""
15411524
c_extract_region = self.get_libgmt_func(

pygmt/figure.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ class Figure:
7373
>>> fig = Figure()
7474
>>> fig.basemap(region="JP", projection="M3i", frame=True)
7575
>>> # The fig.region attribute shows the WESN bounding box for the figure
76-
>>> print(", ".join("{:.2f}".format(i) for i in fig.region))
76+
>>> print(", ".join(f"{i:.2f}" for i in fig.region))
7777
122.94, 145.82, 20.53, 45.52
7878
"""
7979

@@ -103,7 +103,7 @@ def _activate_figure(self):
103103
# Passing format '-' tells pygmt.end to not produce any files.
104104
fmt = "-"
105105
with Session() as lib:
106-
lib.call_module("figure", "{} {}".format(self._name, fmt))
106+
lib.call_module("figure", f"{self._name} {fmt}")
107107

108108
def _preprocess(self, **kwargs):
109109
"""
@@ -358,9 +358,9 @@ def shift_origin(self, xshift=None, yshift=None):
358358
self._preprocess()
359359
args = ["-T"]
360360
if xshift:
361-
args.append("-X{}".format(xshift))
361+
args.append(f"-X{xshift}")
362362
if yshift:
363-
args.append("-Y{}".format(yshift))
363+
args.append(f"-Y{yshift}")
364364

365365
with Session() as lib:
366366
lib.call_module("plot", " ".join(args))

pygmt/helpers/decorators.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ def fmt_docstring(module_func):
468468
aliases = ["**Aliases:**\n"]
469469
for arg in sorted(module_func.aliases):
470470
alias = module_func.aliases[arg]
471-
aliases.append("- {} = {}".format(arg, alias))
471+
aliases.append(f"- {arg} = {alias}")
472472
filler_text["aliases"] = "\n".join(aliases)
473473

474474
filler_text["table-like"] = " or ".join(
@@ -634,15 +634,12 @@ def kwargs_to_strings(**conversions):
634634
... "A module that prints the arguments it received"
635635
... print("{", end="")
636636
... print(
637-
... ", ".join(
638-
... "'{}': {}".format(k, repr(kwargs[k]))
639-
... for k in sorted(kwargs)
640-
... ),
637+
... ", ".join(f"'{k}': {repr(kwargs[k])}" for k in sorted(kwargs)),
641638
... end="",
642639
... )
643640
... print("}")
644641
... if args:
645-
... print("args:", " ".join("{}".format(x) for x in args))
642+
... print("args:", " ".join(f"{x}" for x in args))
646643
>>> module(R=[1, 2, 3, 4])
647644
{'R': '1/2/3/4'}
648645
>>> # It's already a string, do nothing
@@ -690,7 +687,7 @@ def kwargs_to_strings(**conversions):
690687
for arg, fmt in conversions.items():
691688
if fmt not in valid_conversions:
692689
raise GMTInvalidInput(
693-
"Invalid conversion type '{}' for argument '{}'.".format(fmt, arg)
690+
f"Invalid conversion type '{fmt}' for argument '{arg}'."
694691
)
695692

696693
separators = {

pygmt/helpers/testing.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,9 @@ def wrapper(*args, ext="png", request=None, **kwargs):
113113
for key in ["actual", "expected", "diff"]:
114114
err[key] = os.path.relpath(err[key])
115115
raise GMTImageComparisonFailure(
116-
"images not close (RMS %(rms).3f):\n\t%(actual)s\n\t%(expected)s "
117-
% err
116+
f"images not close (RMS {err['rms']:.3f}):\n"
117+
f"\t{err['actual']}\n"
118+
f"\t{err['expected']}"
118119
)
119120
finally:
120121
del fig_ref

pygmt/src/config.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,7 @@ def __init__(self, **kwargs):
5555
self.old_defaults[key] = lib.get_default(key)
5656

5757
# call gmt set to change GMT defaults
58-
arg_str = " ".join(
59-
["{}={}".format(key, value) for key, value in kwargs.items()]
60-
)
58+
arg_str = " ".join([f"{key}={value}" for key, value in kwargs.items()])
6159
with Session() as lib:
6260
lib.call_module("set", arg_str)
6361

@@ -67,7 +65,7 @@ def __enter__(self):
6765
def __exit__(self, exc_type, exc_value, traceback):
6866
# revert to initial values
6967
arg_str = " ".join(
70-
["{}={}".format(key, value) for key, value in self.old_defaults.items()]
68+
[f"{key}={value}" for key, value in self.old_defaults.items()]
7169
)
7270
with Session() as lib:
7371
lib.call_module("set", arg_str)

pygmt/src/grd2cpt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def grd2cpt(grid, **kwargs):
167167
with file_context as infile:
168168
if "H" not in kwargs.keys(): # if no output is set
169169
arg_str = " ".join([infile, build_arg_string(kwargs)])
170-
elif "H" in kwargs.keys(): # if output is set
170+
if "H" in kwargs: # if output is set
171171
outfile = kwargs.pop("H")
172172
if not outfile or not isinstance(outfile, str):
173173
raise GMTInvalidInput("'output' should be a proper file name.")

pygmt/src/legend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,6 @@ def legend(self, spec=None, position="JTR+jTR+o0.2c", box="+gwhite+p1p", **kwarg
8686
elif data_kind(spec) == "file":
8787
specfile = spec
8888
else:
89-
raise GMTInvalidInput("Unrecognized data type: {}".format(type(spec)))
89+
raise GMTInvalidInput(f"Unrecognized data type: {type(spec)}")
9090
arg_str = " ".join([specfile, build_arg_string(kwargs)])
9191
lib.call_module("legend", arg_str)

pygmt/src/makecpt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,9 +149,9 @@ def makecpt(**kwargs):
149149
with Session() as lib:
150150
if "W" in kwargs and "Ww" in kwargs:
151151
raise GMTInvalidInput("Set only categorical or cyclic to True, not both.")
152-
if "H" not in kwargs.keys(): # if no output is set
152+
if "H" not in kwargs: # if no output is set
153153
arg_str = build_arg_string(kwargs)
154-
elif "H" in kwargs.keys(): # if output is set
154+
elif "H" in kwargs: # if output is set
155155
outfile = kwargs.pop("H")
156156
if not outfile or not isinstance(outfile, str):
157157
raise GMTInvalidInput("'output' should be a proper file name.")

pygmt/src/meca.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ def update_pointers(data_pointers):
455455
elif kind == "file":
456456
file_context = dummy_context(spec)
457457
else:
458-
raise GMTInvalidInput("Unrecognized data type: {}".format(type(spec)))
458+
raise GMTInvalidInput(f"Unrecognized data type: {type(spec)}")
459459
with file_context as fname:
460460
arg_str = " ".join([fname, build_arg_string(kwargs)])
461461
lib.call_module("meca", arg_str)

pygmt/src/surface.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def surface(x=None, y=None, z=None, data=None, **kwargs):
105105
elif kind == "vectors":
106106
file_context = lib.virtualfile_from_vectors(x, y, z)
107107
else:
108-
raise GMTInvalidInput("Unrecognized data type: {}".format(type(data)))
108+
raise GMTInvalidInput(f"Unrecognized data type: {type(data)}")
109109
with file_context as infile:
110110
if "G" not in kwargs.keys(): # if outgrid is unset, output to tmpfile
111111
kwargs.update({"G": tmpfile.name})

pygmt/src/x2sys_cross.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def x2sys_cross(tracks=None, outfile=None, **kwargs):
202202
# $X2SYS_HOME/TAGNAME/TAGNAME.tag file
203203
lastline = (
204204
Path(os.environ["X2SYS_HOME"], kwargs["T"], f"{kwargs['T']}.tag")
205-
.read_text()
205+
.read_text(encoding="utf8")
206206
.strip()
207207
.split("\n")[-1]
208208
) # e.g. "-Dxyz -Etsv -I1/1"

0 commit comments

Comments
 (0)