Skip to content

Commit

Permalink
Fix pylint 2.11 consider-using-f-string checker errors (GenericMappin…
Browse files Browse the repository at this point in the history
…gTools#1517)

* Use f-strings throughout the project
* Fix C0201 consider-iterating-dictionary
* Fix W1514 unspecified-encoding
  • Loading branch information
weiji14 authored and Josh Sixsmith committed Dec 21, 2022
1 parent 17eb015 commit f00ffbf
Show file tree
Hide file tree
Showing 14 changed files with 69 additions and 107 deletions.
6 changes: 2 additions & 4 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,9 @@
release = __version__

# These enable substitutions using |variable| in the rst files
rst_epilog = """
rst_epilog = f"""
.. |year| replace:: {year}
""".format(
year=year
)
"""

html_last_updated_fmt = "%b %d, %Y"
html_title = "PyGMT"
Expand Down
4 changes: 2 additions & 2 deletions pygmt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def print_clib_info():
lines = ["GMT library information:"]
with Session() as ses:
for key in sorted(ses.info):
lines.append(" {}: {}".format(key, ses.info[key]))
lines.append(f" {key}: {ses.info[key]}")
print("\n".join(lines))


Expand Down Expand Up @@ -212,7 +212,7 @@ def test(doctest=True, verbose=True, coverage=False, figures=True):
if verbose:
args.append("-vv")
if coverage:
args.append("--cov={}".format(package))
args.append(f"--cov={package}")
args.append("--cov-report=term-missing")
if doctest:
args.append("--doctest-modules")
Expand Down
59 changes: 21 additions & 38 deletions pygmt/clib/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,7 @@ class Session:
... with GMTTempFile() as fout:
... # Call the grdinfo module with the virtual file as input
... # and the temp file as output.
... ses.call_module(
... "grdinfo", "{} -C ->{}".format(fin, fout.name)
... )
... ses.call_module("grdinfo", f"{fin} -C ->{fout.name}")
... # Read the contents of the temp file before it's deleted.
... print(fout.read().strip())
...
Expand Down Expand Up @@ -189,9 +187,8 @@ def __enter__(self):
if Version(version) < Version(self.required_version):
self.destroy()
raise GMTVersionError(
"Using an incompatible GMT version {}. Must be equal or newer than {}.".format(
version, self.required_version
)
f"Using an incompatible GMT version {version}. "
f"Must be equal or newer than {self.required_version}."
)
return self

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

if session is None:
raise GMTCLibError(
"Failed to create a GMT API session:\n{}".format(self._error_message)
f"Failed to create a GMT API session:\n{self._error_message}"
)

self.session_pointer = session
Expand Down Expand Up @@ -412,7 +409,7 @@ def destroy(self):
status = c_destroy_session(self.session_pointer)
if status:
raise GMTCLibError(
"Failed to destroy GMT API session:\n{}".format(self._error_message)
f"Failed to destroy GMT API session:\n{self._error_message}"
)

self.session_pointer = None
Expand Down Expand Up @@ -462,9 +459,7 @@ def get_default(self, name):

if status != 0:
raise GMTCLibError(
"Error getting default value for '{}' (error code {}).".format(
name, status
)
f"Error getting default value for '{name}' (error code {status})."
)

return value.value.decode()
Expand Down Expand Up @@ -503,9 +498,7 @@ def call_module(self, module, args):
)
if status != 0:
raise GMTCLibError(
"Module '{}' failed with status code {}:\n{}".format(
module, status, self._error_message
)
f"Module '{module}' failed with status code {status}:\n{self._error_message}"
)

