Skip to content

Commit

Permalink
Migrate from % syntax or bad format() syntax to fstring
Browse files Browse the repository at this point in the history
We can do that in python 3.6
  • Loading branch information
Pierre-Sassoulas committed Feb 21, 2021
1 parent 5bed07e commit ee91075
Show file tree
Hide file tree
Showing 15 changed files with 62 additions and 127 deletions.
15 changes: 3 additions & 12 deletions pylint/checkers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1331,7 +1331,6 @@ def is_iterable(internal_node):
isinstance(value, astroid.Instance)
and value.qname() in DEFAULT_ARGUMENT_SYMBOLS
):

if value is default:
msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()]
elif isinstance(value, astroid.Instance) or is_iterable(value):
Expand All @@ -1350,10 +1349,7 @@ def is_iterable(internal_node):
msg = f"{default.as_string()} ({value.qname()})"
else:
# this argument is a name
msg = "{} ({})".format(
default.as_string(),
DEFAULT_ARGUMENT_SYMBOLS[value.qname()],
)
msg = f"{default.as_string()} ({DEFAULT_ARGUMENT_SYMBOLS[value.qname()]})"
self.add_message("dangerous-default-value", node=node, args=(msg,))

@utils.check_messages("unreachable", "lost-exception")
Expand Down Expand Up @@ -2437,14 +2433,9 @@ def _is_nan(node) -> bool:
if checking_for_absence:
absence_text = "not "
if nan_left:
suggestion = "'{}math.isnan({})'".format(
absence_text, right_value.as_string()
)
suggestion = f"'{absence_text}math.isnan({right_value.as_string()})'"
else:
suggestion = "'{}math.isnan({})'".format(
absence_text, left_value.as_string()
)

suggestion = f"'{absence_text}math.isnan({left_value.as_string()})'"
self.add_message(
"nan-comparison",
node=root_node,
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/classes.py
Original file line number Diff line number Diff line change
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 = "{} or {!r}".format(valid, config[-1])
valid = f"{valid} or {config[-1]!r}"
self.add_message(message, args=(method_name, valid), node=node)

def _check_bases_classes(self, node):
Expand Down
6 changes: 1 addition & 5 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1643,11 +1643,7 @@ def _check_is_unused(self, name, node, stmt, global_names, nonlocal_names):
return
if isinstance(stmt, astroid.ImportFrom):
if asname is not None:
msg = "{} imported from {} as {}".format(
qname,
stmt.modname,
asname,
)
msg = f"{qname} imported from {stmt.modname} as {asname}"
else:
msg = f"{name} imported from {stmt.modname}"
self.add_message("unused-import", args=msg, node=stmt)
Expand Down
2 changes: 1 addition & 1 deletion pylint/config/__init__.py
Original file line number Diff line number Diff line change
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, "{}{}{}".format(base_name, recurs, ".stats"))
return os.path.join(PYLINT_HOME, f"{base_name}{recurs}.stats")


def load_results(base):
Expand Down
72 changes: 24 additions & 48 deletions pylint/config/man_help_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,9 @@ def format_option(self, option):
help_string = help_string.replace("[current:", "[default:")
else:
help_string = ""
return """.IP "{}"
{}
""".format(
optstring,
help_string,
)
return f""".IP "{optstring}"
{help_string}
"""

def format_head(self, optparser, pkginfo, section=1):
long_desc = ""
Expand All @@ -50,12 +47,10 @@ def format_head(self, optparser, pkginfo, section=1):
short_desc = self.format_short_description(pgm, pkginfo.description)
if hasattr(pkginfo, "long_desc"):
long_desc = self.format_long_description(pgm, pkginfo.long_desc)
return "{}\n{}\n{}\n{}".format(
self.format_title(pgm, section),
short_desc,
self.format_synopsis(pgm),
long_desc,
)
return f"""{self.format_title(pgm, section)}
{short_desc}
{self.format_synopsis(pgm)}
{long_desc}"""

@staticmethod
def format_title(pgm, section):
Expand All @@ -64,69 +59,50 @@ def format_title(pgm, section):

@staticmethod
def format_short_description(pgm, short_desc):
return """.SH NAME
.B {}
\\- {}
""".format(
pgm,
short_desc.strip(),
)
return f""".SH NAME
.B {pgm}
\\- {short_desc.strip()}
"""

