Skip to content

Commit

Permalink
Move from % string formatting syntax to f-string or .format()
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre-Sassoulas committed Feb 21, 2021
1 parent a1e553d commit 5bed07e
Show file tree
Hide file tree
Showing 39 changed files with 115 additions and 115 deletions.
2 changes: 1 addition & 1 deletion doc/conf.py
Expand Up @@ -55,7 +55,7 @@
# General information about the project.
project = "Pylint"
current_year = datetime.utcnow().year
copyright = "2003-{year}, Logilab, PyCQA and contributors".format(year=current_year)
copyright = f"2003-{current_year}, Logilab, PyCQA and contributors"

# The full version, including alpha/beta/rc tags.
release = version
Expand Down
22 changes: 11 additions & 11 deletions pylint/checkers/base.py
Expand Up @@ -1345,12 +1345,12 @@ def is_iterable(internal_node):
if is_iterable(default):
msg = value.pytype()
elif isinstance(default, astroid.Call):
msg = "%s() (%s)" % (value.name, value.qname())
msg = f"{value.name}() ({value.qname()})"
else:
msg = "%s (%s)" % (default.as_string(), value.qname())
msg = f"{default.as_string()} ({value.qname()})"
else:
# this argument is a name
msg = "%s (%s)" % (
msg = "{} ({})".format(
default.as_string(),
DEFAULT_ARGUMENT_SYMBOLS[value.qname()],
)
Expand Down Expand Up @@ -1695,7 +1695,7 @@ def _create_naming_options():
name_type = name_type.replace("_", "-")
name_options.append(
(
"%s-naming-style" % (name_type,),
f"{name_type}-naming-style",
{
"default": default_style,
"type": "choice",
Expand All @@ -1708,7 +1708,7 @@ def _create_naming_options():
)
name_options.append(
(
"%s-rgx" % (name_type,),
f"{name_type}-rgx",
{
"default": None,
"type": "regexp",
Expand Down Expand Up @@ -1852,7 +1852,7 @@ def open(self):
)
for group in self.config.name_group:
for name_type in group.split(":"):
self._name_group[name_type] = "group_%s" % (group,)
self._name_group[name_type] = f"group_{group}"

regexps, hints = self._create_naming_rules()
self._name_regexps = regexps
Expand All @@ -1869,12 +1869,12 @@ def _create_naming_rules(self):
hints = {}

for name_type in KNOWN_NAME_TYPES:
naming_style_option_name = "%s_naming_style" % (name_type,)
naming_style_option_name = f"{name_type}_naming_style"
naming_style_name = getattr(self.config, naming_style_option_name)

regexps[name_type] = NAMING_STYLES[naming_style_name].get_regex(name_type)

custom_regex_setting_name = "%s_rgx" % (name_type,)
custom_regex_setting_name = f"{name_type}_rgx"
custom_regex = getattr(self.config, custom_regex_setting_name, None)
if custom_regex is not None:
regexps[name_type] = custom_regex
Expand Down Expand Up @@ -2448,7 +2448,7 @@ def _is_nan(node) -> bool:
self.add_message(
"nan-comparison",
node=root_node,
args=("'{}'".format(root_node.as_string()), suggestion),
args=(f"'{root_node.as_string()}'", suggestion),
)

def _check_literal_comparison(self, literal, node):
Expand All @@ -2469,7 +2469,7 @@ def _check_misplaced_constant(self, node, left, right, operator):
if isinstance(right, astroid.Const):
return
operator = REVERSED_COMPS.get(operator, operator)
suggestion = "%s %s %r" % (right.as_string(), operator, left.value)
suggestion = f"{right.as_string()} {operator} {left.value!r}"
self.add_message("misplaced-comparison-constant", node=node, args=(suggestion,))

def _check_logical_tautology(self, node):
Expand All @@ -2496,7 +2496,7 @@ def _check_logical_tautology(self, node):
right_operand = right_operand.name

if left_operand == right_operand:
suggestion = "%s %s %s" % (left_operand, operator, right_operand)
suggestion = f"{left_operand} {operator} {right_operand}"
self.add_message("comparison-with-itself", node=node, args=(suggestion,))

def _check_callable_comparison(self, node):
Expand Down
4 changes: 2 additions & 2 deletions pylint/checkers/classes.py
Expand Up @@ -827,7 +827,7 @@ def _check_proper_bases(self, node):
if not ancestor:
continue
if isinstance(ancestor, astroid.Instance) and ancestor.is_subtype_of(
"%s.type" % (BUILTINS,)
f"{BUILTINS}.type"
):
continue
if (
Expand Down Expand Up @@ -1604,7 +1604,7 @@ def _check_first_arg_config(self, first, config, node, message, method_name):
valid = repr(config[0])
else:
valid = ", ".join(repr(v) for v in config[:-1])
valid = "%s or %r" % (valid, config[-1])
valid = "{} or {!r}".format(valid, config[-1])
self.add_message(message, args=(method_name, valid), node=node)

def _check_bases_classes(self, node):
Expand Down
6 changes: 3 additions & 3 deletions pylint/checkers/exceptions.py
Expand Up @@ -495,7 +495,7 @@ def gather_exceptions_from_handler(
def visit_binop(self, node):
if isinstance(node.parent, astroid.ExceptHandler):
# except (V | A)
suggestion = "Did you mean '(%s, %s)' instead?" % (
suggestion = "Did you mean '({}, {})' instead?".format(
node.left.as_string(),
node.right.as_string(),
)
Expand All @@ -505,7 +505,7 @@ def visit_binop(self, node):
def visit_compare(self, node):
if isinstance(node.parent, astroid.ExceptHandler):
# except (V < A)
suggestion = "Did you mean '(%s, %s)' instead?" % (
suggestion = "Did you mean '({}, {})' instead?".format(
node.left.as_string(),
", ".join(operand.as_string() for _, operand in node.ops),
)
Expand Down Expand Up @@ -568,7 +568,7 @@ def visit_tryexcept(self, node):

for previous_exc in exceptions_classes:
if previous_exc in exc_ancestors:
msg = "%s is an ancestor class of %s" % (
msg = "{} is an ancestor class of {}".format(
previous_exc.name,
exc.name,
)
Expand Down
12 changes: 6 additions & 6 deletions pylint/checkers/imports.py
Expand Up @@ -94,7 +94,7 @@ def _get_import_name(importnode, modname):

def _get_first_import(node, context, name, base, level, alias):
"""return the node where [base.]<name> is imported or None if not found"""
fullname = "%s.%s" % (base, name) if base else name
fullname = f"{base}.{name}" if base else name

first = None
found = False
Expand All @@ -110,7 +110,7 @@ def _get_first_import(node, context, name, base, level, alias):
elif isinstance(first, astroid.ImportFrom):
if level == first.level:
for imported_name, imported_alias in first.names:
if fullname == "%s.%s" % (first.modname, imported_name):
if fullname == f"{first.modname}.{imported_name}":
found = True
break
if (
Expand Down Expand Up @@ -161,10 +161,10 @@ def _repr_tree_defs(data, indent_str=None):
else:
files = "(%s)" % ",".join(sorted(files))
if indent_str is None:
lines.append("%s %s" % (mod, files))
lines.append(f"{mod} {files}")
sub_indent_str = " "
else:
lines.append(r"%s\-%s %s" % (indent_str, mod, files))
lines.append(fr"{indent_str}\-{mod} {files}")
if i == len(nodes) - 1:
sub_indent_str = "%s " % indent_str
else:
Expand Down Expand Up @@ -197,7 +197,7 @@ def _make_graph(filename, dep_info, sect, gtype):
report's section
"""
_dependencies_graph(filename, dep_info)
sect.append(Paragraph("%simports graph has been written to %s" % (gtype, filename)))
sect.append(Paragraph(f"{gtype}imports graph has been written to {filename}"))


# the import checker itself ###################################################
Expand Down Expand Up @@ -537,7 +537,7 @@ def visit_importfrom(self, node):
return
for name, _ in node.names:
if name != "*":
self._add_imported_module(node, "%s.%s" % (imported_module.name, name))
self._add_imported_module(node, f"{imported_module.name}.{name}")
else:
self._add_imported_module(node, imported_module.name)

Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/misc.py
Expand Up @@ -107,7 +107,7 @@ def open(self):

notes = "|".join(map(re.escape, self.config.notes))
if self.config.notes_rgx:
regex_string = r"#\s*(%s|%s)\b" % (notes, self.config.notes_rgx)
regex_string = fr"#\s*({notes}|{self.config.notes_rgx})\b"
else:
regex_string = r"#\s*(%s)\b" % (notes)

Expand Down
4 changes: 2 additions & 2 deletions pylint/checkers/refactoring/not_checker.py
Expand Up @@ -40,7 +40,7 @@ class NotChecker(checkers.BaseChecker):
skipped_nodes = (astroid.Set,)
# 'builtins' py3, '__builtin__' py2
skipped_classnames = [
"%s.%s" % (builtins.__name__, qname) for qname in ("set", "frozenset")
f"{builtins.__name__}.{qname}" for qname in ("set", "frozenset")
]

@utils.check_messages("unneeded-not")
Expand Down Expand Up @@ -77,7 +77,7 @@ def visit_unaryop(self, node):
and _type.qname() in self.skipped_classnames
):
return
suggestion = "%s %s %s" % (
suggestion = "{} {} {}".format(
left.as_string(),
self.reverse_op[operator],
right.as_string(),
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/refactoring/refactoring_checker.py
Expand Up @@ -937,7 +937,7 @@ def _check_consider_using_in(self, node):
values = list(collections.OrderedDict.fromkeys(values))
values.remove(common_variable)
values_string = ", ".join(values) if len(values) != 1 else values[0] + ","
suggestion = "%s %s (%s)" % (common_variable, comprehension, values_string)
suggestion = f"{common_variable} {comprehension} ({values_string})"

self.add_message("consider-using-in", node=node, args=(suggestion,))

Expand Down
4 changes: 2 additions & 2 deletions pylint/checkers/similar.py
Expand Up @@ -107,7 +107,7 @@ def _display_sims(self, sims):
couples = sorted(couples)
lineset = idx = None
for lineset, idx in couples:
print("==%s:%s" % (lineset.name, idx))
print(f"=={lineset.name}:{idx}")
if lineset:
for line in lineset._real_lines[idx : idx + num]:
print(" ", line.rstrip())
Expand Down Expand Up @@ -404,7 +404,7 @@ def close(self):
msg = []
lineset = idx = None
for lineset, idx in couples:
msg.append("==%s:%s" % (lineset.name, idx))
msg.append(f"=={lineset.name}:{idx}")
msg.sort()

if lineset:
Expand Down
4 changes: 2 additions & 2 deletions pylint/checkers/spelling.py
Expand Up @@ -66,7 +66,7 @@ class Chunker: # type: ignore
br = enchant.Broker()
dicts = br.list_dicts()
dict_choices = [""] + [d[0] for d in dicts]
dicts = ["%s (%s)" % (d[0], d[1].name) for d in dicts]
dicts = ["{} ({})".format(d[0], d[1].name) for d in dicts]
dicts = ", ".join(dicts)
instr = ""
else:
Expand Down Expand Up @@ -358,7 +358,7 @@ def _check_spelling(self, msgid, line, line_num):
col += 1
indicator = (" " * col) + ("^" * len(word))
all_suggestion = "' or '".join(suggestions)
args = (word, original_line, indicator, "'{}'".format(all_suggestion))
args = (word, original_line, indicator, f"'{all_suggestion}'")
self.add_message(msgid, line=line_num, args=args)

def process_tokens(self, tokens):
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/strings.py
Expand Up @@ -227,7 +227,7 @@ def get_access_path(key, parts):
if is_attribute:
path.append(f".{specifier}")
else:
path.append("[{!r}]".format(specifier))
path.append(f"[{specifier!r}]")
return str(key) + "".join(path)


Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/typecheck.py
Expand Up @@ -958,7 +958,7 @@ def visit_attribute(self, node):
):
continue

qualname = "{}.{}".format(owner.pytype(), node.attrname)
qualname = f"{owner.pytype()}.{node.attrname}"
if any(
pattern.match(qualname) for pattern in self._compiled_generated_members
):
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/utils.py
Expand Up @@ -313,7 +313,7 @@ def clobber_in_except(
(False, None) otherwise.
"""
if isinstance(node, astroid.AssignAttr):
return True, (node.attrname, "object %r" % (node.expr.as_string(),))
return True, (node.attrname, f"object {node.expr.as_string()!r}")
if isinstance(node, astroid.AssignName):
name = node.name
if is_builtin(name):
Expand Down
12 changes: 6 additions & 6 deletions pylint/checkers/variables.py
Expand Up @@ -181,7 +181,7 @@ def _get_unpacking_extra_info(node, inferred):
elif inferred.lineno:
more = " defined at line %s" % inferred.lineno
elif inferred.lineno:
more = " defined at line %s of %s" % (inferred.lineno, inferred_module)
more = f" defined at line {inferred.lineno} of {inferred_module}"
return more


Expand Down Expand Up @@ -1636,20 +1636,20 @@ def _check_is_unused(self, name, node, stmt, global_names, nonlocal_names):
else:
if isinstance(stmt, astroid.Import):
if asname is not None:
msg = "%s imported as %s" % (qname, asname)
msg = f"{qname} imported as {asname}"
else:
msg = "import %s" % name
self.add_message("unused-import", args=msg, node=stmt)
return
if isinstance(stmt, astroid.ImportFrom):
if asname is not None:
msg = "%s imported from %s as %s" % (
msg = "{} imported from {} as {}".format(
qname,
stmt.modname,
asname,
)
else:
msg = "%s imported from %s" % (name, stmt.modname)
msg = f"{name} imported from {stmt.modname}"
self.add_message("unused-import", args=msg, node=stmt)
return
message_name = "unused-variable"
Expand Down Expand Up @@ -2002,7 +2002,7 @@ def _check_imports(self, not_consumed):
if as_name is None:
msg = "import %s" % imported_name
else:
msg = "%s imported as %s" % (imported_name, as_name)
msg = f"{imported_name} imported as {as_name}"
if not _is_type_checking_import(stmt):
self.add_message("unused-import", args=msg, node=stmt)
elif isinstance(stmt, astroid.ImportFrom) and stmt.modname != FUTURE:
Expand All @@ -2024,7 +2024,7 @@ def _check_imports(self, not_consumed):
self.add_message("unused-wildcard-import", args=name, node=stmt)
else:
if as_name is None:
msg = "%s imported from %s" % (imported_name, stmt.modname)
msg = f"{imported_name} imported from {stmt.modname}"
else:
fields = (imported_name, stmt.modname, as_name)
msg = "%s imported from %s as %s" % fields
Expand Down
4 changes: 2 additions & 2 deletions pylint/config/__init__.py
Expand Up @@ -68,7 +68,7 @@

def _get_pdata_path(base_name, recurs):
base_name = base_name.replace(os.sep, "_")
return os.path.join(PYLINT_HOME, "%s%s%s" % (base_name, recurs, ".stats"))
return os.path.join(PYLINT_HOME, "{}{}{}".format(base_name, recurs, ".stats"))


def load_results(base):
Expand All @@ -91,7 +91,7 @@ def save_results(results, base):
with open(data_file, "wb") as stream:
pickle.dump(results, stream)
except OSError as ex:
print("Unable to create file %s: %s" % (data_file, ex), file=sys.stderr)
print(f"Unable to create file {data_file}: {ex}", file=sys.stderr)


def find_pylintrc():
Expand Down

0 comments on commit 5bed07e

Please sign in to comment.