def create_data(self, family, geometry, mode, **kwargs):
Expand Down Expand Up @@ -650,30 +643,24 @@ def _parse_constant(self, constant, valid, valid_modifiers=None):
nmodifiers = len(parts) - 1
if nmodifiers > 1:
raise GMTInvalidInput(
"Only one modifier is allowed in constants, {} given: '{}'".format(
nmodifiers, constant
)
f"Only one modifier is allowed in constants, {nmodifiers} given: '{constant}'"
)
if nmodifiers > 0 and valid_modifiers is None:
raise GMTInvalidInput(
"Constant modifiers not allowed since valid values were not "
+ "given: '{}'".format(constant)
+ f"given: '{constant}'"
)
if name not in valid:
raise GMTInvalidInput(
"Invalid constant argument '{}'. Must be one of {}.".format(
name, str(valid)
)
f"Invalid constant argument '{name}'. Must be one of {str(valid)}."
)
if (
nmodifiers > 0
and valid_modifiers is not None
and parts[1] not in valid_modifiers
):
raise GMTInvalidInput(
"Invalid constant modifier '{}'. Must be one of {}.".format(
parts[1], str(valid_modifiers)
)
f"Invalid constant modifier '{parts[1]}'. Must be one of {str(valid_modifiers)}."
)
integer_value = sum(self[part] for part in parts)
return integer_value
Expand Down Expand Up @@ -905,7 +892,7 @@ def put_matrix(self, dataset, matrix, pad=0):
self.session_pointer, dataset, gmt_type, pad, matrix_pointer
)
if status != 0:
raise GMTCLibError("Failed to put matrix of type {}.".format(matrix.dtype))
raise GMTCLibError(f"Failed to put matrix of type {matrix.dtype}.")