@staticmethod
def format_synopsis(pgm):
return (
""".SH SYNOPSIS
.B %s
return f""".SH SYNOPSIS
.B {pgm}
[
.I OPTIONS
] [
.I <arguments>
]
"""
% pgm
)

@staticmethod
def format_long_description(pgm, long_desc):
long_desc = "\n".join(line.lstrip() for line in long_desc.splitlines())
long_desc = long_desc.replace("\n.\n", "\n\n")
if long_desc.lower().startswith(pgm):
long_desc = long_desc[len(pgm) :]
return """.SH DESCRIPTION
.B {}
{}
""".format(
pgm,
long_desc.strip(),
)
return f""".SH DESCRIPTION
.B {pgm}
{long_desc.strip()}
"""

@staticmethod
def format_tail(pkginfo):
tail = """.SH SEE ALSO
/usr/share/doc/pythonX.Y-{}/
tail = f""".SH SEE ALSO
/usr/share/doc/pythonX.Y-{getattr(pkginfo, "debian_name", "pylint")}/
.SH BUGS
Please report bugs on the project\'s mailing list:
{}
{pkginfo.mailinglist}
.SH AUTHOR
{} <{}>
""".format(
getattr(pkginfo, "debian_name", "pylint"),
pkginfo.mailinglist,
pkginfo.author,
pkginfo.author_email,
)

{pkginfo.author} <{pkginfo.author_email}>
"""
if hasattr(pkginfo, "copyright"):
tail += (
"""
tail += f"""
.SH COPYRIGHT
%s
{pkginfo.copyright}
"""
% pkginfo.copyright
)

return tail


Expand Down
8 changes: 3 additions & 5 deletions pylint/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ class WarningScope:
NODE = "node-based-msg"


full_version = "pylint {}\nastroid {}\nPython {}".format(
pylint_version,
astroid_version,
sys.version,
)
full_version = f"""pylint {pylint_version}
astroid {astroid_version}
Python { sys.version}"""
8 changes: 3 additions & 5 deletions pylint/message/message_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,15 @@ def __init__(
@staticmethod
def check_msgid(msgid: str) -> None:
if len(msgid) != 5:
raise InvalidMessageError("Invalid message id %r" % msgid)
raise InvalidMessageError(f"Invalid message id {msgid!r}")
if msgid[0] not in MSG_TYPES:
raise InvalidMessageError(
"Bad message type {} in {!r}".format(msgid[0], msgid)
)
raise InvalidMessageError(f"Bad message type {msgid[0]} in {msgid!r}")

def __repr__(self):
return f"MessageDefinition:{self.symbol} ({self.msgid})"

def __str__(self):
return "{}:\n{} {}".format(repr(self), self.msg, self.description)
return f"{repr(self)}:\n{self.msg} {self.description}"

def may_be_emitted(self):
"""return True if message may be emitted using the current interpreter"""
Expand Down
12 changes: 5 additions & 7 deletions pylint/message/message_id_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,7 @@ def _raise_duplicate_symbol(msgid, symbol, other_symbol):
symbols = [symbol, other_symbol]
symbols.sort()
error_message = f"Message id '{msgid}' cannot have both "
error_message += "'{other_symbol}' and '{symbol}' as symbolic name.".format(
other_symbol=symbols[0], symbol=symbols[1]
)
error_message += f"'{symbols[0]}' and '{symbols[1]}' as symbolic name."
raise InvalidMessageError(error_message)

@staticmethod
Expand All @@ -97,10 +95,10 @@ def _raise_duplicate_msgid(symbol, msgid, other_msgid):
msgids = [msgid, other_msgid]
msgids.sort()
error_message = (
"Message symbol '{symbol}' cannot be used for "
"'{other_msgid}' and '{msgid}' at the same time."
" If you're creating an 'old_names' use 'old-{symbol}' as the old symbol."
).format(symbol=symbol, other_msgid=msgids[0], msgid=msgids[1])
f"Message symbol '{symbol}' cannot be used for "
f"'{msgids[0]}' and '{msgids[1]}' at the same time."
f" If you're creating an 'old_names' use 'old-{symbol}' as the old symbol."
)
raise InvalidMessageError(error_message)

def get_active_msgids(self, msgid_or_symbol: str) -> List[str]:
Expand Down
8 changes: 2 additions & 6 deletions pylint/pyreverse/inspector.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def visit_importfrom(self, node):
if name[0] == "*":
continue
# analyze dependencies
fullname = "{}.{}".format(basename, name[0])
fullname = f"{basename}.{name[0]}"
if fullname.find(".") > -1:
try:
fullname = modutils.get_module_part(fullname, context_file)
Expand Down Expand Up @@ -319,11 +319,7 @@ def get_children(self):
return self.modules

