提交 27bd9aaf authored 作者: Ben Mares's avatar Ben Mares

Fix UP031: Use format specifiers instead of percent format

上级 75b57060
......@@ -75,9 +75,9 @@ def main():
if items:
_logger.warning(
"There remain elements in the cache dir that you may "
"need to erase manually. The cache dir is:\n %s\n"
f"need to erase manually. The cache dir is:\n {config.compiledir}\n"
'You can also call "pytensor-cache purge" to '
"remove everything from that directory." % config.compiledir
"remove everything from that directory."
)
_logger.debug(f"Remaining elements ({len(items)}): {', '.join(items)}")
elif sys.argv[1] == "list":
......
......@@ -105,7 +105,7 @@ class PdbBreakpoint(Op):
except Exception:
raise ValueError(
"Some of the inputs to the PdbBreakpoint op "
"'%s' could not be casted to NumPy arrays" % self.name
f"'{self.name}' could not be casted to NumPy arrays"
)
print("\n")
......
......@@ -709,7 +709,7 @@ class OpFromGraph(Op, HasInnerGraph):
if not isinstance(roverrides_l, list):
raise TypeError(
"Rop overriding function should return a list, "
'got "%s"' % type(roverrides_l)
f'got "{type(roverrides_l)}"'
)
all_rops_l, all_rops_ov_l = zip(
*[
......
......@@ -252,7 +252,7 @@ class FromFunctionOp(Op):
return hash(type(self)) ^ hash(self.__fn)
def __str__(self):
return "FromFunctionOp{%s}" % self.__fn.__name__
return f"FromFunctionOp{{{self.__fn.__name__}}}"
def perform(self, node, inputs, outputs):
outs = self.__fn(*inputs)
......
......@@ -262,8 +262,13 @@ class Params(dict):
self.__dict__.update(__params_type__=params_type, __signatures__=None)
def __repr__(self):
return "Params(%s)" % ", ".join(
[(f"{k}:{type(self[k]).__name__}:{self[k]}") for k in sorted(self.keys())]
return "Params({})".format(
", ".join(
[
(f"{k}:{type(self[k]).__name__}:{self[k]}")
for k in sorted(self.keys())
]
)
)
def __getattr__(self, key):
......@@ -346,13 +351,11 @@ class ParamsType(CType):
for attribute_name in kwargs:
if re.match("^[A-Za-z_][A-Za-z0-9_]*$", attribute_name) is None:
raise AttributeError(
'ParamsType: attribute "%s" should be a valid identifier.'
% attribute_name
f'ParamsType: attribute "{attribute_name}" should be a valid identifier.'
)
if attribute_name in c_cpp_keywords:
raise SyntaxError(
'ParamsType: "%s" is a potential C/C++ keyword and should not be used as attribute name.'
% attribute_name
f'ParamsType: "{attribute_name}" is a potential C/C++ keyword and should not be used as attribute name.'
)
type_instance = kwargs[attribute_name]
type_name = type_instance.__class__.__name__
......@@ -424,8 +427,10 @@ class ParamsType(CType):
return super().__getattr__(self, key)
def __repr__(self):
return "ParamsType<%s>" % ", ".join(
[(f"{self.fields[i]}:{self.types[i]}") for i in range(self.length)]
return "ParamsType<{}>".format(
", ".join(
[(f"{self.fields[i]}:{self.types[i]}") for i in range(self.length)]
)
)
def __eq__(self, other):
......@@ -733,18 +738,18 @@ class ParamsType(CType):
struct_cleanup = "\n".join(c_cleanup_list)
struct_extract = "\n\n".join(c_extract_list)
struct_extract_method = """
void extract(PyObject* object, int field_pos) {
switch(field_pos) {
void extract(PyObject* object, int field_pos) {{
switch(field_pos) {{
// Extraction cases.
%s
{}
// Default case.
default:
PyErr_Format(PyExc_TypeError, "ParamsType: no extraction defined for a field %%d.", field_pos);
PyErr_Format(PyExc_TypeError, "ParamsType: no extraction defined for a field %d.", field_pos);
this->setErrorOccurred();
break;
}
}
""" % (
}}
}}
""".format(
"\n".join(
[
("case %d: extract_%s(object); break;" % (i, self.fields[i]))
......@@ -866,7 +871,7 @@ class ParamsType(CType):
struct_name=self.name,
length=self.length,
fail=sub["fail"],
fields_list='"%s"' % '", "'.join(self.fields),
fields_list='"{}"'.format('", "'.join(self.fields)),
)
)
......
......@@ -355,8 +355,13 @@ def raise_with_op(
+ f"\nInputs values: {scalar_values}"
)
if verbosity == "high":
detailed_err_msg += "\nInputs type_num: %s" % str(
[getattr(getattr(i[0], "dtype", ""), "num", "") for i in thunk.inputs]
detailed_err_msg += "\nInputs type_num: {}".format(
str(
[
getattr(getattr(i[0], "dtype", ""), "num", "")
for i in thunk.inputs
]
)
)
detailed_err_msg += f"\nOutputs clients: {clients}\n"
......
......@@ -475,7 +475,7 @@ class ScalarType(CType, HasDataType, HasShape):
sub,
name=name,
dtype=specs[1],
pyarr_type="Py%sArrType_Type" % specs[2],
pyarr_type=f"Py{specs[2]}ArrType_Type",
)
)
else:
......
......@@ -180,9 +180,9 @@ class Gemv(Op):
def __str__(self):
if self.inplace:
return "%s{inplace}" % self.__class__.__name__
return f"{self.__class__.__name__}{{inplace}}"
else:
return "%s{no_inplace}" % self.__class__.__name__
return f"{self.__class__.__name__}{{no_inplace}}"
def make_node(self, y, alpha, A, x, beta):
y = ptb.as_tensor_variable(y)
......@@ -279,9 +279,9 @@ class Ger(Op):
def __str__(self):
if self.destructive:
return "%s{destructive}" % self.__class__.__name__
return f"{self.__class__.__name__}{{destructive}}"
else:
return "%s{non-destructive}" % self.__class__.__name__
return f"{self.__class__.__name__}{{non-destructive}}"
def make_node(self, A, alpha, x, y):
A = ptb.as_tensor_variable(A)
......@@ -1811,9 +1811,10 @@ class BatchedDot(COp):
f"{strides}[{i}] > 0 && {strides}[{i}] % type_size == 0"
for i in range(1, ndim)
),
"(%s)"
% " || ".join(
f"{strides}[{i}] == type_size" for i in range(1, ndim)
"({})".format(
" || ".join(
f"{strides}[{i}] == type_size" for i in range(1, ndim)
)
),
]
)
......
......@@ -1098,14 +1098,14 @@ class Elemwise(OpenMPOp):
all_broadcastable = all(s == 1 for s in var.type.shape)
cond1 = " && ".join(
[
"PyArray_ISCONTIGUOUS(%s)" % arr
f"PyArray_ISCONTIGUOUS({arr})"
for arr, var in z
if not all_broadcastable
]
)
cond2 = " && ".join(
[
"PyArray_ISFORTRAN(%s)" % arr
f"PyArray_ISFORTRAN({arr})"
for arr, var in z
if not all_broadcastable
]
......
......@@ -652,8 +652,8 @@ class Repeat(Op):
if repeats.dtype in numpy_unsupported_dtypes:
raise TypeError(
(
"dtypes %s are not supported by numpy.repeat "
"for the 'repeats' parameter, " % str(numpy_unsupported_dtypes)
f"dtypes {numpy_unsupported_dtypes!s} are not supported by numpy.repeat "
"for the 'repeats' parameter, "
),
repeats.dtype,
)
......@@ -882,8 +882,8 @@ class FillDiagonal(Op):
val = ptb.as_tensor_variable(val)
if a.ndim < 2:
raise TypeError(
"%s: first parameter must have at least"
" two dimensions" % self.__class__.__name__
f"{self.__class__.__name__}: first parameter must have at least"
" two dimensions"
)
elif val.ndim != 0:
raise TypeError(
......@@ -892,8 +892,8 @@ class FillDiagonal(Op):
val = ptb.cast(val, dtype=upcast(a.dtype, val.dtype))
if val.dtype != a.dtype:
raise TypeError(
"%s: type of second parameter must be the same as"
" the first's" % self.__class__.__name__
f"{self.__class__.__name__}: type of second parameter must be the same as"
" the first's"
)
return Apply(self, [a, val], [a.type()])
......@@ -926,8 +926,8 @@ class FillDiagonal(Op):
return [None, None]
elif a.ndim > 2:
raise NotImplementedError(
"%s: gradient is currently implemented"
" for matrices only" % self.__class__.__name__
f"{self.__class__.__name__}: gradient is currently implemented"
" for matrices only"
)
wr_a = fill_diagonal(grad, 0) # valid for any number of dimensions
# diag is only valid for matrices
......@@ -984,8 +984,8 @@ class FillDiagonalOffset(Op):
offset = ptb.as_tensor_variable(offset)
if a.ndim != 2:
raise TypeError(
"%s: first parameter must have exactly"
" two dimensions" % self.__class__.__name__
f"{self.__class__.__name__}: first parameter must have exactly"
" two dimensions"
)
elif val.ndim != 0:
raise TypeError(
......@@ -998,8 +998,8 @@ class FillDiagonalOffset(Op):
val = ptb.cast(val, dtype=upcast(a.dtype, val.dtype))
if val.dtype != a.dtype:
raise TypeError(
"%s: type of second parameter must be the same"
" as the first's" % self.__class__.__name__
f"{self.__class__.__name__}: type of second parameter must be the same"
" as the first's"
)
elif offset.dtype not in integer_dtypes:
raise TypeError(
......
......@@ -20,8 +20,7 @@ class RFFTOp(Op):
a = as_tensor_variable(a)
if a.ndim < 2:
raise TypeError(
"%s: input must have dimension > 2, with first dimension batches"
% self.__class__.__name__
f"{self.__class__.__name__}: input must have dimension > 2, with first dimension batches"
)
if s is None:
......@@ -31,8 +30,8 @@ class RFFTOp(Op):
s = as_tensor_variable(s)
if s.dtype not in integer_dtypes:
raise TypeError(
"%s: length of the transformed axis must be"
" of type integer" % self.__class__.__name__
f"{self.__class__.__name__}: length of the transformed axis must be"
" of type integer"
)
return Apply(self, [a, s], [self.output_type(a)()])
......@@ -92,8 +91,8 @@ class IRFFTOp(Op):
s = as_tensor_variable(s)
if s.dtype not in integer_dtypes:
raise TypeError(
"%s: length of the transformed axis must be"
" of type integer" % self.__class__.__name__
f"{self.__class__.__name__}: length of the transformed axis must be"
" of type integer"
)
return Apply(self, [a, s], [self.output_type(a)()])
......
......@@ -28,7 +28,7 @@ class LoadFromDisk(Op):
if mmap_mode not in (None, "c"):
raise ValueError(
"The only supported values for mmap_mode "
"are None and 'c', got %s" % mmap_mode
f"are None and 'c', got {mmap_mode}"
)
self.mmap_mode = mmap_mode
......
......@@ -1540,7 +1540,7 @@ class Mean(FixedOpCAReduce):
def __str__(self):
if self.axis is not None:
return "Mean{%s}" % (", ".join(str(x) for x in self.axis))
return "Mean{{{}}}".format(", ".join(str(x) for x in self.axis))
else:
return "Mean"
......
......@@ -2174,7 +2174,7 @@ class AdvancedIncSubtensor1(COp):
else:
msg += ",inc"
return self.__class__.__name__ + "{%s}" % msg
return self.__class__.__name__ + f"{{{msg}}}"
def make_node(self, x, y, ilist):
x_ = as_tensor_variable(x)
......
......@@ -365,8 +365,7 @@ def get_root():
me_dir = os.path.normcase(os.path.splitext(my_path)[0])
vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
print("Warning: build in %s is using versioneer.py from %s"
% (os.path.dirname(my_path), versioneer_py))
print(f"Warning: build in {os.path.dirname(my_path)} is using versioneer.py from {versioneer_py}")
except NameError:
pass
return root
......@@ -455,18 +454,18 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(f"unable to run {dispcmd}")
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print(f"unable to find command, tried {commands}")
return None, None
stdout = process.communicate()[0].strip().decode()
if process.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
print(f"unable to run {dispcmd} (error)")
print(f"stdout was {stdout}")
return None, process.returncode
return stdout, process.returncode
......@@ -1198,9 +1197,9 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# "stabilization", as well as "HEAD" and "master".
tags = {r for r in refs if re.search(r'\d', r)}
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
print("discarding '{}', no digits".format(",".join(refs - tags)))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
print("likely tags: {}".format(",".join(sorted(tags))))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
......@@ -1211,7 +1210,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not re.match(r'\d', r):
continue
if verbose:
print("picking %s" % r)
print(f"picking {r}")
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
......@@ -1247,7 +1246,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
hide_stderr=not verbose)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
print(f"Directory {root} not under git control")
raise NotThisMethod("'git rev-parse --git-dir' returned error")
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
......@@ -1320,8 +1319,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparsable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = (f"unable to parse git-describe output: '{describe_out}'")
return pieces
# tag
......@@ -1330,8 +1328,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
pieces["error"] = (f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'")
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
......@@ -1414,8 +1411,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
root = os.path.dirname(root) # up a level
if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
print(f"Tried directories {rootdirs!s} but none started with prefix {parentdir_prefix}")
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
......@@ -1462,7 +1458,7 @@ def write_to_version_file(filename, versions):
with open(filename, "w") as f:
f.write(SHORT_VERSION_PY % contents)
print("set %s to '%s'" % (filename, versions["version"]))
print("set {} to '{}'".format(filename, versions["version"]))
def plus_or_dot(pieces):
......@@ -1578,13 +1574,13 @@ def render_pep440_post(pieces):
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
rendered += "g{}".format(pieces["short"])
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
rendered += "+g{}".format(pieces["short"])
return rendered
......@@ -1603,7 +1599,7 @@ def render_pep440_post_branch(pieces):
if pieces["branch"] != "master":
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
rendered += "g{}".format(pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
......@@ -1611,7 +1607,7 @@ def render_pep440_post_branch(pieces):
rendered = "0.post%d" % pieces["distance"]
if pieces["branch"] != "master":
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
rendered += "+g{}".format(pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
......@@ -1708,7 +1704,7 @@ def render(pieces, style):
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
raise ValueError(f"unknown style '{style}'")
return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
......@@ -1733,7 +1729,7 @@ def get_versions(verbose=False):
assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
handlers = HANDLERS.get(cfg.VCS)
assert handlers, "unrecognized VCS '%s'" % cfg.VCS
assert handlers, f"unrecognized VCS '{cfg.VCS}'"
verbose = verbose or cfg.verbose
assert cfg.versionfile_source is not None, \
"please set versioneer.versionfile_source"
......@@ -1754,7 +1750,7 @@ def get_versions(verbose=False):
keywords = get_keywords_f(versionfile_abs)
ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
if verbose:
print("got version from expanded keyword %s" % ver)
print(f"got version from expanded keyword {ver}")
return ver
except NotThisMethod:
pass
......@@ -1762,7 +1758,7 @@ def get_versions(verbose=False):
try:
ver = versions_from_file(versionfile_abs)
if verbose:
print("got version from file %s %s" % (versionfile_abs, ver))
print(f"got version from file {versionfile_abs} {ver}")
return ver
except NotThisMethod:
pass
......@@ -1773,7 +1769,7 @@ def get_versions(verbose=False):
pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
ver = render(pieces, cfg.style)
if verbose:
print("got version from VCS %s" % ver)
print(f"got version from VCS {ver}")
return ver
except NotThisMethod:
pass
......@@ -1782,7 +1778,7 @@ def get_versions(verbose=False):
if cfg.parentdir_prefix:
ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
if verbose:
print("got version from parentdir %s" % ver)
print(f"got version from parentdir {ver}")
return ver
except NotThisMethod:
pass
......@@ -1839,12 +1835,12 @@ def get_cmdclass(cmdclass=None):
def run(self):
vers = get_versions(verbose=True)
print("Version: %s" % vers["version"])
print(" full-revisionid: %s" % vers.get("full-revisionid"))
print(" dirty: %s" % vers.get("dirty"))
print(" date: %s" % vers.get("date"))
print("Version: {}".format(vers["version"]))
print(" full-revisionid: {}".format(vers.get("full-revisionid")))
print(" dirty: {}".format(vers.get("dirty")))
print(" date: {}".format(vers.get("date")))
if vers["error"]:
print(" error: %s" % vers["error"])
print(" error: {}".format(vers["error"]))
cmds["version"] = cmd_version
# we override "build_py" in setuptools
......@@ -1886,7 +1882,7 @@ def get_cmdclass(cmdclass=None):
if cfg.versionfile_build:
target_versionfile = os.path.join(self.build_lib,
cfg.versionfile_build)
print("UPDATING %s" % target_versionfile)
print(f"UPDATING {target_versionfile}")
write_to_version_file(target_versionfile, versions)
cmds["build_py"] = cmd_build_py
......@@ -1918,7 +1914,7 @@ def get_cmdclass(cmdclass=None):
"version update. This can happen if you are running build_ext "
"without first running build_py.")
return
print("UPDATING %s" % target_versionfile)
print(f"UPDATING {target_versionfile}")
write_to_version_file(target_versionfile, versions)
cmds["build_ext"] = cmd_build_ext
......@@ -1937,7 +1933,7 @@ def get_cmdclass(cmdclass=None):
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
print(f"UPDATING {target_versionfile}")
write_to_version_file(target_versionfile, versions)
_build_exe.run(self)
......@@ -1966,7 +1962,7 @@ def get_cmdclass(cmdclass=None):
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
print(f"UPDATING {target_versionfile}")
write_to_version_file(target_versionfile, versions)
_py2exe.run(self)
......@@ -2042,7 +2038,7 @@ def get_cmdclass(cmdclass=None):
# (remembering that it may be a hardlink) and replace it with an
# updated value
target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
print("UPDATING %s" % target_versionfile)
print(f"UPDATING {target_versionfile}")
write_to_version_file(target_versionfile,
self._versioneer_generated_versions)
cmds["sdist"] = cmd_sdist
......@@ -2114,7 +2110,7 @@ def do_setup():
print(CONFIG_ERROR, file=sys.stderr)
return 1
print(" creating %s" % cfg.versionfile_source)
print(f" creating {cfg.versionfile_source}")
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG % {"DOLLAR": "$",
......@@ -2135,17 +2131,17 @@ def do_setup():
module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0]
snippet = INIT_PY_SNIPPET.format(module)
if OLD_SNIPPET in old:
print(" replacing boilerplate in %s" % ipy)
print(f" replacing boilerplate in {ipy}")
with open(ipy, "w") as f:
f.write(old.replace(OLD_SNIPPET, snippet))
elif snippet not in old:
print(" appending to %s" % ipy)
print(f" appending to {ipy}")
with open(ipy, "a") as f:
f.write(snippet)
else:
print(" %s unmodified" % ipy)
print(f" {ipy} unmodified")
else:
print(" %s doesn't exist, ok" % ipy)
print(f" {ipy} doesn't exist, ok")
ipy = None
# Make VCS-specific changes. For git, this means creating/changing
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论