def write_data(self, family, geometry, mode, wesn, output, data):
"""
Expand Down Expand Up @@ -974,7 +961,7 @@ def write_data(self, family, geometry, mode, wesn, output, data):
data,
)
if status != 0:
raise GMTCLibError("Failed to write dataset to '{}'".format(output))
raise GMTCLibError(f"Failed to write dataset to '{output}'")

@contextmanager
def open_virtual_file(self, family, geometry, direction, data):
Expand Down Expand Up @@ -1036,7 +1023,7 @@ def open_virtual_file(self, family, geometry, direction, data):
... with lib.open_virtual_file(*vfargs) as vfile:
... # Send the output to a temp file so that we can read it
... with GMTTempFile() as ofile:
... args = "{} ->{}".format(vfile, ofile.name)
... args = f"{vfile} ->{ofile.name}"
... lib.call_module("info", args)
... print(ofile.read().strip())
...
Expand Down Expand Up @@ -1083,7 +1070,7 @@ def open_virtual_file(self, family, geometry, direction, data):
finally:
status = c_close_virtualfile(self.session_pointer, vfname.encode())
if status != 0:
raise GMTCLibError("Failed to close virtual file '{}'.".format(vfname))
raise GMTCLibError(f"Failed to close virtual file '{vfname}'.")

@contextmanager
def virtualfile_from_vectors(self, *vectors):
Expand Down Expand Up @@ -1131,9 +1118,7 @@ def virtualfile_from_vectors(self, *vectors):
... with ses.virtualfile_from_vectors(x, y, z) as fin:
... # Send the output to a file so that we can read it
... with GMTTempFile() as fout:
... ses.call_module(
... "info", "{} ->{}".format(fin, fout.name)
... )
... ses.call_module("info", f"{fin} ->{fout.name}")
... print(fout.read().strip())
...
<vector memory>: N = 3 <1/3> <4/6> <7/9>
Expand Down Expand Up @@ -1244,9 +1229,7 @@ def virtualfile_from_matrix(self, matrix):
... with ses.virtualfile_from_matrix(data) as fin:
... # Send the output to a file so that we can read it
... with GMTTempFile() as fout:
... ses.call_module(
... "info", "{} ->{}".format(fin, fout.name)
... )
... ses.call_module("info", f"{fin} ->{fout.name}")
... print(fout.read().strip())
...
<matrix memory>: N = 4 <0/9> <1/10> <2/11>
Expand Down Expand Up @@ -1327,7 +1310,7 @@ def virtualfile_from_grid(self, grid):
... with ses.virtualfile_from_grid(data) as fin:
... # Send the output to a file so that we can read it
... with GMTTempFile() as fout:
... args = "{} -L0 -Cn ->{}".format(fin, fout.name)
... args = f"{fin} -L0 -Cn ->{fout.name}"
... ses.call_module("grdinfo", args)
... print(fout.read().strip())
...
Expand Down Expand Up @@ -1508,7 +1491,7 @@ def extract_region(self):
>>> with Session() as lib:
... wesn = lib.extract_region()
...
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
0.00, 10.00, -20.00, -10.00
Using ISO country codes for the regions (for example ``'US.HI'`` for
Expand All @@ -1521,7 +1504,7 @@ def extract_region(self):
>>> with Session() as lib:
... wesn = lib.extract_region()
...
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
-164.71, -154.81, 18.91, 23.58
The country codes can have an extra argument that rounds the region a
Expand All @@ -1535,7 +1518,7 @@ def extract_region(self):
>>> with Session() as lib:
... wesn = lib.extract_region()
...
>>> print(", ".join(["{:.2f}".format(x) for x in wesn]))
>>> print(", ".join([f"{x:.2f}" for x in wesn]))
-165.00, -150.00, 15.00, 25.00
"""
c_extract_region = self.get_libgmt_func(
Expand Down
8 changes: 4 additions & 4 deletions pygmt/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class Figure:
>>> fig = Figure()
>>> fig.basemap(region="JP", projection="M3i", frame=True)
>>> # The fig.region attribute shows the WESN bounding box for the figure
>>> print(", ".join("{:.2f}".format(i) for i in fig.region))
>>> print(", ".join(f"{i:.2f}" for i in fig.region))
122.94, 145.82, 20.53, 45.52
"""

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

def _preprocess(self, **kwargs):
"""
Expand Down Expand Up @@ -358,9 +358,9 @@ def shift_origin(self, xshift=None, yshift=None):
self._preprocess()
args = ["-T"]
if xshift:
args.append("-X{}".format(xshift))
args.append(f"-X{xshift}")
if yshift:
args.append("-Y{}".format(yshift))
args.append(f"-Y{yshift}")

with Session() as lib:
lib.call_module("plot", " ".join(args))
Expand Down
11 changes: 4 additions & 7 deletions pygmt/helpers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ def fmt_docstring(module_func):
aliases = ["**Aliases:**\n"]
for arg in sorted(module_func.aliases):
alias = module_func.aliases[arg]
aliases.append("- {} = {}".format(arg, alias))
aliases.append(f"- {arg} = {alias}")
filler_text["aliases"] = "\n".join(aliases)

filler_text["table-like"] = " or ".join(
Expand Down Expand Up @@ -634,15 +634,12 @@ def kwargs_to_strings(**conversions):
... "A module that prints the arguments it received"
... print("{", end="")
... print(
... ", ".join(
... "'{}': {}".format(k, repr(kwargs[k]))
... for k in sorted(kwargs)
... ),
... ", ".join(f"'{k}': {repr(kwargs[k])}" for k in sorted(kwargs)),
... end="",
... )
... print("}")
... if args:
... print("args:", " ".join("{}".format(x) for x in args))
... print("args:", " ".join(f"{x}" for x in args))
>>> module(R=[1, 2, 3, 4])
{'R': '1/2/3/4'}
>>> # It's already a string, do nothing
Expand Down Expand Up @@ -690,7 +687,7 @@ def kwargs_to_strings(**conversions):
for arg, fmt in conversions.items():
if fmt not in valid_conversions:
raise GMTInvalidInput(
"Invalid conversion type '{}' for argument '{}'.".format(fmt, arg)
f"Invalid conversion type '{fmt}' for argument '{arg}'."
)

separators = {
Expand Down
5 changes: 3 additions & 2 deletions pygmt/helpers/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,9 @@ def wrapper(*args, ext="png", request=None, **kwargs):
for key in ["actual", "expected", "diff"]:
err[key] = os.path.relpath(err[key])
raise GMTImageComparisonFailure(
"images not close (RMS %(rms).3f):\n\t%(actual)s\n\t%(expected)s "
% err
f"images not close (RMS {err['rms']:.3f}):\n"
f"\t{err['actual']}\n"
f"\t{err['expected']}"
)
finally:
del fig_ref
Expand Down
6 changes: 2 additions & 4 deletions pygmt/src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ def __init__(self, **kwargs):
self.old_defaults[key] = lib.get_default(key)

# call gmt set to change GMT defaults
arg_str = " ".join(
["{}={}".format(key, value) for key, value in kwargs.items()]
)
arg_str = " ".join([f"{key}={value}" for key, value in kwargs.items()])
with Session() as lib:
lib.call_module("set", arg_str)

Expand All @@ -67,7 +65,7 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
# revert to initial values
arg_str = " ".join(
["{}={}".format(key, value) for key, value in self.old_defaults.items()]
[f"{key}={value}" for key, value in self.old_defaults.items()]
)
with Session() as lib:
lib.call_module("set", arg_str)
2 changes: 1 addition & 1 deletion pygmt/src/grd2cpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def grd2cpt(grid, **kwargs):
with file_context as infile:
if "H" not in kwargs.keys(): # if no output is set
arg_str = " ".join([infile, build_arg_string(kwargs)])
elif "H" in kwargs.keys(): # if output is set
if "H" in kwargs: # if output is set
outfile = kwargs.pop("H")
if not outfile or not isinstance(outfile, str):
raise GMTInvalidInput("'output' should be a proper file name.")
Expand Down
2 changes: 1 addition & 1 deletion pygmt/src/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,6 @@ def legend(self, spec=None, position="JTR+jTR+o0.2c", box="+gwhite+p1p", **kwarg
elif data_kind(spec) == "file":
specfile = spec
else:
raise GMTInvalidInput("Unrecognized data type: {}".format(type(spec)))
raise GMTInvalidInput(f"Unrecognized data type: {type(spec)}")
arg_str = " ".join([specfile, build_arg_string(kwargs)])
lib.call_module("legend", arg_str)
4 changes: 2 additions & 2 deletions pygmt/src/makecpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ def makecpt(**kwargs):
with Session() as lib:
if "W" in kwargs and "Ww" in kwargs:
raise GMTInvalidInput("Set only categorical or cyclic to True, not both.")
if "H" not in kwargs.keys(): # if no output is set
if "H" not in kwargs: # if no output is set
arg_str = build_arg_string(kwargs)
elif "H" in kwargs.keys(): # if output is set
elif "H" in kwargs: # if output is set
outfile = kwargs.pop("H")
if not outfile or not isinstance(outfile, str):
raise GMTInvalidInput("'output' should be a proper file name.")
Expand Down
2 changes: 1 addition & 1 deletion pygmt/src/meca.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ def update_pointers(data_pointers):
elif kind == "file":
file_context = dummy_context(spec)
else:
raise GMTInvalidInput("Unrecognized data type: {}".format(type(spec)))
raise GMTInvalidInput(f"Unrecognized data type: {type(spec)}")
with file_context as fname:
arg_str = " ".join([fname, build_arg_string(kwargs)])
lib.call_module("meca", arg_str)
2 changes: 1 addition & 1 deletion pygmt/src/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def surface(x=None, y=None, z=None, data=None, **kwargs):
elif kind == "vectors":
file_context = lib.virtualfile_from_vectors(x, y, z)
else:
raise GMTInvalidInput("Unrecognized data type: {}".format(type(data)))
raise GMTInvalidInput(f"Unrecognized data type: {type(data)}")
with file_context as infile:
if "G" not in kwargs.keys(): # if outgrid is unset, output to tmpfile
kwargs.update({"G": tmpfile.name})
Expand Down
2 changes: 1 addition & 1 deletion pygmt/src/x2sys_cross.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def x2sys_cross(tracks=None, outfile=None, **kwargs):
# $X2SYS_HOME/TAGNAME/TAGNAME.tag file
lastline = (
Path(os.environ["X2SYS_HOME"], kwargs["T"], f"{kwargs['T']}.tag")
.read_text()
.read_text(encoding="utf8")
.strip()
.split("\n")[-1]
) # e.g. "-Dxyz -Etsv -I1/1"
Expand Down
Loading

0 comments on commit f00ffbf

Please sign in to comment.