def __repr__(self):
return "<Project {!r} at {} ({} modules)>".format(
self.name,
id(self),
len(self.modules),
)
return f"<Project {self.name!r} at {id(self)} ({len(self.modules)} modules)>"


def project_from_files(
Expand Down
7 changes: 3 additions & 4 deletions pylint/pyreverse/vcgutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,13 @@ def _write_attributes(self, attributes_dict, **args):
if not _type:
self._stream.write(f'{self._indent}{key}:"{value}"\n')
elif _type == 1:
self._stream.write("{}{}:{}\n".format(self._indent, key, int(value)))
self._stream.write(f"{self._indent}{key}:{int(value)}\n")
elif value in _type:
self._stream.write(f"{self._indent}{key}:{value}\n")
else:
raise Exception(
"""value %s isn\'t correct for attribute %s
correct values are %s"""
% (value, key, _type)
f"""value {value} isn't correct for attribute {key}
correct values are {type}"""
)

def _inc_indent(self):
Expand Down
6 changes: 1 addition & 5 deletions pylint/testutils/lint_module_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,7 @@ def _should_be_skipped_due_to_version(self):
)

def __str__(self):
return "{} ({}.{})".format(
self._test_file.base,
self.__class__.__module__,
self.__class__.__name__,
)
return f"{self._test_file.base} ({self.__class__.__module__}.{self.__class__.__name__})"

@staticmethod
def get_expected_messages(stream):
Expand Down
2 changes: 1 addition & 1 deletion pylint/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def get_module_and_frameid(node):

def get_rst_title(title, character):
"""Permit to get a title formatted as ReStructuredText test (underlined with a chosen character)."""
return "{}\n{}\n".format(title, character * len(title))
return f"{title}\n{character * len(title)}\n"


def get_rst_section(section, options, doc=None):
Expand Down
22 changes: 8 additions & 14 deletions tests/checkers/unittest_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,23 +551,17 @@ def _test_should_always_pass(self, naming_style):
for name, name_type in always_pass_data:
self._test_is_correct(naming_style, name, name_type)

def _test_is_correct(self, naming_style, name, name_type):
@staticmethod
def _test_is_correct(naming_style, name, name_type):
rgx = naming_style.get_regex(name_type)
self.assertTrue(
rgx.match(name),
"{!r} does not match pattern {!r} (style: {}, type: {})".format(
name, rgx, naming_style, name_type
),
)
fail = f"{name!r} does not match pattern {rgx!r} (style: {naming_style}, type: {name_type})"
assert rgx.match(name), fail

def _test_is_incorrect(self, naming_style, name, name_type):
@staticmethod
def _test_is_incorrect(naming_style, name, name_type):
rgx = naming_style.get_regex(name_type)
self.assertFalse(
rgx.match(name),
"{!r} match pattern {!r} but shouldn't (style: {}, type: {})".format(
name, rgx, naming_style, name_type
),
)
fail = f"{name!r} not match pattern {rgx!r} (style: {naming_style}, type: {name_type})"
assert not rgx.match(name), fail

def test_snake_case(self):
naming_style = base.SnakeCaseStyle
Expand Down
5 changes: 2 additions & 3 deletions tests/checkers/unittest_spelling.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ class TestSpellingChecker(CheckerTestCase):
)

def _get_msg_suggestions(self, word, count=4):
return "'{}'".format(
"' or '".join(self.checker.spelling_dict.suggest(word)[:count])
)
suggestions = "' or '".join(self.checker.spelling_dict.suggest(word)[:count])
return f"'{suggestions}'"

@skip_on_missing_package_or_dict
@set_config(spelling_dict=spell_dict)
Expand Down
14 changes: 4 additions & 10 deletions tests/unittest_pyreverse_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,10 @@ def test_dot_files(generated_file):
generated = "\n".join(generated)
expected = "\n".join(expected)
files = f"\n *** expected : {expected_file}, generated : {generated_file} \n"
assert expected == generated, "{}{}".format(
files,
"\n".join(
line for line in unified_diff(expected.splitlines(), generated.splitlines())
),
diff = "\n".join(
line for line in unified_diff(expected.splitlines(), generated.splitlines())
)
assert expected == generated, f"{files}{diff}"
os.remove(generated_file)


Expand All @@ -130,8 +128,4 @@ def test_dot_files(generated_file):
def test_get_visibility(names, expected):
for name in names:
got = get_visibility(name)
assert got == expected, "got {} instead of {} for value {}".format(
got,
expected,
name,
)
assert got == expected, f"got {got} instead of {expected} for value {name}"

0 comments on commit ee91075

Please sign in to comment.