From 8020641d2b558f21fc28207e8aa8d5dd362f52e6 Mon Sep 17 00:00:00 2001 From: Pierre Sassoulas Date: Mon, 15 Feb 2021 23:04:54 +0100 Subject: Move from format() to f-string where it makes sense As we do not maintain python 3.5 it permit to simplify some code --- doc/exts/pylint_extensions.py | 2 +- pylint/checkers/base.py | 2 +- pylint/checkers/base_checker.py | 29 +++---- pylint/checkers/classes.py | 2 +- pylint/checkers/imports.py | 2 +- pylint/checkers/misc.py | 18 +---- pylint/checkers/python3.py | 8 +- pylint/checkers/refactoring/refactoring_checker.py | 4 +- pylint/checkers/spelling.py | 17 +--- pylint/checkers/strings.py | 2 +- pylint/checkers/typecheck.py | 4 +- pylint/checkers/variables.py | 27 +++---- pylint/config/option_manager_mixin.py | 6 +- pylint/lint/run.py | 2 +- pylint/message/message_id_store.py | 13 +--- pylint/testutils/functional_test_file.py | 4 +- pylint/testutils/lint_module_test.py | 14 ++-- pylint/testutils/output_line.py | 16 ++-- tests/checkers/unittest_python3.py | 90 +++++++++------------- tests/checkers/unittest_spelling.py | 2 +- tests/checkers/unittest_typecheck.py | 8 +- tests/extensions/test_check_docs.py | 40 ++++------ tests/message/unittest_message_definition.py | 8 +- tests/profile/test_profile_against_externals.py | 6 +- tests/test_func.py | 7 +- tests/test_self.py | 60 ++++++--------- 26 files changed, 148 insertions(+), 245 deletions(-) diff --git a/doc/exts/pylint_extensions.py b/doc/exts/pylint_extensions.py index c78eb1f3c..c06c90e08 100755 --- a/doc/exts/pylint_extensions.py +++ b/doc/exts/pylint_extensions.py @@ -56,7 +56,7 @@ def builder_inited(app): ) stream.write("Pylint provides the following optional plugins:\n\n") for module in modules: - stream.write("- :ref:`{}`\n".format(module)) + stream.write(f"- :ref:`{module}`\n") stream.write("\n") stream.write( "You can activate any or all of these extensions " diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py index 6f6c7cbdf..aeaa85379 100644 --- a/pylint/checkers/base.py +++ b/pylint/checkers/base.py @@ -2399,7 +2399,7 @@ class ComparisonChecker(_BasicChecker): self.add_message( "singleton-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): diff --git a/pylint/checkers/base_checker.py b/pylint/checkers/base_checker.py index ccdca6568..f7beed603 100644 --- a/pylint/checkers/base_checker.py +++ b/pylint/checkers/base_checker.py @@ -51,15 +51,12 @@ class BaseChecker(OptionsProviderMixIn): def __gt__(self, other): """Permit to sort a list of Checker by name.""" - return "{}{}".format(self.name, self.msgs).__gt__( - "{}{}".format(other.name, other.msgs) - ) + return f"{self.name}{self.msgs}".__gt__(f"{other.name}{other.msgs}") def __repr__(self): status = "Checker" if self.enabled else "Disabled checker" - return "{} '{}' (responsible for '{}')".format( - status, self.name, "', '".join(self.msgs.keys()) - ) + msgs = "', '".join(self.msgs.keys()) + return f"{status} '{self.name}' (responsible for '{msgs}')" def __str__(self): """This might be incomplete because multiple class inheriting BaseChecker @@ -80,15 +77,15 @@ class BaseChecker(OptionsProviderMixIn): result += "Verbatim name of the checker is ``%s``.\n\n" % self.name if doc: # Provide anchor to link against - result += get_rst_title("{} Documentation".format(checker_title), "^") + result += get_rst_title(f"{checker_title} Documentation", "^") result += "%s\n\n" % cleandoc(doc) # options might be an empty generator and not be False when casted to boolean options = list(options) if options: - result += get_rst_title("{} Options".format(checker_title), "^") + result += get_rst_title(f"{checker_title} Options", "^") result += "%s\n" % get_rst_section(None, options) if msgs: - result += get_rst_title("{} Messages".format(checker_title), "^") + result += get_rst_title(f"{checker_title} Messages", "^") for msgid, msg in sorted( msgs.items(), key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1]) ): @@ -96,7 +93,7 @@ class BaseChecker(OptionsProviderMixIn): result += "%s\n" % msg.format_help(checkerref=False) result += "\n" if reports: - result += get_rst_title("{} Reports".format(checker_title), "^") + result += get_rst_title(f"{checker_title} Reports", "^") for report in reports: result += ":%s: %s\n" % report[:2] result += "\n" @@ -124,12 +121,8 @@ class BaseChecker(OptionsProviderMixIn): for message in self.messages: if checker_id is not None and checker_id != message.msgid[1:3]: error_msg = "Inconsistent checker part in message id " - error_msg += "'{}' (expected 'x{checker_id}xx' ".format( - message.msgid, checker_id=checker_id - ) - error_msg += "because we already had {existing_ids}).".format( - existing_ids=existing_ids - ) + error_msg += f"'{message.msgid}' (expected 'x{checker_id}xx' " + error_msg += f"because we already had {existing_ids})." raise InvalidMessageError(error_msg) checker_id = message.msgid[1:3] existing_ids.append(message.msgid) @@ -171,8 +164,8 @@ class BaseChecker(OptionsProviderMixIn): for message_definition in self.messages: if message_definition.msgid == msgid: return message_definition - error_msg = "MessageDefinition for '{}' does not exists. ".format(msgid) - error_msg += "Choose from {}.".format([m.msgid for m in self.messages]) + error_msg = f"MessageDefinition for '{msgid}' does not exists. " + error_msg += f"Choose from {[m.msgid for m in self.messages]}." raise InvalidMessageError(error_msg) def open(self): diff --git a/pylint/checkers/classes.py b/pylint/checkers/classes.py index 06fe30ca7..d3fb1fa60 100644 --- a/pylint/checkers/classes.py +++ b/pylint/checkers/classes.py @@ -402,7 +402,7 @@ def _is_attribute_property(name, klass): attributes = klass.getattr(name) except astroid.NotFoundError: return False - property_name = "{}.property".format(BUILTINS) + property_name = f"{BUILTINS}.property" for attr in attributes: if attr is astroid.Uninferable: continue diff --git a/pylint/checkers/imports.py b/pylint/checkers/imports.py index 37b814e30..f22cb3315 100644 --- a/pylint/checkers/imports.py +++ b/pylint/checkers/imports.py @@ -963,7 +963,7 @@ class ImportsChecker(BaseChecker): return module_names = [ - "{}.{}".format(node.modname, name[0]) + f"{node.modname}.{name[0]}" if isinstance(node, astroid.ImportFrom) else name[0] for name in node.names diff --git a/pylint/checkers/misc.py b/pylint/checkers/misc.py index 509ed9c7b..be6fbd363 100644 --- a/pylint/checkers/misc.py +++ b/pylint/checkers/misc.py @@ -55,14 +55,8 @@ class ByIdManagedMessagesChecker(BaseChecker): managed_msgs = MessagesHandlerMixIn.get_by_id_managed_msgs() for (mod_name, msg_id, msg_symbol, lineno, is_disabled) in managed_msgs: if mod_name == module.name: - if is_disabled: - txt = "Id '{ident}' is used to disable '{symbol}' message emission".format( - ident=msg_id, symbol=msg_symbol - ) - else: - txt = "Id '{ident}' is used to enable '{symbol}' message emission".format( - ident=msg_id, symbol=msg_symbol - ) + verb = "disable" if is_disabled else "enable" + txt = f"Id '{msg_id}' is used to {verb} '{msg_symbol}' message emission" self.add_message("use-symbolic-message-instead", line=lineno, args=txt) MessagesHandlerMixIn.clear_by_id_managed_msgs() @@ -127,12 +121,8 @@ class EncodingChecker(BaseChecker): pass except LookupError: if line.startswith("#") and "coding" in line and file_encoding in line: - self.add_message( - "syntax-error", - line=lineno, - args='Cannot decode using encoding "{}",' - " bad encoding".format(file_encoding), - ) + msg = f"Cannot decode using encoding '{file_encoding}', bad encoding" + self.add_message("syntax-error", line=lineno, args=msg) return None def process_module(self, module): diff --git a/pylint/checkers/python3.py b/pylint/checkers/python3.py index 0b9369a4a..9b46c1fe1 100644 --- a/pylint/checkers/python3.py +++ b/pylint/checkers/python3.py @@ -1111,7 +1111,7 @@ class Python3Checker(checkers.BaseChecker): if not inferred: return - builtins_list = "{}.list".format(bases.BUILTINS) + builtins_list = f"{bases.BUILTINS}.list" if isinstance(inferred, astroid.List) or inferred.qname() == builtins_list: kwargs = node.keywords @@ -1120,7 +1120,7 @@ class Python3Checker(checkers.BaseChecker): if not inferred: return - builtins_sorted = "{}.sorted".format(bases.BUILTINS) + builtins_sorted = f"{bases.BUILTINS}.sorted" if inferred.qname() == builtins_sorted: kwargs = node.keywords @@ -1181,7 +1181,7 @@ class Python3Checker(checkers.BaseChecker): and node.func.attrname in DICT_METHODS ): if not _in_iterating_context(node): - checker = "dict-{}-not-iterating".format(node.func.attrname) + checker = f"dict-{node.func.attrname}-not-iterating" self.add_message(checker, node=node) except astroid.InferenceError: pass @@ -1232,7 +1232,7 @@ class Python3Checker(checkers.BaseChecker): if _is_builtin(found_node): if node.func.name in ("filter", "map", "range", "zip"): if not _in_iterating_context(node): - checker = "{}-builtin-not-iterating".format(node.func.name) + checker = f"{node.func.name}-builtin-not-iterating" self.add_message(checker, node=node) elif node.func.name == "open" and node.keywords: kwargs = node.keywords diff --git a/pylint/checkers/refactoring/refactoring_checker.py b/pylint/checkers/refactoring/refactoring_checker.py index 110fbd74d..81bb18213 100644 --- a/pylint/checkers/refactoring/refactoring_checker.py +++ b/pylint/checkers/refactoring/refactoring_checker.py @@ -622,7 +622,7 @@ class RefactoringChecker(checkers.BaseTokenChecker): test_reduced_to = "bool(test)" if (node.body.value, node.orelse.value) == (True, False): - reduced_to = "'{}'".format(test_reduced_to) + reduced_to = f"'{test_reduced_to}'" elif (node.body.value, node.orelse.value) == (False, True): reduced_to = "'not test'" else: @@ -666,7 +666,7 @@ class RefactoringChecker(checkers.BaseTokenChecker): @staticmethod def _check_exception_inherit_from_stopiteration(exc): """Return True if the exception node in argument inherit from StopIteration""" - stopiteration_qname = "{}.StopIteration".format(utils.EXCEPTIONS_MODULE) + stopiteration_qname = f"{utils.EXCEPTIONS_MODULE}.StopIteration" return any(_class.qname() == stopiteration_qname for _class in exc.mro()) def _check_consider_using_comprehension_constructor(self, node): diff --git a/pylint/checkers/spelling.py b/pylint/checkers/spelling.py index e8d00381a..4c08b855f 100644 --- a/pylint/checkers/spelling.py +++ b/pylint/checkers/spelling.py @@ -347,7 +347,6 @@ class SpellingChecker(BaseTokenChecker): # Present up to N suggestions. suggestions = self.spelling_dict.suggest(word) del suggestions[self.config.max_spelling_suggestions :] - line_segment = line[word_start_at:] match = re.search(r"(\W|^)(%s)(\W|$)" % word, line_segment) if match: @@ -355,23 +354,13 @@ class SpellingChecker(BaseTokenChecker): col = match.regs[2][0] else: col = line_segment.index(word) - col += word_start_at - if starts_with_comment: col += 1 indicator = (" " * col) + ("^" * len(word)) - - self.add_message( - msgid, - line=line_num, - args=( - word, - original_line, - indicator, - "'{}'".format("' or '".join(suggestions)), - ), - ) + all_suggestion = "' or '".join(suggestions) + args = (word, original_line, indicator, "'{}'".format(all_suggestion)) + self.add_message(msgid, line=line_num, args=args) def process_tokens(self, tokens): if not self.initialized: diff --git a/pylint/checkers/strings.py b/pylint/checkers/strings.py index 3cf1d86c5..c36b06570 100644 --- a/pylint/checkers/strings.py +++ b/pylint/checkers/strings.py @@ -226,7 +226,7 @@ def get_access_path(key, parts): path = [] for is_attribute, specifier in parts: if is_attribute: - path.append(".{}".format(specifier)) + path.append(f".{specifier}") else: path.append("[{!r}]".format(specifier)) return str(key) + "".join(path) diff --git a/pylint/checkers/typecheck.py b/pylint/checkers/typecheck.py index e135f6e94..38ebfde6f 100644 --- a/pylint/checkers/typecheck.py +++ b/pylint/checkers/typecheck.py @@ -154,7 +154,7 @@ def _is_owner_ignored(owner, attrname, ignored_classes, ignored_modules): if not current_module: current_module = part else: - current_module += ".{}".format(part) + current_module += f".{part}" if current_module in ignored_modules: return True @@ -246,7 +246,7 @@ def _missing_member_hint(owner, attrname, distance_threshold, max_choices): else: names = "one of {} or {}".format(", ".join(names[:-1]), names[-1]) - return "; maybe {}?".format(names) + return f"; maybe {names}?" MSGS = { diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index e9e8a22e3..0fb296a84 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -516,24 +516,15 @@ class NamesConsumer: self.node = node def __repr__(self): - msg = "\nto_consume : {:s}\n".format( - ", ".join( - [ - "{}->{}".format(key, val) - for key, val in self._atomic.to_consume.items() - ] - ) - ) - msg += "consumed : {:s}\n".format( - ", ".join( - [ - "{}->{}".format(key, val) - for key, val in self._atomic.consumed.items() - ] - ) - ) - msg += "scope_type : {:s}\n".format(self._atomic.scope_type) - return msg + to_consumes = [f"{k}->{v}" for k, v in self._atomic.to_consume.items()] + consumed = [f"{k}->{v}" for k, v in self._atomic.consumed.items()] + to_consumes = ", ".join(to_consumes) + consumed = ", ".join(consumed) + return f""" +to_consume : {to_consumes} +consumed : {consumed} +scope_type : {self._atomic.scope_type} +""" def __iter__(self): return iter(self._atomic) diff --git a/pylint/config/option_manager_mixin.py b/pylint/config/option_manager_mixin.py index 353e1c8bc..e4c677724 100644 --- a/pylint/config/option_manager_mixin.py +++ b/pylint/config/option_manager_mixin.py @@ -258,7 +258,7 @@ class OptionsManagerMixIn: if config_file is not None: config_file = os.path.expanduser(config_file) if not os.path.exists(config_file): - raise OSError("The config file {:s} doesn't exist!".format(config_file)) + raise OSError(f"The config file {config_file} doesn't exist!") use_config_file = config_file and os.path.exists(config_file) if use_config_file: # pylint: disable=too-many-nested-blocks @@ -295,12 +295,10 @@ class OptionsManagerMixIn: sect = sect[len("pylint.") :] if not sect.isupper() and values: parser._sections[sect.upper()] = values - if not verbose: return - if use_config_file: - msg = "Using config file {}".format(os.path.abspath(config_file)) + msg = f"Using config file {os.path.abspath(config_file)}" else: msg = "No config file found, using default configuration" print(msg, file=sys.stderr) diff --git a/pylint/lint/run.py b/pylint/lint/run.py index 35bc802b2..63f67ead4 100644 --- a/pylint/lint/run.py +++ b/pylint/lint/run.py @@ -34,7 +34,7 @@ def cb_list_extensions(option, optname, value, parser): for filename in os.listdir(os.path.dirname(extensions.__file__)): if filename.endswith(".py") and not filename.startswith("_"): extension_name, _, _ = filename.partition(".") - print("pylint.extensions.{}".format(extension_name)) + print(f"pylint.extensions.{extension_name}") sys.exit(0) diff --git a/pylint/message/message_id_store.py b/pylint/message/message_id_store.py index ec515b21f..0395f0878 100644 --- a/pylint/message/message_id_store.py +++ b/pylint/message/message_id_store.py @@ -21,7 +21,7 @@ class MessageIdStore: def __repr__(self): result = "MessageIdStore: [\n" for msgid, symbol in self.__msgid_to_symbol.items(): - result += " - {msgid} ({symbol})\n".format(msgid=msgid, symbol=symbol) + result += f" - {msgid} ({symbol})\n" result += "]" return result @@ -80,7 +80,7 @@ class MessageIdStore: :raises InvalidMessageError:""" symbols = [symbol, other_symbol] symbols.sort() - error_message = "Message id '{msgid}' cannot have both ".format(msgid=msgid) + 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] ) @@ -114,13 +114,6 @@ class MessageIdStore: msgid = self.__symbol_to_msgid.get(msgid_or_symbol) symbol = msgid_or_symbol if not msgid or not symbol: - error_msg = "No such message id or symbol '{msgid_or_symbol}'.".format( - msgid_or_symbol=msgid_or_symbol - ) + error_msg = f"No such message id or symbol '{msgid_or_symbol}'." raise UnknownMessageError(error_msg) - # logging.debug( - # "Return for {} and msgid {} is {}".format( - # msgid_or_symbol, msgid, self.__old_names.get(msgid, [msgid]) - # ) - # ) return self.__old_names.get(msgid, [msgid]) diff --git a/pylint/testutils/functional_test_file.py b/pylint/testutils/functional_test_file.py index fab6e3aa2..53651527b 100644 --- a/pylint/testutils/functional_test_file.py +++ b/pylint/testutils/functional_test_file.py @@ -35,7 +35,7 @@ class FunctionalTestFile: self._parse_options() def __repr__(self): - return "FunctionalTest:{}".format(self.base) + return f"FunctionalTest:{self.base}" def _parse_options(self): cp = configparser.ConfigParser() @@ -70,4 +70,4 @@ class FunctionalTestFile: name = join(self._directory, self.base + ext) if not check_exists or exists(name): return name - raise NoFileError("Cannot find '{}'.".format(name)) + raise NoFileError(f"Cannot find '{name}'.") diff --git a/pylint/testutils/lint_module_test.py b/pylint/testutils/lint_module_test.py index d63fdaf41..2524f8c0e 100644 --- a/pylint/testutils/lint_module_test.py +++ b/pylint/testutils/lint_module_test.py @@ -158,7 +158,7 @@ class LintModuleTest: for msg in messages: assert ( msg.symbol != "fatal" - ), "Pylint analysis failed because of '{}'".format(msg.msg) + ), f"Pylint analysis failed because of '{msg.msg}'" received_msgs[msg.line, msg.symbol] += 1 received_output_lines.append(OutputLine.from_msg(msg)) return received_msgs, received_output_lines @@ -191,22 +191,20 @@ class LintModuleTest: missing = set(expected_lines) - set(received_lines) unexpected = set(received_lines) - set(expected_lines) error_msg = ( - "Wrong output for '{_file}.txt':\n" + f"Wrong output for '{self._test_file.base}.txt':\n" "You can update the expected output automatically with: '" - 'python tests/test_functional.py {update_option} -k "test_functional[{_file}]"\'\n\n'.format( - update_option=UPDATE_OPTION, - _file=self._test_file.base, - ) + f"python tests/test_functional.py {UPDATE_OPTION} -k " + f'""test_functional[{self._test_file.base}]"\'\n\n' ) sort_by_line_number = operator.attrgetter("lineno") if missing: error_msg += "\n- Missing lines:\n" for line in sorted(missing, key=sort_by_line_number): - error_msg += "{}\n".format(line) + error_msg += f"{line}\n" if unexpected: error_msg += "\n- Unexpected lines:\n" for line in sorted(unexpected, key=sort_by_line_number): - error_msg += "{}\n".format(line) + error_msg += f"{line}\n" return error_msg def _check_output_text(self, _, expected_output, actual_output): diff --git a/pylint/testutils/output_line.py b/pylint/testutils/output_line.py index d1753605c..bad3d46ee 100644 --- a/pylint/testutils/output_line.py +++ b/pylint/testutils/output_line.py @@ -37,23 +37,17 @@ class MalformedOutputLineException(Exception): reconstructed_row = "" i = 0 for i, column in enumerate(row): - reconstructed_row += "\t{}='{}' ?\n".format(expected[i], column) + reconstructed_row += f"\t{expected[i]}='{column}' ?\n" for missing in expected[i + 1 :]: - reconstructed_row += "\t{}= Nothing provided !\n".format(missing) - msg = """\ + reconstructed_row += f"\t{missing}= Nothing provided !\n" + raw = ":".join(row) + msg = f"""\ {exception} Expected '{example}' or '{other_example}' but we got '{raw}': {reconstructed_row} -Try updating it with: 'python tests/test_functional.py {update_option}'""".format( - exception=exception, - example=example, - other_example=other_example, - raw=":".join(row), - reconstructed_row=reconstructed_row, - update_option=UPDATE_OPTION, - ) +Try updating it with: 'python tests/test_functional.py {UPDATE_OPTION}'""" Exception.__init__(self, msg) diff --git a/tests/checkers/unittest_python3.py b/tests/checkers/unittest_python3.py index 36bf44719..cbb4fbb20 100644 --- a/tests/checkers/unittest_python3.py +++ b/tests/checkers/unittest_python3.py @@ -69,115 +69,107 @@ class TestPython3Checker(testutils.CheckerTestCase): self.check_bad_builtin(builtin) def as_iterable_in_for_loop_test(self, fxn): - code = "for x in {}(): pass".format(fxn) + code = f"for x in {fxn}(): pass" module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_used_by_iterable_in_for_loop_test(self, fxn): - checker = "{}-builtin-not-iterating".format(fxn) + checker = f"{fxn}-builtin-not-iterating" node = astroid.extract_node( - """ + f""" for x in (whatever( - {}() #@ + {fxn}() #@ )): pass - """.format( - fxn - ) + """ ) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node) def as_iterable_in_genexp_test(self, fxn): - code = "x = (x for x in {}())".format(fxn) + code = f"x = (x for x in {fxn}())" module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_iterable_in_starred_context(self, fxn): - code = "x = test(*{}())".format(fxn) + code = f"x = test(*{fxn}())" module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_iterable_in_listcomp_test(self, fxn): - code = "x = [x for x in {}(None, [1])]".format(fxn) + code = f"x = [x for x in {fxn}(None, [1])]" module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_iterable_in_yield_from(self, fxn): - code = "yield from {}()".format(fxn) + code = f"yield from {fxn}()" module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_used_in_variant_in_genexp_test(self, fxn): - checker = "{}-builtin-not-iterating".format(fxn) + checker = f"{fxn}-builtin-not-iterating" node = astroid.extract_node( - """ + f""" list( - __({}(x)) + __({fxn}(x)) for x in [1] ) - """.format( - fxn - ) + """ ) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node) def as_used_in_variant_in_listcomp_test(self, fxn): - checker = "{}-builtin-not-iterating".format(fxn) + checker = f"{fxn}-builtin-not-iterating" node = astroid.extract_node( - """ + f""" [ - __({}(None, x)) + __({fxn}(None, x)) for x in [[1]]] - """.format( - fxn - ) + """ ) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node) def as_argument_to_callable_constructor_test(self, fxn, callable_fn): - module = astroid.parse("x = {}({}())".format(callable_fn, fxn)) + module = astroid.parse(f"x = {callable_fn}({fxn}())") with self.assertNoMessages(): self.walk(module) def as_argument_to_materialized_filter(self, callable_fn): - module = astroid.parse("list(filter(None, {}()))".format(callable_fn)) + module = astroid.parse(f"list(filter(None, {callable_fn}()))") with self.assertNoMessages(): self.walk(module) def as_argument_to_random_fxn_test(self, fxn): - checker = "{}-builtin-not-iterating".format(fxn) + checker = f"{fxn}-builtin-not-iterating" node = astroid.extract_node( - """ + f""" y( - {}() #@ + {fxn}() #@ ) - """.format( - fxn - ) + """ ) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node) def as_argument_to_str_join_test(self, fxn): - code = "x = ''.join({}())".format(fxn) + code = f"x = ''.join({fxn}())" module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_argument_to_itertools_functions(self, fxn): - code = """ + code = f""" from __future__ import absolute_import import itertools from itertools import product @@ -185,32 +177,26 @@ class TestPython3Checker(testutils.CheckerTestCase): pass for i,j in itertools.product({fxn}(), repeat=2): pass - """.format( - fxn=fxn - ) + """ module = astroid.parse(code) with self.assertNoMessages(): self.walk(module) def as_iterable_in_unpacking(self, fxn): node = astroid.extract_node( - """ - a, b = __({}()) - """.format( - fxn - ) + f""" + a, b = __({fxn}()) + """ ) with self.assertNoMessages(): self.checker.visit_call(node) def as_assignment(self, fxn): - checker = "{}-builtin-not-iterating".format(fxn) + checker = f"{fxn}-builtin-not-iterating" node = astroid.extract_node( - """ - a = __({}()) - """.format( - fxn - ) + f""" + a = __({fxn}()) + """ ) message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): @@ -301,7 +287,7 @@ class TestPython3Checker(testutils.CheckerTestCase): with_value = code.format(dict_method) node = astroid.extract_node(with_value) - checker = "dict-{}-not-iterating".format(method) + checker = f"dict-{method}-not-iterating" message = testutils.Message(checker, node=node) with self.assertAddsMessages(message): self.checker.visit_call(node) @@ -321,12 +307,10 @@ class TestPython3Checker(testutils.CheckerTestCase): def defined_method_test(self, method, warning): """Helper for verifying that a certain method is not defined.""" node = astroid.extract_node( - """ + f""" class Foo(object): - def __{}__(self, other): #@ - pass""".format( - method - ) + def __{method}__(self, other): #@ + pass""" ) message = testutils.Message(warning, node=node) with self.assertAddsMessages(message): diff --git a/tests/checkers/unittest_spelling.py b/tests/checkers/unittest_spelling.py index de3482ccf..777cac7f5 100644 --- a/tests/checkers/unittest_spelling.py +++ b/tests/checkers/unittest_spelling.py @@ -237,7 +237,7 @@ class TestSpellingChecker(CheckerTestCase): "affine3D", ): stmt = astroid.extract_node( - 'class TestClass(object):\n """{} comment"""\n pass'.format(ccn) + f'class TestClass(object):\n """{ccn} comment"""\n pass' ) self.checker.visit_classdef(stmt) assert self.linter.release_messages() == [] diff --git a/tests/checkers/unittest_typecheck.py b/tests/checkers/unittest_typecheck.py index 802a00e7c..367a22d80 100644 --- a/tests/checkers/unittest_typecheck.py +++ b/tests/checkers/unittest_typecheck.py @@ -402,12 +402,10 @@ class TestTypeCheckerOnDecorators(CheckerTestCase): def typing_objects_are_subscriptable(self, generic): module = astroid.parse( - """ + f""" import typing - test = typing.{}[int] - """.format( - generic - ) + test = typing.{generic}[int] + """ ) subscript = module.body[-1].value with self.assertNoMessages(): diff --git a/tests/extensions/test_check_docs.py b/tests/extensions/test_check_docs.py index a40e96220..8dbca32b7 100644 --- a/tests/extensions/test_check_docs.py +++ b/tests/extensions/test_check_docs.py @@ -1416,20 +1416,18 @@ class TestParamDocChecker(CheckerTestCase): @pytest.mark.parametrize("complex_type", COMPLEX_TYPES) def test_finds_multiple_types_sphinx(self, complex_type): node = astroid.extract_node( - ''' + f''' def my_func(named_arg): """The docstring :param named_arg: Returned - :type named_arg: {0} + :type named_arg: {complex_type} :returns: named_arg - :rtype: {0} + :rtype: {complex_type} """ return named_arg - '''.format( - complex_type - ) + ''' ) with self.assertNoMessages(): self.checker.visit_functiondef(node) @@ -1437,20 +1435,18 @@ class TestParamDocChecker(CheckerTestCase): @pytest.mark.parametrize("complex_type", COMPLEX_TYPES) def test_finds_multiple_types_google(self, complex_type): node = astroid.extract_node( - ''' + f''' def my_func(named_arg): """The docstring Args: - named_arg ({0}): Returned + named_arg ({complex_type}): Returned Returns: - {0}: named_arg + {complex_type}: named_arg """ return named_arg - '''.format( - complex_type - ) + ''' ) with self.assertNoMessages(): self.checker.visit_functiondef(node) @@ -1458,24 +1454,22 @@ class TestParamDocChecker(CheckerTestCase): @pytest.mark.parametrize("complex_type", COMPLEX_TYPES) def test_finds_multiple_types_numpy(self, complex_type): node = astroid.extract_node( - ''' + f''' def my_func(named_arg): """The docstring Args ---- - named_arg : {0} + named_arg : {complex_type} Returned Returns ------- - {0} + {complex_type} named_arg """ return named_arg - '''.format( - complex_type - ) + ''' ) with self.assertNoMessages(): self.checker.visit_functiondef(node) @@ -1483,19 +1477,17 @@ class TestParamDocChecker(CheckerTestCase): @pytest.mark.parametrize("container_type", CONTAINER_TYPES) def test_finds_compact_container_types_sphinx(self, container_type): node = astroid.extract_node( - ''' + f''' def my_func(named_arg): """The docstring - :param {0} named_arg: Returned + :param {container_type} named_arg: Returned :returns: named_arg - :rtype: {0} + :rtype: {container_type} """ return named_arg - '''.format( - container_type - ) + ''' ) with self.assertNoMessages(): self.checker.visit_functiondef(node) diff --git a/tests/message/unittest_message_definition.py b/tests/message/unittest_message_definition.py index b9b936d67..c9870e8a1 100644 --- a/tests/message/unittest_message_definition.py +++ b/tests/message/unittest_message_definition.py @@ -47,11 +47,11 @@ class FalseChecker(BaseChecker): class TestMessagesDefinition: @staticmethod def assert_with_fail_msg(msg, expected=True): - fail_msg = "With minversion='{}' and maxversion='{}',".format( - msg.minversion, msg.maxversion + fail_msg = ( + f"With minversion='{msg.minversion}' and maxversion='{msg.maxversion}'," + f" and the python interpreter being {sys.version_info} " + "the message should{}be emitable" ) - fail_msg += " and the python interpreter being {} ".format(sys.version_info) - fail_msg += "the message should{}be emitable" if expected: assert msg.may_be_emitted(), fail_msg.format(" ") else: diff --git a/tests/profile/test_profile_against_externals.py b/tests/profile/test_profile_against_externals.py index 4bbac7556..27265f22c 100644 --- a/tests/profile/test_profile_against_externals.py +++ b/tests/profile/test_profile_against_externals.py @@ -42,11 +42,7 @@ def test_run(tmp_path, name, git_repo): """ Runs pylint against external sources """ checkoutdir = tmp_path / name checkoutdir.mkdir() - os.system( - "git clone --depth=1 {git_repo} {checkoutdir}".format( - git_repo=git_repo, checkoutdir=str(checkoutdir) - ) - ) + os.system(f"git clone --depth=1 {git_repo} {checkoutdir}") filepaths = _get_py_files(scanpath=str(checkoutdir)) print("Have %d files" % len(filepaths)) diff --git a/tests/test_func.py b/tests/test_func.py index ab99f6b63..e10aa4fa7 100644 --- a/tests/test_func.py +++ b/tests/test_func.py @@ -62,12 +62,9 @@ class LintTestUsingModule: def _check_result(self, got): error_msg = ( - "Wrong output for '{_file}':\n" + f"Wrong output for '{self.output}':\n" "You can update the expected output automatically with: '" - "python tests/test_func.py {update_option}'\n\n".format( - update_option=UPDATE_OPTION, - _file=self.output, - ) + f"python tests/test_func.py {UPDATE_OPTION}'\n\n" ) assert self._get_expected() == got, error_msg diff --git a/tests/test_self.py b/tests/test_self.py index e8f9f848f..5dd5b7b3a 100644 --- a/tests/test_self.py +++ b/tests/test_self.py @@ -202,9 +202,9 @@ class TestRunTC: output = out.getvalue() # Get rid of the pesky messages that pylint emits if the # configuration file is not found. - pattern = r"\[{}".format(MAIN_CHECKER_NAME.upper()) + pattern = rf"\[{MAIN_CHECKER_NAME.upper()}" master = re.search(pattern, output) - assert master is not None, "{} not found in {}".format(pattern, output) + assert master is not None, f"{pattern} not found in {output}" out = StringIO(output[master.start() :]) parser = configparser.RawConfigParser() parser.read_file(out) @@ -283,14 +283,12 @@ class TestRunTC: def test_enable_all_works(self): module = join(HERE, "data", "clientmodule_test.py") expected = textwrap.dedent( - """ + f""" ************* Module data.clientmodule_test - {0}:10:8: W0612: Unused variable 'local_variable' (unused-variable) - {0}:18:4: C0116: Missing function or method docstring (missing-function-docstring) - {0}:22:0: C0115: Missing class docstring (missing-class-docstring) - """.format( - module - ) + {module}:10:8: W0612: Unused variable 'local_variable' (unused-variable) + {module}:18:4: C0116: Missing function or method docstring (missing-function-docstring) + {module}:22:0: C0115: Missing class docstring (missing-class-docstring) + """ ) self._test_output( [module, "--disable=all", "--enable=all", "-rn"], expected_output=expected @@ -300,12 +298,10 @@ class TestRunTC: module1 = join(HERE, "regrtest_data", "import_something.py") module2 = join(HERE, "regrtest_data", "wrong_import_position.py") expected_output = textwrap.dedent( - """ + f""" ************* Module wrong_import_position - {}:11:0: C0413: Import "import os" should be placed at the top of the module (wrong-import-position) - """.format( - module2 - ) + {module2}:11:0: C0413: Import "import os" should be placed at the top of the module (wrong-import-position) + """ ) args = [ module2, @@ -422,12 +418,10 @@ class TestRunTC: def test_error_mode_shows_no_score(self): module = join(HERE, "regrtest_data", "application_crash.py") expected_output = textwrap.dedent( - """ + f""" ************* Module application_crash - {}:1:6: E0602: Undefined variable 'something_undefined' (undefined-variable) - """.format( - module - ) + {module}:1:6: E0602: Undefined variable 'something_undefined' (undefined-variable) + """ ) self._test_output([module, "-E"], expected_output=expected_output) @@ -482,14 +476,12 @@ class TestRunTC: path = join(HERE, "regrtest_data", "test_pylintrc_comments.py") config_path = join(HERE, "regrtest_data", "comments_pylintrc") expected = textwrap.dedent( - """ + f""" ************* Module test_pylintrc_comments - {0}:2:0: W0311: Bad indentation. Found 1 spaces, expected 4 (bad-indentation) - {0}:1:0: C0114: Missing module docstring (missing-module-docstring) - {0}:1:0: C0116: Missing function or method docstring (missing-function-docstring) - """.format( - path - ) + {path}:2:0: W0311: Bad indentation. Found 1 spaces, expected 4 (bad-indentation) + {path}:1:0: C0114: Missing module docstring (missing-module-docstring) + {path}:1:0: C0116: Missing function or method docstring (missing-function-docstring) + """ ) self._test_output( [path, "--rcfile=%s" % config_path, "-rn"], expected_output=expected @@ -503,11 +495,9 @@ class TestRunTC: def test_getdefaultencoding_crashes_with_lc_ctype_utf8(self): module = join(HERE, "regrtest_data", "application_crash.py") expected_output = textwrap.dedent( - """ - {}:1:6: E0602: Undefined variable 'something_undefined' (undefined-variable) - """.format( - module - ) + f""" + {module}:1:6: E0602: Undefined variable 'something_undefined' (undefined-variable) + """ ) with _configure_lc_ctype("UTF-8"): self._test_output([module, "-E"], expected_output=expected_output) @@ -540,10 +530,10 @@ class TestRunTC: ], ) def test_stdin(self, input_path, module, expected_path): - expected_output = ( - "************* Module {module}\n" - "{path}:1:0: W0611: Unused import os (unused-import)\n\n" - ).format(path=expected_path, module=module) + expected_output = f"""************* Module {module} +{expected_path}:1:0: W0611: Unused import os (unused-import) + +""" with mock.patch( "pylint.lint.pylinter._read_stdin", return_value="import os\n" -- cgit v1.2.1