From 5af876aa11ac5fa1c09c99c4a75b830ef64a18e5 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sun, 1 May 2022 15:59:58 -0600 Subject: [PATCH] mypy: use more f-strings Done largely using https://github.com/ikamensh/flynt I went over this pretty closely since I wasn't familiar with the tool I made a couple changes and left out a couple instances which were harder to parse --- mypy/build.py | 41 +++++++++++++------------- mypy/checker.py | 8 ++--- mypy/checkexpr.py | 2 +- mypy/checkstrformat.py | 2 +- mypy/config_parser.py | 10 +++---- mypy/dmypy/client.py | 8 ++--- mypy/dmypy_server.py | 2 +- mypy/dmypy_util.py | 2 +- mypy/fastparse.py | 2 +- mypy/main.py | 21 +++++++------- mypy/memprofile.py | 10 +++---- mypy/messages.py | 53 ++++++++++++++-------------------- mypy/moduleinspect.py | 2 +- mypy/nodes.py | 7 ++--- mypy/plugins/dataclasses.py | 2 +- mypy/plugins/singledispatch.py | 4 +-- mypy/report.py | 7 ++--- mypy/semanal.py | 18 ++++++------ mypy/semanal_enum.py | 12 ++++---- mypy/semanal_newtype.py | 2 +- mypy/semanal_typeddict.py | 2 +- mypy/server/deps.py | 2 +- mypy/server/mergecheck.py | 4 +-- mypy/server/trigger.py | 2 +- mypy/server/update.py | 25 ++++++++-------- mypy/strconv.py | 18 +++++------- mypy/stubdoc.py | 4 +-- mypy/stubgen.py | 32 ++++++++++---------- mypy/stubgenc.py | 16 +++++----- mypy/stubutil.py | 10 +++---- mypy/suggestions.py | 13 ++++----- mypy/test/data.py | 9 ++---- mypy/test/testcheck.py | 2 +- mypy/test/testdeps.py | 5 ++-- mypy/test/testdiff.py | 3 +- mypy/test/testfinegrained.py | 6 ++-- mypy/test/testmerge.py | 12 +++----- mypy/test/testparse.py | 3 +- mypy/test/testpythoneval.py | 2 +- mypy/test/testsemanal.py | 9 ++---- mypy/test/teststubgen.py | 6 ++-- mypy/test/teststubtest.py | 3 +- mypy/test/testtransform.py | 3 +- mypy/test/testtypegen.py | 3 +- mypy/typeanal.py | 9 +++--- mypy/types.py | 6 ++-- mypy/util.py | 2 +- 47 files changed, 190 insertions(+), 236 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 107a291ad582..ba2d1b1b3d35 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -665,7 +665,7 @@ def dump_stats(self) -> None: if self.options.dump_build_stats: print("Stats:") for key, value in sorted(self.stats_summary().items()): - print("{:24}{}".format(key + ":", value)) + print(f"{key + ':':24}{value}") def use_fine_grained_cache(self) -> bool: return self.cache_enabled and self.options.use_fine_grained_cache @@ -1083,7 +1083,7 @@ def read_deps_cache(manager: BuildManager, except FileNotFoundError: matched = False if not matched: - manager.log('Invalid or missing fine-grained deps cache: {}'.format(meta['path'])) + manager.log(f"Invalid or missing fine-grained deps cache: {meta['path']}") return None return module_deps_metas @@ -1485,8 +1485,7 @@ def write_cache(id: str, path: str, tree: MypyFile, # Obtain file paths. meta_json, data_json, _ = get_cache_names(id, path, manager.options) - manager.log('Writing {} {} {} {}'.format( - id, path, meta_json, data_json)) + manager.log(f'Writing {id} {path} {meta_json} {data_json}') # Update tree.path so that in bazel mode it's made relative (since # sometimes paths leak out). @@ -1590,7 +1589,7 @@ def delete_cache(id: str, path: str, manager: BuildManager) -> None: # tracked separately. meta_path, data_path, _ = get_cache_names(id, path, manager.options) cache_paths = [meta_path, data_path] - manager.log('Deleting {} {} {}'.format(id, path, " ".join(x for x in cache_paths if x))) + manager.log(f"Deleting {id} {path} {' '.join(x for x in cache_paths if x)}") for filename in cache_paths: try: @@ -2490,7 +2489,7 @@ def find_module_and_diagnose(manager: BuildManager, and not options.custom_typeshed_dir): raise CompileError([ f'mypy: "{os.path.relpath(result)}" shadows library module "{id}"', - 'note: A user-defined top-level module with name "%s" is not supported' % id + f'note: A user-defined top-level module with name "{id}" is not supported' ]) return (result, follow_imports) else: @@ -2523,7 +2522,7 @@ def find_module_and_diagnose(manager: BuildManager, # If we can't find a root source it's always fatal. # TODO: This might hide non-fatal errors from # root sources processed earlier. - raise CompileError(["mypy: can't find module '%s'" % id]) + raise CompileError([f"mypy: can't find module '{id}'"]) else: raise ModuleNotFound @@ -2670,21 +2669,21 @@ def log_configuration(manager: BuildManager, sources: List[BuildSource]) -> None ] for conf_name, conf_value in configuration_vars: - manager.log("{:24}{}".format(conf_name + ":", conf_value)) + manager.log(f"{conf_name + ':':24}{conf_value}") for source in sources: - manager.log("{:24}{}".format("Found source:", source)) + manager.log(f"{'Found source:':24}{source}") # Complete list of searched paths can get very long, put them under TRACE for path_type, paths in manager.search_paths._asdict().items(): if not paths: - manager.trace("No %s" % path_type) + manager.trace(f"No {path_type}") continue - manager.trace("%s:" % path_type) + manager.trace(f"{path_type}:") for pth in paths: - manager.trace(" %s" % pth) + manager.trace(f" {pth}") # The driver @@ -2720,7 +2719,7 @@ def dispatch(sources: List[BuildSource], if not graph: print("Nothing to do?!", file=stdout) return graph - manager.log("Loaded graph with %d nodes (%.3f sec)" % (len(graph), t1 - t0)) + manager.log(f"Loaded graph with {len(graph)} nodes ({t1 - t0:.3f} sec)") if manager.options.dump_graph: dump_graph(graph, stdout) return graph @@ -3009,7 +3008,7 @@ def process_graph(graph: Graph, manager: BuildManager) -> None: scc.append('builtins') if manager.options.verbosity >= 2: for id in scc: - manager.trace("Priorities for %s:" % id, + manager.trace(f"Priorities for {id}:", " ".join("%s:%d" % (x, graph[id].priorities[x]) for x in graph[id].dependencies if x in ascc and x in graph[id].priorities)) @@ -3059,19 +3058,19 @@ def process_graph(graph: Graph, manager: BuildManager) -> None: # (on some platforms). if oldest_in_scc < newest_in_deps: fresh = False - fresh_msg = "out of date by %.0f seconds" % (newest_in_deps - oldest_in_scc) + fresh_msg = f"out of date by {newest_in_deps - oldest_in_scc:.0f} seconds" else: fresh_msg = "fresh" elif undeps: - fresh_msg = "stale due to changed suppression (%s)" % " ".join(sorted(undeps)) + fresh_msg = f"stale due to changed suppression ({' '.join(sorted(undeps))})" elif stale_scc: fresh_msg = "inherently stale" if stale_scc != ascc: - fresh_msg += " (%s)" % " ".join(sorted(stale_scc)) + fresh_msg += f" ({' '.join(sorted(stale_scc))})" if stale_deps: - fresh_msg += " with stale deps (%s)" % " ".join(sorted(stale_deps)) + fresh_msg += f" with stale deps ({' '.join(sorted(stale_deps))})" else: - fresh_msg = "stale due to deps (%s)" % " ".join(sorted(stale_deps)) + fresh_msg = f"stale due to deps ({' '.join(sorted(stale_deps))})" # Initialize transitive_error for all SCC members from union # of transitive_error of dependencies. @@ -3371,7 +3370,7 @@ def topsort(data: Dict[T, Set[T]]) -> Iterable[Set[T]]: data = {item: (dep - ready) for item, dep in data.items() if item not in ready} - assert not data, "A cyclic dependency exists amongst %r" % data + assert not data, f"A cyclic dependency exists amongst {data!r}" def missing_stubs_file(cache_dir: str) -> str: @@ -3388,7 +3387,7 @@ def record_missing_stub_packages(cache_dir: str, missing_stub_packages: Set[str] if missing_stub_packages: with open(fnam, 'w') as f: for pkg in sorted(missing_stub_packages): - f.write('%s\n' % pkg) + f.write(f'{pkg}\n') else: if os.path.isfile(fnam): os.remove(fnam) diff --git a/mypy/checker.py b/mypy/checker.py index d0820e483d65..cff637dbb57a 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -886,7 +886,7 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) self.msg.unimported_type_becomes_any("Return type", ret_type, fdef) for idx, arg_type in enumerate(fdef.type.arg_types): if has_any_from_unimported_type(arg_type): - prefix = f"Argument {idx + 1} to \"{fdef.name}\"" + prefix = f'Argument {idx + 1} to "{fdef.name}"' self.msg.unimported_type_becomes_any(prefix, arg_type, fdef) check_for_explicit_any(fdef.type, self.options, self.is_typeshed_stub, self.msg, context=fdef) @@ -1918,9 +1918,7 @@ def check_final_enum(self, defn: ClassDef, base: TypeInfo) -> None: for sym in base.names.values(): if self.is_final_enum_value(sym): self.fail( - 'Cannot extend enum with existing members: "{}"'.format( - base.name, - ), + f'Cannot extend enum with existing members: "{base.name}"', defn, ) break @@ -2571,7 +2569,7 @@ def check_compatibility_super(self, lvalue: RefExpr, lvalue_type: Optional[Type] return self.check_subtype(compare_type, base_type, rvalue, message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, 'expression has type', - 'base class "%s" defined the type as' % base.name, + f'base class "{base.name}" defined the type as', code=codes.ASSIGNMENT) return True diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index ed6fd73acfa5..9dfc0e2a6458 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -263,7 +263,7 @@ def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: result = self.object_type() else: if isinstance(node, PlaceholderNode): - assert False, 'PlaceholderNode %r leaked to checker' % node.fullname + assert False, f'PlaceholderNode {node.fullname!r} leaked to checker' # Unknown reference; use any type implicitly to avoid # generating extra type errors. result = AnyType(TypeOfAny.from_error) diff --git a/mypy/checkstrformat.py b/mypy/checkstrformat.py index 589a1fd6ac40..20b3716ea513 100644 --- a/mypy/checkstrformat.py +++ b/mypy/checkstrformat.py @@ -718,7 +718,7 @@ def check_mapping_str_interpolation(self, specifiers: List[ConversionSpecifier], self.chk.check_subtype(rep_type, expected_type, replacements, message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION, 'expression has type', - 'placeholder with key \'%s\' has type' % specifier.key, + f'placeholder with key \'{specifier.key}\' has type', code=codes.STRING_FORMATTING) if specifier.conv_type == 's': self.check_s_special_cases(expr, rep_type, expr) diff --git a/mypy/config_parser.py b/mypy/config_parser.py index a9ba8535a5d6..952c3f96f29a 100644 --- a/mypy/config_parser.py +++ b/mypy/config_parser.py @@ -211,10 +211,10 @@ def parse_config_file(options: Options, set_strict_flags: Callable[[], None], if 'mypy' not in parser: if filename or file_read not in defaults.SHARED_CONFIG_FILES: - print("%s: No [mypy] section in config file" % file_read, file=stderr) + print(f"{file_read}: No [mypy] section in config file", file=stderr) else: section = parser['mypy'] - prefix = '{}: [{}]: '.format(file_read, 'mypy') + prefix = f"{file_read}: [mypy]: " updates, report_dirs = parse_section( prefix, options, set_strict_flags, section, config_types, stderr) for k, v in updates.items(): @@ -322,7 +322,7 @@ def destructure_overrides(toml_data: Dict[str, Any]) -> Dict[str, Any]: for module in modules: module_overrides = override.copy() del module_overrides['module'] - old_config_name = 'mypy-%s' % module + old_config_name = f'mypy-{module}' if old_config_name not in result: result[old_config_name] = module_overrides else: @@ -447,7 +447,7 @@ def convert_to_boolean(value: Optional[Any]) -> bool: if not isinstance(value, str): value = str(value) if value.lower() not in configparser.RawConfigParser.BOOLEAN_STATES: - raise ValueError('Not a boolean: %s' % value) + raise ValueError(f'Not a boolean: {value}') return configparser.RawConfigParser.BOOLEAN_STATES[value.lower()] @@ -552,7 +552,7 @@ def get_config_module_names(filename: Optional[str], modules: List[str]) -> str: return '' if not is_toml(filename): - return ", ".join("[mypy-%s]" % module for module in modules) + return ", ".join(f"[mypy-{module}]" for module in modules) return "module = ['%s']" % ("', '".join(sorted(modules))) diff --git a/mypy/dmypy/client.py b/mypy/dmypy/client.py index 56ec804ad7a7..3ed85dca9750 100644 --- a/mypy/dmypy/client.py +++ b/mypy/dmypy/client.py @@ -273,7 +273,7 @@ def do_run(args: argparse.Namespace) -> None: response = request(args.status_file, 'run', version=__version__, args=args.flags) # If the daemon signals that a restart is necessary, do it if 'restart' in response: - print('Restarting: {}'.format(response['restart'])) + print(f"Restarting: {response['restart']}") restart_server(args, allow_sources=True) response = request(args.status_file, 'run', version=__version__, args=args.flags) @@ -300,7 +300,7 @@ def do_status(args: argparse.Namespace) -> None: if args.verbose or 'error' in response: show_stats(response) if 'error' in response: - fail("Daemon is stuck; consider %s kill" % sys.argv[0]) + fail(f"Daemon is stuck; consider {sys.argv[0]} kill") print("Daemon is up and running") @@ -311,7 +311,7 @@ def do_stop(args: argparse.Namespace) -> None: response = request(args.status_file, 'stop', timeout=5) if 'error' in response: show_stats(response) - fail("Daemon is stuck; consider %s kill" % sys.argv[0]) + fail(f"Daemon is stuck; consider {sys.argv[0]} kill") else: print("Daemon stopped") @@ -389,7 +389,7 @@ def check_output(response: Dict[str, Any], verbose: bool, try: out, err, status_code = response['out'], response['err'], response['status'] except KeyError: - fail("Response: %s" % str(response)) + fail(f"Response: {str(response)}") sys.stdout.write(out) sys.stdout.flush() sys.stderr.write(err) diff --git a/mypy/dmypy_server.py b/mypy/dmypy_server.py index de03d6400525..3fbda6b1a7d8 100644 --- a/mypy/dmypy_server.py +++ b/mypy/dmypy_server.py @@ -264,7 +264,7 @@ def run_command(self, command: str, data: Dict[str, object]) -> Dict[str, object key = 'cmd_' + command method = getattr(self.__class__, key, None) if method is None: - return {'error': "Unrecognized command '%s'" % command} + return {'error': f"Unrecognized command '{command}'"} else: if command not in {'check', 'recheck', 'run'}: # Only the above commands use some error formatting. diff --git a/mypy/dmypy_util.py b/mypy/dmypy_util.py index 8a527afe5762..2b458c51e5a4 100644 --- a/mypy/dmypy_util.py +++ b/mypy/dmypy_util.py @@ -27,5 +27,5 @@ def receive(connection: IPCBase) -> Any: except Exception as e: raise OSError("Data received is not valid JSON") from e if not isinstance(data, dict): - raise OSError("Data received is not a dict (%s)" % str(type(data))) + raise OSError(f"Data received is not a dict ({type(data)})") return data diff --git a/mypy/fastparse.py b/mypy/fastparse.py index e4e8f4a7888d..242b6d260c1e 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -56,7 +56,7 @@ if sys.version_info >= (3, 8): import ast as ast3 assert 'kind' in ast3.Constant._fields, \ - "This 3.8.0 alpha (%s) is too old; 3.8.0a3 required" % sys.version.split()[0] + f"This 3.8.0 alpha ({sys.version.split()[0]}) is too old; 3.8.0a3 required" # TODO: Num, Str, Bytes, NameConstant, Ellipsis are deprecated in 3.8. # TODO: Index, ExtSlice are deprecated in 3.9. from ast import ( diff --git a/mypy/main.py b/mypy/main.py index 6b0238295314..f598194455c1 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -791,9 +791,9 @@ def add_invertible_flag(flag: str, description='Generate a report in the specified format.') for report_type in sorted(defaults.REPORTER_NAMES): if report_type not in {'memory-xml'}: - report_group.add_argument('--%s-report' % report_type.replace('_', '-'), + report_group.add_argument(f"--{report_type.replace('_', '-')}-report", metavar='DIR', - dest='special-opts:%s_report' % report_type) + dest=f'special-opts:{report_type}_report') other_group = parser.add_argument_group( title='Miscellaneous') @@ -918,7 +918,7 @@ def add_invertible_flag(flag: str, # Don't explicitly test if "config_file is not None" for this check. # This lets `--config-file=` (an empty string) be used to disable all config files. if config_file and not os.path.exists(config_file): - parser.error("Cannot find config file '%s'" % config_file) + parser.error(f"Cannot find config file '{config_file}'") options = Options() @@ -989,8 +989,7 @@ def set_strict_flags() -> None: invalid_codes = (enabled_codes | disabled_codes) - valid_error_codes if invalid_codes: - parser.error("Invalid error code(s): %s" % - ', '.join(sorted(invalid_codes))) + parser.error(f"Invalid error code(s): {', '.join(sorted(invalid_codes))}") options.disabled_error_codes |= {error_codes[code] for code in disabled_codes} options.enabled_error_codes |= {error_codes[code] for code in enabled_codes} @@ -1090,17 +1089,17 @@ def process_package_roots(fscache: Optional[FileSystemCache], package_root = [] for root in options.package_root: if os.path.isabs(root): - parser.error("Package root cannot be absolute: %r" % root) + parser.error(f"Package root cannot be absolute: {root!r}") drive, root = os.path.splitdrive(root) if drive and drive != current_drive: - parser.error("Package root must be on current drive: %r" % (drive + root)) + parser.error(f"Package root must be on current drive: {drive + root!r}") # Empty package root is always okay. if root: root = os.path.relpath(root) # Normalize the heck out of it. if not root.endswith(os.sep): root = root + os.sep if root.startswith(dotdotslash): - parser.error("Package root cannot be above current directory: %r" % root) + parser.error(f"Package root cannot be above current directory: {root!r}") if root in trivial_paths: root = '' package_root.append(root) @@ -1119,9 +1118,9 @@ def process_cache_map(parser: argparse.ArgumentParser, for i in range(0, n, 3): source, meta_file, data_file = special_opts.cache_map[i:i + 3] if source in options.cache_map: - parser.error("Duplicate --cache-map source %s)" % source) + parser.error(f"Duplicate --cache-map source {source})") if not source.endswith('.py') and not source.endswith('.pyi'): - parser.error("Invalid --cache-map source %s (triple[0] must be *.py[i])" % source) + parser.error(f"Invalid --cache-map source {source} (triple[0] must be *.py[i])") if not meta_file.endswith('.meta.json'): parser.error("Invalid --cache-map meta_file %s (triple[1] must be *.meta.json)" % meta_file) @@ -1140,7 +1139,7 @@ def maybe_write_junit_xml(td: float, serious: bool, messages: List[str], options def fail(msg: str, stderr: TextIO, options: Options) -> NoReturn: """Fail with a serious error.""" - stderr.write('%s\n' % msg) + stderr.write(f'{msg}\n') maybe_write_junit_xml(0.0, serious=True, messages=[msg], options=options) sys.exit(2) diff --git a/mypy/memprofile.py b/mypy/memprofile.py index 7494fed75750..ac49fd346abc 100644 --- a/mypy/memprofile.py +++ b/mypy/memprofile.py @@ -33,23 +33,23 @@ def collect_memory_stats() -> Tuple[Dict[str, int], n = type(obj).__name__ if hasattr(obj, '__dict__'): # Keep track of which class a particular __dict__ is associated with. - inferred[id(obj.__dict__)] = '%s (__dict__)' % n + inferred[id(obj.__dict__)] = f'{n} (__dict__)' if isinstance(obj, (Node, Type)): # type: ignore if hasattr(obj, '__dict__'): for x in obj.__dict__.values(): if isinstance(x, list): # Keep track of which node a list is associated with. - inferred[id(x)] = '%s (list)' % n + inferred[id(x)] = f'{n} (list)' if isinstance(x, tuple): # Keep track of which node a list is associated with. - inferred[id(x)] = '%s (tuple)' % n + inferred[id(x)] = f'{n} (tuple)' for k in get_class_descriptors(type(obj)): x = getattr(obj, k, None) if isinstance(x, list): - inferred[id(x)] = '%s (list)' % n + inferred[id(x)] = f'{n} (list)' if isinstance(x, tuple): - inferred[id(x)] = '%s (tuple)' % n + inferred[id(x)] = f'{n} (tuple)' freqs: Dict[str, int] = {} memuse: Dict[str, int] = {} diff --git a/mypy/messages.py b/mypy/messages.py index 801f84c2580b..70d79384c1a9 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -365,8 +365,7 @@ def unsupported_operand_types(self, if self.are_type_names_disabled(): msg = f'Unsupported operand types for {op} (likely involving Union)' else: - msg = 'Unsupported operand types for {} ({} and {})'.format( - op, left_str, right_str) + msg = f'Unsupported operand types for {op} ({left_str} and {right_str})' self.fail(msg, context, code=code) def unsupported_left_operand(self, op: str, typ: Type, @@ -374,8 +373,7 @@ def unsupported_left_operand(self, op: str, typ: Type, if self.are_type_names_disabled(): msg = f'Unsupported left operand type for {op} (some union)' else: - msg = 'Unsupported left operand type for {} ({})'.format( - op, format_type(typ)) + msg = f'Unsupported left operand type for {op} ({format_type(typ)})' self.fail(msg, context, code=codes.OPERATOR) def not_callable(self, typ: Type, context: Context) -> Type: @@ -707,7 +705,7 @@ def unexpected_keyword_argument(self, callee: CallableType, name: str, arg_type: if not matches: matches = best_matches(name, not_matching_type_args) if matches: - msg += "; did you mean {}?".format(pretty_seq(matches[:3], "or")) + msg += f"; did you mean {pretty_seq(matches[:3], 'or')}?" self.fail(msg, context, code=codes.CALL_ARG) module = find_defining_module(self.modules, callee) if module: @@ -980,7 +978,7 @@ def too_many_string_formatting_arguments(self, context: Context) -> None: code=codes.STRING_FORMATTING) def unsupported_placeholder(self, placeholder: str, context: Context) -> None: - self.fail('Unsupported format character "%s"' % placeholder, context, + self.fail(f'Unsupported format character "{placeholder}"', context, code=codes.STRING_FORMATTING) def string_interpolation_with_star_and_key(self, context: Context) -> None: @@ -999,7 +997,7 @@ def requires_int_or_char(self, context: Context, context, code=codes.STRING_FORMATTING) def key_not_in_mapping(self, key: str, context: Context) -> None: - self.fail('Key "%s" not found in mapping' % key, context, + self.fail(f'Key "{key}" not found in mapping', context, code=codes.STRING_FORMATTING) def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None: @@ -1007,7 +1005,7 @@ def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None code=codes.STRING_FORMATTING) def cannot_determine_type(self, name: str, context: Context) -> None: - self.fail('Cannot determine type of "%s"' % name, context, code=codes.HAS_TYPE) + self.fail(f'Cannot determine type of "{name}"', context, code=codes.HAS_TYPE) def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None: self.fail(f'Cannot determine type of "{name}" in base class "{base}"', context) @@ -1029,7 +1027,7 @@ def incompatible_conditional_function_def(self, defn: FuncDef) -> None: def cannot_instantiate_abstract_class(self, class_name: str, abstract_attributes: List[str], context: Context) -> None: - attrs = format_string_list(['"%s"' % a for a in abstract_attributes]) + attrs = format_string_list([f'"{a}"' for a in abstract_attributes]) self.fail('Cannot instantiate abstract class "%s" with abstract ' 'attribute%s %s' % (class_name, plural_s(abstract_attributes), attrs), @@ -1047,7 +1045,7 @@ def cant_assign_to_method(self, context: Context) -> None: code=codes.ASSIGNMENT) def cant_assign_to_classvar(self, name: str, context: Context) -> None: - self.fail('Cannot assign to class variable "%s" via instance' % name, context) + self.fail(f'Cannot assign to class variable "{name}" via instance', context) def final_cant_override_writable(self, name: str, ctx: Context) -> None: self.fail(f'Cannot override writable attribute "{name}" with a final one', ctx) @@ -1072,8 +1070,7 @@ def final_without_value(self, ctx: Context) -> None: def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None: - self.fail('Property "{}" defined in "{}" is read-only'.format( - name, type.name), context) + self.fail(f'Property "{name}" defined in "{type.name}" is read-only', context) def incompatible_typevar_value(self, callee: CallableType, @@ -1142,8 +1139,7 @@ def operator_method_signatures_overlap( def forward_operator_not_callable( self, forward_method: str, context: Context) -> None: - self.fail('Forward operator "{}" is not callable'.format( - forward_method), context) + self.fail(f'Forward operator "{forward_method}" is not callable', context) def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None: @@ -1322,8 +1318,7 @@ def disallowed_any_type(self, typ: Type, context: Context) -> None: self.fail(message, context) def incorrectly_returning_any(self, typ: Type, context: Context) -> None: - message = 'Returning Any from function declared to return {}'.format( - format_type(typ)) + message = f'Returning Any from function declared to return {format_type(typ)}' self.fail(message, context, code=codes.NO_ANY_RETURN) def incorrect__exit__return(self, context: Context) -> None: @@ -1481,8 +1476,7 @@ def report_protocol_problems(self, if conflict_types and (not is_subtype(subtype, erase_type(supertype)) or not subtype.type.defn.type_vars or not supertype.type.defn.type_vars): - self.note('Following member(s) of {} have ' - 'conflicts:'.format(format_type(subtype)), + self.note(f'Following member(s) of {format_type(subtype)} have conflicts:', context, code=code) for name, got, exp in conflict_types[:MAX_ITEMS]: @@ -1562,8 +1556,7 @@ def print_more(self, *, code: Optional[ErrorCode] = None) -> None: if len(conflicts) > max_items: - self.note('<{} more conflict(s) not shown>' - .format(len(conflicts) - max_items), + self.note(f'<{len(conflicts) - max_items} more conflict(s) not shown>', context, offset=offset, code=code) def try_report_long_tuple_assignment_error(self, @@ -1670,9 +1663,7 @@ def format_callable_args(arg_types: List[Type], arg_kinds: List[ArgKind], else: constructor = ARG_CONSTRUCTOR_NAMES[arg_kind] if arg_kind.is_star() or arg_name is None: - arg_strings.append("{}({})".format( - constructor, - format(arg_type))) + arg_strings.append(f"{constructor}({format(arg_type)})") else: arg_strings.append("{}({}, {})".format( constructor, @@ -1760,10 +1751,8 @@ def format_literal_value(typ: LiteralType) -> str: items = [] for (item_name, item_type) in typ.items.items(): modifier = '' if item_name in typ.required_keys else '?' - items.append('{!r}{}: {}'.format(item_name, - modifier, - format(item_type))) - s = 'TypedDict({{{}}})'.format(', '.join(items)) + items.append(f'{item_name!r}{modifier}: {format(item_type)}') + s = f"TypedDict({{{', '.join(items)}}})" return s elif isinstance(typ, LiteralType): return f'Literal[{format_literal_value(typ)}]' @@ -2027,7 +2016,7 @@ def [T <: int] f(self, x: int, y: T) -> None else: # For other TypeVarLikeTypes, just use the repr tvars.append(repr(tvar)) - s = '[{}] {}'.format(', '.join(tvars), s) + s = f"[{', '.join(tvars)}] {s}" return f'def {s}' @@ -2134,7 +2123,7 @@ def format_string_list(lst: List[str]) -> str: if len(lst) == 1: return lst[0] elif len(lst) <= 5: - return '{} and {}'.format(', '.join(lst[:-1]), lst[-1]) + return f"{', '.join(lst[:-1])} and {lst[-1]}" else: return '%s, ... and %s (%i methods suppressed)' % ( ', '.join(lst[:2]), lst[-1], len(lst) - 3) @@ -2143,9 +2132,9 @@ def format_string_list(lst: List[str]) -> str: def format_item_name_list(s: Iterable[str]) -> str: lst = list(s) if len(lst) <= 5: - return '(' + ', '.join(['"%s"' % name for name in lst]) + ')' + return '(' + ', '.join([f'"{name}"' for name in lst]) + ')' else: - return '(' + ', '.join(['"%s"' % name for name in lst[:5]]) + ', ...)' + return '(' + ', '.join([f'"{name}"' for name in lst[:5]]) + ', ...)' def callable_name(type: FunctionLike) -> Optional[str]: @@ -2263,4 +2252,4 @@ def format_key_list(keys: List[str], *, short: bool = False) -> str: elif len(keys) == 1: return f'{td}key {formatted_keys[0]}' else: - return '{}keys ({})'.format(td, ', '.join(formatted_keys)) + return f"{td}keys ({', '.join(formatted_keys)})" diff --git a/mypy/moduleinspect.py b/mypy/moduleinspect.py index ebcbb25ea5e5..2b2068e0b7c5 100644 --- a/mypy/moduleinspect.py +++ b/mypy/moduleinspect.py @@ -138,7 +138,7 @@ def get_package_properties(self, package_id: str) -> ModuleProperties: if res is None: # The process died; recover and report error. self._start() - raise InspectError('Process died when importing %r' % package_id) + raise InspectError(f'Process died when importing {package_id!r}') if isinstance(res, str): # Error importing module if self.counter > 0: diff --git a/mypy/nodes.py b/mypy/nodes.py index c0e53ea9367c..4ffa3116a118 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -483,7 +483,7 @@ def deserialize(cls, data: JsonDict) -> 'ImportedName': assert False, "ImportedName should never be serialized" def __str__(self) -> str: - return 'ImportedName(%s)' % self.target_fullname + return f'ImportedName({self.target_fullname})' FUNCBASE_FLAGS: Final = ["is_property", "is_class", "is_static", "is_final"] @@ -2778,7 +2778,7 @@ def __getitem__(self, name: str) -> 'SymbolTableNode': raise KeyError(name) def __repr__(self) -> str: - return '' % self.fullname + return f'' def __bool__(self) -> bool: # We defined this here instead of just overriding it in @@ -2859,8 +2859,7 @@ def type_str(typ: 'mypy.types.Type') -> str: head = 'TypeInfo' + str_conv.format_id(self) if self.bases: - base = 'Bases({})'.format(', '.join(type_str(base) - for base in self.bases)) + base = f"Bases({', '.join(type_str(base) for base in self.bases)})" mro = 'Mro({})'.format(', '.join(item.fullname + str_conv.format_id(item) for item in self.mro)) names = [] diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 5827a21e8ccf..62b4c89bd674 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -195,7 +195,7 @@ def transform(self) -> None: if existing_method is not None and not existing_method.plugin_generated: assert existing_method.node ctx.api.fail( - 'You may not have a custom %s method when order=True' % method_name, + f'You may not have a custom {method_name} method when order=True', existing_method.node, ) diff --git a/mypy/plugins/singledispatch.py b/mypy/plugins/singledispatch.py index 0eb855d3a315..d6150836c562 100644 --- a/mypy/plugins/singledispatch.py +++ b/mypy/plugins/singledispatch.py @@ -48,9 +48,7 @@ def get_first_arg(args: List[List[T]]) -> Optional[T]: REGISTER_RETURN_CLASS: Final = '_SingleDispatchRegisterCallable' -REGISTER_CALLABLE_CALL_METHOD: Final = 'functools.{}.__call__'.format( - REGISTER_RETURN_CLASS -) +REGISTER_CALLABLE_CALL_METHOD: Final = f'functools.{REGISTER_RETURN_CLASS}.__call__' def make_fake_register_class_instance(api: CheckerPluginInterface, type_args: Sequence[Type] diff --git a/mypy/report.py b/mypy/report.py index 8d3465f3c1f0..28fa5c274b74 100644 --- a/mypy/report.py +++ b/mypy/report.py @@ -181,8 +181,7 @@ def on_finish(self) -> None: with open(os.path.join(self.output_dir, "linecount.txt"), "w") as f: f.write("{:7} {:7} {:6} {:6} total\n".format(*total_counts)) for c, p in counts: - f.write('{:7} {:7} {:6} {:6} {}\n'.format( - c[0], c[1], c[2], c[3], p)) + f.write(f'{c[0]:7} {c[1]:7} {c[2]:6} {c[3]:6} {p}\n') register_reporter('linecount', LineCountReporter) @@ -490,7 +489,7 @@ def on_file(self, # Assumes a layout similar to what XmlReporter uses. xslt_path = os.path.relpath('mypy-html.xslt', path) transform_pi = etree.ProcessingInstruction('xml-stylesheet', - 'type="text/xsl" href="%s"' % pathname2url(xslt_path)) + f'type="text/xsl" href="{pathname2url(xslt_path)}"') root.addprevious(transform_pi) self.schema.assertValid(doc) @@ -526,7 +525,7 @@ def on_finish(self) -> None: total=str(file_info.total())) xslt_path = os.path.relpath('mypy-html.xslt', '.') transform_pi = etree.ProcessingInstruction('xml-stylesheet', - 'type="text/xsl" href="%s"' % pathname2url(xslt_path)) + f'type="text/xsl" href="{pathname2url(xslt_path)}"') root.addprevious(transform_pi) self.schema.assertValid(doc) diff --git a/mypy/semanal.py b/mypy/semanal.py index eb0411f0afc8..a9445a9c8748 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -366,7 +366,7 @@ def prepare_builtins_namespace(self, file_node: MypyFile) -> None: for name in CORE_BUILTIN_CLASSES: cdef = ClassDef(name, Block([])) # Dummy ClassDef, will be replaced later info = TypeInfo(SymbolTable(), cdef, 'builtins') - info._fullname = 'builtins.%s' % name + info._fullname = f'builtins.{name}' names[name] = SymbolTableNode(GDEF, info) bool_info = names['bool'].node @@ -388,7 +388,7 @@ def prepare_builtins_namespace(self, file_node: MypyFile) -> None: for name, typ in special_var_types: v = Var(name, typ) - v._fullname = 'builtins.%s' % name + v._fullname = f'builtins.{name}' file_node.names[name] = SymbolTableNode(GDEF, v) # @@ -1107,7 +1107,7 @@ def visit_decorator(self, dec: Decorator) -> None: def check_decorated_function_is_method(self, decorator: str, context: Context) -> None: if not self.type or self.is_func_scope(): - self.fail('"%s" used with a non-method' % decorator, context) + self.fail(f'"{decorator}" used with a non-method', context) # # Classes @@ -1722,7 +1722,7 @@ def verify_base_classes(self, defn: ClassDef) -> bool: return False dup = find_duplicate(info.direct_base_classes()) if dup: - self.fail('Duplicate base class "%s"' % dup.name, defn, blocker=True) + self.fail(f'Duplicate base class "{dup.name}"', defn, blocker=True) return False return not cycle @@ -1749,7 +1749,7 @@ def analyze_metaclass(self, defn: ClassDef) -> None: elif isinstance(defn.metaclass, MemberExpr): metaclass_name = get_member_expr_fullname(defn.metaclass) if metaclass_name is None: - self.fail('Dynamic metaclass not supported for "%s"' % defn.name, defn.metaclass) + self.fail(f'Dynamic metaclass not supported for "{defn.name}"', defn.metaclass) return sym = self.lookup_qualified(metaclass_name, defn.metaclass) if sym is None: @@ -1766,7 +1766,7 @@ def analyze_metaclass(self, defn: ClassDef) -> None: self.defer(defn) return if not isinstance(sym.node, TypeInfo) or sym.node.tuple_type is not None: - self.fail('Invalid metaclass "%s"' % metaclass_name, defn.metaclass) + self.fail(f'Invalid metaclass "{metaclass_name}"', defn.metaclass) return if not sym.node.is_metaclass(): self.fail('Metaclasses not inheriting from "type" are not supported', @@ -1788,7 +1788,7 @@ def analyze_metaclass(self, defn: ClassDef) -> None: # Inconsistency may happen due to multiple baseclasses even in classes that # do not declare explicit metaclass, but it's harder to catch at this stage if defn.metaclass is not None: - self.fail('Inconsistent metaclass structure for "%s"' % defn.name, defn) + self.fail(f'Inconsistent metaclass structure for "{defn.name}"', defn) else: if defn.info.metaclass_type.type.has_base('enum.EnumMeta'): defn.info.is_enum = True @@ -1953,7 +1953,7 @@ def report_missing_module_attribute( alternatives = set(module.names.keys()).difference({source_id}) matches = best_matches(source_id, alternatives)[:3] if matches: - suggestion = "; maybe {}?".format(pretty_seq(matches, "or")) + suggestion = f"; maybe {pretty_seq(matches, 'or')}?" message += f"{suggestion}" self.fail(message, context, code=codes.ATTR_DEFINED) self.add_unknown_imported_symbol( @@ -3120,7 +3120,7 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool: # Also give error for another type variable with the same name. (isinstance(existing.node, TypeVarExpr) and existing.node is call.analyzed)): - self.fail('Cannot redefine "%s" as a type variable' % name, s) + self.fail(f'Cannot redefine "{name}" as a type variable', s) return False if self.options.disallow_any_unimported: diff --git a/mypy/semanal_enum.py b/mypy/semanal_enum.py index 251767bef3e0..0f09a4bf9457 100644 --- a/mypy/semanal_enum.py +++ b/mypy/semanal_enum.py @@ -119,11 +119,11 @@ def parse_enum_call_args(self, call: CallExpr, """ args = call.args if not all([arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds]): - return self.fail_enum_call_arg("Unexpected arguments to %s()" % class_name, call) + return self.fail_enum_call_arg(f"Unexpected arguments to {class_name}()", call) if len(args) < 2: - return self.fail_enum_call_arg("Too few arguments for %s()" % class_name, call) + return self.fail_enum_call_arg(f"Too few arguments for {class_name}()", call) if len(args) > 6: - return self.fail_enum_call_arg("Too many arguments for %s()" % class_name, call) + return self.fail_enum_call_arg(f"Too many arguments for {class_name}()", call) valid_name = [None, 'value', 'names', 'module', 'qualname', 'type', 'start'] for arg_name in call.arg_names: if arg_name not in valid_name: @@ -140,7 +140,7 @@ def parse_enum_call_args(self, call: CallExpr, names = args[1] if not isinstance(value, (StrExpr, UnicodeExpr)): return self.fail_enum_call_arg( - "%s() expects a string literal as the first argument" % class_name, call) + f"{class_name}() expects a string literal as the first argument", call) items = [] values: List[Optional[Expression]] = [] if isinstance(names, (StrExpr, UnicodeExpr)): @@ -171,7 +171,7 @@ def parse_enum_call_args(self, call: CallExpr, for key, value in names.items: if not isinstance(key, (StrExpr, UnicodeExpr)): return self.fail_enum_call_arg( - "%s() with dict literal requires string literals" % class_name, call) + f"{class_name}() with dict literal requires string literals", call) items.append(key.value) values.append(value) elif isinstance(args[1], RefExpr) and isinstance(args[1].node, Var): @@ -198,7 +198,7 @@ def parse_enum_call_args(self, call: CallExpr, class_name, call) if len(items) == 0: - return self.fail_enum_call_arg("%s() needs at least one item" % class_name, call) + return self.fail_enum_call_arg(f"{class_name}() needs at least one item", call) if not values: values = [None] * len(items) assert len(items) == len(values) diff --git a/mypy/semanal_newtype.py b/mypy/semanal_newtype.py index 047df3d85b83..948c5b36052f 100644 --- a/mypy/semanal_newtype.py +++ b/mypy/semanal_newtype.py @@ -127,7 +127,7 @@ def analyze_newtype_declaration(self, # Give a better error message than generic "Name already defined". if (existing and not isinstance(existing.node, PlaceholderNode) and not s.rvalue.analyzed): - self.fail('Cannot redefine "%s" as a NewType' % name, s) + self.fail(f'Cannot redefine "{name}" as a NewType', s) # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be # overwritten later with a fully complete NewTypeExpr if there are no other diff --git a/mypy/semanal_typeddict.py b/mypy/semanal_typeddict.py index 3b384bdec1a3..4087f477c597 100644 --- a/mypy/semanal_typeddict.py +++ b/mypy/semanal_typeddict.py @@ -86,7 +86,7 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> Tuple[bool, Optional[Typ typeddict_bases.append(expr) else: assert isinstance(expr.node, TypeInfo) - self.fail('Duplicate base class "%s"' % expr.node.name, defn) + self.fail(f'Duplicate base class "{expr.node.name}"', defn) else: self.fail("All bases of a new TypedDict must be TypedDict types", defn) diff --git a/mypy/server/deps.py b/mypy/server/deps.py index b70a43db2540..f339344e79b5 100644 --- a/mypy/server/deps.py +++ b/mypy/server/deps.py @@ -1040,4 +1040,4 @@ def dump_all_dependencies(modules: Dict[str, MypyFile], for trigger, targets in sorted(all_deps.items(), key=lambda x: x[0]): print(trigger) for target in sorted(targets): - print(' %s' % target) + print(f' {target}') diff --git a/mypy/server/mergecheck.py b/mypy/server/mergecheck.py index 2c28242251e9..41d19f60f436 100644 --- a/mypy/server/mergecheck.py +++ b/mypy/server/mergecheck.py @@ -70,14 +70,14 @@ def path_to_str(path: List[Tuple[object, object]]) -> str: for attr, obj in path: t = type(obj).__name__ if t in ('dict', 'tuple', 'SymbolTable', 'list'): - result += '[%s]' % repr(attr) + result += f'[{repr(attr)}]' else: if isinstance(obj, Var): result += f'.{attr}({t}:{obj.name})' elif t in ('BuildManager', 'FineGrainedBuildManager'): # Omit class name for some classes that aren't part of a class # hierarchy since there isn't much ambiguity. - result += '.%s' % attr + result += f'.{attr}' else: result += f'.{attr}({t})' return result diff --git a/mypy/server/trigger.py b/mypy/server/trigger.py index 3b9b02d20c81..bfd542a40537 100644 --- a/mypy/server/trigger.py +++ b/mypy/server/trigger.py @@ -9,7 +9,7 @@ def make_trigger(name: str) -> str: - return '<%s>' % name + return f'<{name}>' def make_wildcard_trigger(module: str) -> str: diff --git a/mypy/server/update.py b/mypy/server/update.py index 233e989a0e36..e50bb1d158a2 100644 --- a/mypy/server/update.py +++ b/mypy/server/update.py @@ -236,7 +236,7 @@ def update(self, if self.blocking_error: # Handle blocking errors first. We'll exit as soon as we find a # module that still has blocking errors. - self.manager.log_fine_grained('existing blocker: %s' % self.blocking_error[0]) + self.manager.log_fine_grained(f'existing blocker: {self.blocking_error[0]}') changed_modules = dedupe_modules([self.blocking_error] + changed_modules) blocking_error = self.blocking_error[0] self.blocking_error = None @@ -322,7 +322,7 @@ def update_one(self, and next_id not in self.previous_modules and next_id not in initial_set): self.manager.log_fine_grained( - 'skip %r (module with blocking error not in import graph)' % next_id) + f'skip {next_id!r} (module with blocking error not in import graph)') return changed_modules, (next_id, next_path), None result = self.update_module(next_id, next_path, next_id in removed_set) @@ -333,8 +333,7 @@ def update_one(self, t1 = time.time() self.manager.log_fine_grained( - "update once: {} in {:.3f}s - {} left".format( - next_id, t1 - t0, len(changed_modules))) + f"update once: {next_id} in {t1 - t0:.3f}s - {len(changed_modules)} left") return changed_modules, (next_id, next_path), blocker_messages @@ -362,7 +361,7 @@ def update_module(self, - Module which was actually processed as (id, path) tuple - If there was a blocking error, the error messages from it """ - self.manager.log_fine_grained('--- update single %r ---' % module) + self.manager.log_fine_grained(f'--- update single {module!r} ---') self.updated_modules.append(module) # builtins and friends could potentially get triggered because @@ -406,7 +405,7 @@ def update_module(self, if is_verbose(self.manager): filtered = [trigger for trigger in triggered if not trigger.endswith('__>')] - self.manager.log_fine_grained('triggered: %r' % sorted(filtered)) + self.manager.log_fine_grained(f'triggered: {sorted(filtered)!r}') self.triggered.extend(triggered | self.previous_targets_with_errors) if module in graph: graph[module].update_fine_grained_deps(self.deps) @@ -534,7 +533,7 @@ def update_module_isolated(module: str, Returns a named tuple describing the result (see above for details). """ if module not in graph: - manager.log_fine_grained('new module %r' % module) + manager.log_fine_grained(f'new module {module!r}') if not manager.fscache.isfile(path) or force_removed: delete_module(module, path, graph, manager) @@ -592,7 +591,7 @@ def restore(ids: List[str]) -> None: remaining_modules = changed_modules # The remaining modules haven't been processed yet so drop them. restore([id for id, _ in remaining_modules]) - manager.log_fine_grained('--> %r (newly imported)' % module) + manager.log_fine_grained(f'--> {module!r} (newly imported)') else: remaining_modules = [] @@ -662,7 +661,7 @@ def delete_module(module_id: str, path: str, graph: Graph, manager: BuildManager) -> None: - manager.log_fine_grained('delete module %r' % module_id) + manager.log_fine_grained(f'delete module {module_id!r}') # TODO: Remove deps for the module (this only affects memory use, not correctness) if module_id in graph: del graph[module_id] @@ -815,7 +814,7 @@ def propagate_changes_using_dependencies( if id is not None and id not in up_to_date_modules: if id not in todo: todo[id] = set() - manager.log_fine_grained('process target with error: %s' % target) + manager.log_fine_grained(f'process target with error: {target}') more_nodes, _ = lookup_target(manager, target) todo[id].update(more_nodes) triggered = set() @@ -835,7 +834,7 @@ def propagate_changes_using_dependencies( up_to_date_modules = set() targets_with_errors = set() if is_verbose(manager): - manager.log_fine_grained('triggered: %r' % list(triggered)) + manager.log_fine_grained(f'triggered: {list(triggered)!r}') return remaining_modules @@ -891,7 +890,7 @@ def find_targets_recursive( if module_id not in result: result[module_id] = set() - manager.log_fine_grained('process: %s' % target) + manager.log_fine_grained(f'process: {target}') deferred, stale_proto = lookup_target(manager, target) if stale_proto: stale_protos.add(stale_proto) @@ -1040,7 +1039,7 @@ def lookup_target(manager: BuildManager, """ def not_found() -> None: manager.log_fine_grained( - "Can't find matching target for %s (stale dependency?)" % target) + f"Can't find matching target for {target} (stale dependency?)") modules = manager.modules items = split_target(modules, target) diff --git a/mypy/strconv.py b/mypy/strconv.py index 13f3e04ef712..8d6cf92d8f2a 100644 --- a/mypy/strconv.py +++ b/mypy/strconv.py @@ -112,7 +112,7 @@ def visit_import(self, o: 'mypy.nodes.Import') -> str: a.append(f'{id} : {as_id}') else: a.append(id) - return 'Import:{}({})'.format(o.line, ', '.join(a)) + return f"Import:{o.line}({', '.join(a)})" def visit_import_from(self, o: 'mypy.nodes.ImportFrom') -> str: a = [] @@ -121,10 +121,10 @@ def visit_import_from(self, o: 'mypy.nodes.ImportFrom') -> str: a.append(f'{name} : {as_name}') else: a.append(name) - return 'ImportFrom:{}({}, [{}])'.format(o.line, "." * o.relative + o.id, ', '.join(a)) + return f"ImportFrom:{o.line}({'.' * o.relative + o.id}, [{', '.join(a)}])" def visit_import_all(self, o: 'mypy.nodes.ImportAll') -> str: - return 'ImportAll:{}({})'.format(o.line, "." * o.relative + o.id) + return f"ImportAll:{o.line}({'.' * o.relative + o.id})" # Definitions @@ -418,7 +418,7 @@ def visit_call_expr(self, o: 'mypy.nodes.CallExpr') -> str: elif kind == mypy.nodes.ARG_STAR2: extra.append(('DictVarArg', [o.args[i]])) else: - raise RuntimeError("unknown kind %s" % kind) + raise RuntimeError(f"unknown kind {kind}") a: List[Any] = [o.callee, ("Args", args)] return self.dump(a + extra, o) @@ -512,23 +512,19 @@ def visit_type_alias_expr(self, o: 'mypy.nodes.TypeAliasExpr') -> str: return f'TypeAliasExpr({o.type})' def visit_namedtuple_expr(self, o: 'mypy.nodes.NamedTupleExpr') -> str: - return 'NamedTupleExpr:{}({}, {})'.format(o.line, - o.info.name, - o.info.tuple_type) + return f'NamedTupleExpr:{o.line}({o.info.name}, {o.info.tuple_type})' def visit_enum_call_expr(self, o: 'mypy.nodes.EnumCallExpr') -> str: return f'EnumCallExpr:{o.line}({o.info.name}, {o.items})' def visit_typeddict_expr(self, o: 'mypy.nodes.TypedDictExpr') -> str: - return 'TypedDictExpr:{}({})'.format(o.line, - o.info.name) + return f'TypedDictExpr:{o.line}({o.info.name})' def visit__promote_expr(self, o: 'mypy.nodes.PromoteExpr') -> str: return f'PromoteExpr:{o.line}({o.type})' def visit_newtype_expr(self, o: 'mypy.nodes.NewTypeExpr') -> str: - return 'NewTypeExpr:{}({}, {})'.format(o.line, o.name, - self.dump([o.old_type], o)) + return f'NewTypeExpr:{o.line}({o.name}, {self.dump([o.old_type], o)})' def visit_lambda_expr(self, o: 'mypy.nodes.LambdaExpr') -> str: a = self.func_helper(o) diff --git a/mypy/stubdoc.py b/mypy/stubdoc.py index a596ddb4f78d..175b6f9f432c 100644 --- a/mypy/stubdoc.py +++ b/mypy/stubdoc.py @@ -311,8 +311,8 @@ def build_signature(positional: Sequence[str], if arg.startswith('*'): args.append(arg) else: - args.append('%s=...' % arg) - sig = '(%s)' % ', '.join(args) + args.append(f'{arg}=...') + sig = f"({', '.join(args)})" # Ad-hoc fixes. sig = sig.replace('(self)', '') return sig diff --git a/mypy/stubgen.py b/mypy/stubgen.py index 41fc58a2b0fc..2d3e8e8f48ef 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -309,8 +309,8 @@ def visit_call_expr(self, node: CallExpr) -> str: elif kind == ARG_NAMED: args.append(f'{name}={arg.accept(self)}') else: - raise ValueError("Unknown argument kind %s in call" % kind) - return "{}({})".format(callee, ", ".join(args)) + raise ValueError(f"Unknown argument kind {kind} in call") + return f"{callee}({', '.join(args)})" def visit_name_expr(self, node: NameExpr) -> str: self.stubgen.import_tracker.require_name(node.name) @@ -339,7 +339,7 @@ def visit_tuple_expr(self, node: TupleExpr) -> str: return ", ".join(n.accept(self) for n in node.items) def visit_list_expr(self, node: ListExpr) -> str: - return "[{}]".format(", ".join(n.accept(self) for n in node.items)) + return f"[{', '.join(n.accept(self) for n in node.items)}]" def visit_ellipsis(self, node: EllipsisExpr) -> str: return "..." @@ -454,7 +454,7 @@ def import_lines(self) -> List[str]: # Now generate all the from ... import ... lines collected in module_map for module, names in sorted(module_map.items()): - result.append("from {} import {}\n".format(module, ', '.join(sorted(names)))) + result.append(f"from {module} import {', '.join(sorted(names))}\n") return result @@ -589,7 +589,7 @@ def visit_mypy_file(self, o: MypyFile) -> None: self.add('\n') self.add('# Names in __all__ with no definition:\n') for name in sorted(undefined_names): - self.add('# %s\n' % name) + self.add(f'# {name}\n') def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None: """@property with setters and getters, or @overload chain""" @@ -635,7 +635,7 @@ def visit_func_def(self, o: FuncDef, is_abstract: bool = False, for s in self._decorators: self.add(s) self.clear_decorators() - self.add("{}{}def {}(".format(self._indent, 'async ' if o.is_coroutine else '', o.name)) + self.add(f"{self._indent}{'async ' if o.is_coroutine else ''}def {o.name}(") self.record_name(o.name) args: List[str] = [] for i, arg_ in enumerate(o.arguments): @@ -799,7 +799,7 @@ def process_member_expr_decorator(self, expr: MemberExpr, context: Decorator) -> is_abstract = False is_overload = False if expr.name == 'setter' and isinstance(expr.expr, NameExpr): - self.add_decorator('%s.setter' % expr.expr.name) + self.add_decorator(f'{expr.expr.name}.setter') elif (isinstance(expr.expr, NameExpr) and (expr.expr.name == 'abc' or self.import_tracker.reverse_alias.get(expr.expr.name) == 'abc') and @@ -835,7 +835,7 @@ def process_member_expr_decorator(self, expr: MemberExpr, context: Decorator) -> self.import_tracker.reverse_alias.get(expr.expr.name) in TYPING_MODULE_NAMES) and expr.name == 'overload'): self.import_tracker.require_name(expr.expr.name) - self.add_decorator('{}.{}'.format(expr.expr.name, 'overload')) + self.add_decorator(f"{expr.expr.name}.overload") is_overload = True return is_abstract, is_overload @@ -865,7 +865,7 @@ def visit_class_def(self, o: ClassDef) -> None: base_types.append(type_str) self.add_typing_import('Protocol') if base_types: - self.add('(%s)' % ', '.join(base_types)) + self.add(f"({', '.join(base_types)})") self.add(':\n') n = len(self._output) self._indent += ' ' @@ -1036,7 +1036,7 @@ def visit_if_stmt(self, o: IfStmt) -> None: super().visit_if_stmt(o) def visit_import_all(self, o: ImportAll) -> None: - self.add_import_line('from {}{} import *\n'.format('.' * o.relative, o.id)) + self.add_import_line(f"from {'.' * o.relative}{o.id} import *\n") def visit_import_from(self, o: ImportFrom) -> None: exported_names: Set[str] = set() @@ -1227,7 +1227,7 @@ def get_str_type_of_node(self, rvalue: Expression, if can_infer_optional and \ isinstance(rvalue, NameExpr) and rvalue.name == 'None': self.add_typing_import('Incomplete') - return '{} | None'.format(self.typing_name('Incomplete')) + return f"{self.typing_name('Incomplete')} | None" if can_be_any: self.add_typing_import('Incomplete') return self.typing_name('Incomplete') @@ -1492,7 +1492,7 @@ def parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None: if errors.is_blockers(): # Syntax error! for m in errors.new_messages(): - sys.stderr.write('%s\n' % m) + sys.stderr.write(f'{m}\n') sys.exit(1) @@ -1504,7 +1504,7 @@ def generate_asts_for_modules(py_modules: List[StubSource], if not py_modules: return # Nothing to do here, but there may be C modules if verbose: - print('Processing %d files...' % len(py_modules)) + print(f'Processing {len(py_modules)} files...') if parse_only: for mod in py_modules: parse_source_file(mod, mypy_options) @@ -1557,7 +1557,7 @@ def collect_docs_signatures(doc_dir: str) -> Tuple[Dict[str, str], Dict[str, str """ all_sigs: List[Sig] = [] all_class_sigs: List[Sig] = [] - for path in glob.glob('%s/*.rst' % doc_dir): + for path in glob.glob(f'{doc_dir}/*.rst'): with open(path) as f: loc_sigs, loc_class_sigs = parse_all_signatures(f.readlines()) all_sigs += loc_sigs @@ -1610,9 +1610,9 @@ def generate_stubs(options: Options) -> None: if not options.quiet and num_modules > 0: print('Processed %d modules' % num_modules) if len(files) == 1: - print('Generated %s' % files[0]) + print(f'Generated {files[0]}') else: - print('Generated files under %s' % common_dir_prefix(files) + os.sep) + print(f'Generated files under {common_dir_prefix(files)}' + os.sep) HEADER = """%(prog)s [-h] [--py2] [more options, see -h] diff --git a/mypy/stubgenc.py b/mypy/stubgenc.py index e9fa0ef62bb2..682ed418ffc7 100755 --- a/mypy/stubgenc.py +++ b/mypy/stubgenc.py @@ -47,7 +47,7 @@ def generate_stub_for_c_module(module_name: str, will be overwritten. """ module = importlib.import_module(module_name) - assert is_c_module(module), '%s is not a C module' % module_name + assert is_c_module(module), f'{module_name} is not a C module' subdir = os.path.dirname(target) if subdir and not os.path.isdir(subdir): os.makedirs(subdir) @@ -90,7 +90,7 @@ def generate_stub_for_c_module(module_name: str, output = add_typing_import(output) with open(target, 'w') as file: for line in output: - file.write('%s\n' % line) + file.write(f'{line}\n') def add_typing_import(output: List[str]) -> List[str]: @@ -100,7 +100,7 @@ def add_typing_import(output: List[str]) -> List[str]: if any(re.search(r'\b%s\b' % name, line) for line in output): names.append(name) if names: - return ['from typing import %s' % ', '.join(names), ''] + output + return [f"from typing import {', '.join(names)}", ''] + output else: return output[:] @@ -405,19 +405,19 @@ def generate_c_type_stub(module: ModuleType, output.append('') output.append(' ' + line) for line in static_properties: - output.append(' %s' % line) + output.append(f' {line}') for line in rw_properties: - output.append(' %s' % line) + output.append(f' {line}') for line in methods: - output.append(' %s' % line) + output.append(f' {line}') for line in ro_properties: - output.append(' %s' % line) + output.append(f' {line}') else: output.append(f'class {class_name}{bases_str}: ...') def get_type_fullname(typ: type) -> str: - return '{}.{}'.format(typ.__module__, getattr(typ, '__qualname__', typ.__name__)) + return f"{typ.__module__}.{getattr(typ, '__qualname__', typ.__name__)}" def method_name_sort_key(name: str) -> Tuple[int, str]: diff --git a/mypy/stubutil.py b/mypy/stubutil.py index 8ed73cab203b..55f8c0b29345 100644 --- a/mypy/stubutil.py +++ b/mypy/stubutil.py @@ -54,10 +54,10 @@ def walk_packages(inspect: ModuleInspect, """ for package_name in packages: if package_name in NOT_IMPORTABLE_MODULES: - print('%s: Skipped (blacklisted)' % package_name) + print(f'{package_name}: Skipped (blacklisted)') continue if verbose: - print('Trying to import %r for runtime introspection' % package_name) + print(f'Trying to import {package_name!r} for runtime introspection') try: prop = inspect.get_package_properties(package_name) except InspectError: @@ -144,7 +144,7 @@ def find_module_path_and_all_py3(inspect: ModuleInspect, # TODO: Support custom interpreters. if verbose: - print('Trying to import %r for runtime introspection' % module) + print(f'Trying to import {module!r} for runtime introspection') try: mod = inspect.get_package_properties(module) except InspectError as e: @@ -166,7 +166,7 @@ def generate_guarded(mod: str, target: str, Optionally report success. """ if verbose: - print('Processing %s' % mod) + print(f'Processing {mod}') try: yield except Exception as e: @@ -177,7 +177,7 @@ def generate_guarded(mod: str, target: str, print("Stub generation failed for", mod, file=sys.stderr) else: if verbose: - print('Created %s' % target) + print(f'Created {target}') PY2_MODULES = {'cStringIO', 'urlparse', 'collections.UserDict'} diff --git a/mypy/suggestions.py b/mypy/suggestions.py index fbbf00118e82..d311d0edde63 100644 --- a/mypy/suggestions.py +++ b/mypy/suggestions.py @@ -485,7 +485,7 @@ def format_args(self, if name: arg = f"{name}={arg}" args.append(arg) - return "(%s)" % (", ".join(args)) + return f"({', '.join(args)})" def find_node(self, key: str) -> Tuple[str, str, FuncDef]: """From a target name, return module/target names and the func def. @@ -518,10 +518,10 @@ def find_node(self, key: str) -> Tuple[str, str, FuncDef]: if isinstance(node, Decorator): node = self.extract_from_decorator(node) if not node: - raise SuggestionFailure("Object %s is a decorator we can't handle" % key) + raise SuggestionFailure(f"Object {key} is a decorator we can't handle") if not isinstance(node, FuncDef): - raise SuggestionFailure("Object %s is not a function" % key) + raise SuggestionFailure(f"Object {key} is not a function") return modname, tail, node @@ -686,10 +686,7 @@ def pyannotate_signature( def format_signature(self, sig: PyAnnotateSignature) -> str: """Format a callable type in a way suitable as an annotation... kind of""" - return "({}) -> {}".format( - ", ".join(sig['arg_types']), - sig['return_type'] - ) + return f"({', '.join(sig['arg_types'])}) -> {sig['return_type']}" def format_type(self, cur_module: Optional[str], typ: Type) -> str: if self.use_fixme and isinstance(get_proper_type(typ), AnyType): @@ -843,7 +840,7 @@ def visit_callable_type(self, t: CallableType) -> str: # other thing, and I suspect this will produce more better # results than falling back to `...` args = [typ.accept(self) for typ in t.arg_types] - arg_str = "[{}]".format(", ".join(args)) + arg_str = f"[{', '.join(args)}]" return f"Callable[{arg_str}, {t.ret_type.accept(self)}]" diff --git a/mypy/test/data.py b/mypy/test/data.py index 9f1c6a1aa24c..de7e38693f23 100644 --- a/mypy/test/data.py +++ b/mypy/test/data.py @@ -162,13 +162,11 @@ def parse_test_case(case: 'DataDrivenTestCase') -> None: triggered = item.data else: raise ValueError( - 'Invalid section header {} in {} at line {}'.format( - item.id, case.file, item.line)) + f'Invalid section header {item.id} in {case.file} at line {item.line}') if out_section_missing: raise ValueError( - '{}, line {}: Required output section not found'.format( - case.file, first_item.line)) + f'{case.file}, line {first_item.line}: Required output section not found') for passnum in stale_modules.keys(): if passnum not in rechecked_modules: @@ -500,8 +498,7 @@ def expand_errors(input: List[str], output: List[str], fnam: str) -> None: output.append( f'{fnam}:{i + 1}: {severity}: {message}') else: - output.append('{}:{}:{}: {}: {}'.format( - fnam, i + 1, col, severity, message)) + output.append(f'{fnam}:{i + 1}:{col}: {severity}: {message}') def fix_win_path(line: str) -> str: diff --git a/mypy/test/testcheck.py b/mypy/test/testcheck.py index 2f74e543d469..f0dc4bc6a671 100644 --- a/mypy/test/testcheck.py +++ b/mypy/test/testcheck.py @@ -346,7 +346,7 @@ def parse_module(self, cache = FindModuleCache(search_paths, fscache=None, options=None) for module_name in module_names.split(' '): path = cache.find_module(module_name) - assert isinstance(path, str), "Can't find ad hoc case file: %s" % module_name + assert isinstance(path, str), f"Can't find ad hoc case file: {module_name}" with open(path, encoding='utf8') as f: program_text = f.read() out.append((module_name, path, program_text)) diff --git a/mypy/test/testdeps.py b/mypy/test/testdeps.py index d3d184be7f01..7446d44339a0 100644 --- a/mypy/test/testdeps.py +++ b/mypy/test/testdeps.py @@ -67,15 +67,14 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: if source.startswith((' {', '.join(sorted(targets))}" # Clean up output a bit line = line.replace('__main__', 'm') a.append(line) assert_string_arrays_equal( testcase.output, a, - 'Invalid output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid output ({testcase.file}, line {testcase.line})') def build(self, source: str, diff --git a/mypy/test/testdiff.py b/mypy/test/testdiff.py index 9e1e9097152b..56f4564e91d3 100644 --- a/mypy/test/testdiff.py +++ b/mypy/test/testdiff.py @@ -47,8 +47,7 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: assert_string_arrays_equal( testcase.output, a, - 'Invalid output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid output ({testcase.file}, line {testcase.line})') def build(self, source: str, options: Options) -> Tuple[List[str], Optional[Dict[str, MypyFile]]]: diff --git a/mypy/test/testfinegrained.py b/mypy/test/testfinegrained.py index 9fbfdc4395fe..783e21e2869e 100644 --- a/mypy/test/testfinegrained.py +++ b/mypy/test/testfinegrained.py @@ -130,15 +130,13 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: assert_string_arrays_equal( testcase.output, a, - 'Invalid output ({}, line {})'.format( - testcase.file, testcase.line)) + f'Invalid output ({testcase.file}, line {testcase.line})') if testcase.triggered: assert_string_arrays_equal( testcase.triggered, self.format_triggered(all_triggered), - 'Invalid active triggers ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid active triggers ({testcase.file}, line {testcase.line})') def get_options(self, source: str, diff --git a/mypy/test/testmerge.py b/mypy/test/testmerge.py index 2e2f6b67d34a..fe0de2a7fe2d 100644 --- a/mypy/test/testmerge.py +++ b/mypy/test/testmerge.py @@ -98,8 +98,7 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: assert_string_arrays_equal( testcase.output, a, - 'Invalid output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid output ({testcase.file}, line {testcase.line})') def build(self, source: str, testcase: DataDrivenTestCase) -> Optional[BuildResult]: options = parse_options(source, testcase, incremental_step=1) @@ -142,7 +141,7 @@ def dump(self, return self.dump_symbol_tables(modules) elif kind == TYPES: return self.dump_types(manager) - assert False, 'Invalid kind %s' % kind + assert False, f'Invalid kind {kind}' def dump_asts(self, modules: Dict[str, MypyFile]) -> List[str]: a = [] @@ -177,8 +176,7 @@ def format_symbol_table_node(self, node: SymbolTableNode) -> str: return 'UNBOUND_IMPORTED' return 'None' if isinstance(node.node, Node): - s = '{}<{}>'.format(str(type(node.node).__name__), - self.id_mapper.id(node.node)) + s = f'{str(type(node.node).__name__)}<{self.id_mapper.id(node.node)}>' else: s = f'? ({type(node.node)})' if (isinstance(node.node, Var) and node.node.type and @@ -230,9 +228,7 @@ def dump_types(self, manager: FineGrainedBuildManager) -> List[str]: for expr in sorted(type_map, key=lambda n: (n.line, short_type(n), str(n) + str(type_map[n]))): typ = type_map[expr] - a.append('{}:{}: {}'.format(short_type(expr), - expr.line, - self.format_type(typ))) + a.append(f'{short_type(expr)}:{expr.line}: {self.format_type(typ)}') return a def format_type(self, typ: Type) -> str: diff --git a/mypy/test/testparse.py b/mypy/test/testparse.py index 1587147c0777..340d6b904476 100644 --- a/mypy/test/testparse.py +++ b/mypy/test/testparse.py @@ -83,5 +83,4 @@ def test_parse_error(testcase: DataDrivenTestCase) -> None: # are equivalent. assert_string_arrays_equal( testcase.output, e.messages, - 'Invalid compiler output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid compiler output ({testcase.file}, line {testcase.line})') diff --git a/mypy/test/testpythoneval.py b/mypy/test/testpythoneval.py index 8002b7410ee8..770738294755 100644 --- a/mypy/test/testpythoneval.py +++ b/mypy/test/testpythoneval.py @@ -70,7 +70,7 @@ def test_python_evaluation(testcase: DataDrivenTestCase, cache_dir: str) -> None return else: interpreter = python3_path - mypy_cmdline.append('--python-version={}'.format('.'.join(map(str, PYTHON3_VERSION)))) + mypy_cmdline.append(f"--python-version={'.'.join(map(str, PYTHON3_VERSION))}") m = re.search('# flags: (.*)$', '\n'.join(testcase.input), re.MULTILINE) if m: diff --git a/mypy/test/testsemanal.py b/mypy/test/testsemanal.py index a58dc4a3960a..c7a623507ac1 100644 --- a/mypy/test/testsemanal.py +++ b/mypy/test/testsemanal.py @@ -102,8 +102,7 @@ def test_semanal(testcase: DataDrivenTestCase) -> None: a = normalize_error_messages(a) assert_string_arrays_equal( testcase.output, a, - 'Invalid semantic analyzer output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid semantic analyzer output ({testcase.file}, line {testcase.line})') # Semantic analyzer error test cases @@ -165,8 +164,7 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: a = e.messages assert_string_arrays_equal( testcase.output, a, - 'Invalid semantic analyzer output ({}, line {})'.format( - testcase.file, testcase.line)) + f'Invalid semantic analyzer output ({testcase.file}, line {testcase.line})') # Type info export test cases @@ -200,8 +198,7 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: a = e.messages assert_string_arrays_equal( testcase.output, a, - 'Invalid semantic analyzer output ({}, line {})'.format( - testcase.file, testcase.line)) + f'Invalid semantic analyzer output ({testcase.file}, line {testcase.line})') class TypeInfoMap(Dict[str, TypeInfo]): diff --git a/mypy/test/teststubgen.py b/mypy/test/teststubgen.py index 97e3d98597cb..3c2b2967fb3c 100644 --- a/mypy/test/teststubgen.py +++ b/mypy/test/teststubgen.py @@ -662,11 +662,11 @@ def test_infer_setitem_sig(self) -> None: def test_infer_binary_op_sig(self) -> None: for op in ('eq', 'ne', 'lt', 'le', 'gt', 'ge', 'add', 'radd', 'sub', 'rsub', 'mul', 'rmul'): - assert_equal(infer_method_sig('__%s__' % op), [self_arg, ArgSig(name='other')]) + assert_equal(infer_method_sig(f'__{op}__'), [self_arg, ArgSig(name='other')]) def test_infer_unary_op_sig(self) -> None: for op in ('neg', 'pos'): - assert_equal(infer_method_sig('__%s__' % op), [self_arg]) + assert_equal(infer_method_sig(f'__{op}__'), [self_arg]) def test_generate_c_type_stub_no_crash_for_object(self) -> None: output: List[str] = [] @@ -1074,7 +1074,7 @@ def test_non_existent(self) -> None: def module_to_path(out_dir: str, module: str) -> str: - fnam = os.path.join(out_dir, '{}.pyi'.format(module.replace('.', '/'))) + fnam = os.path.join(out_dir, f"{module.replace('.', '/')}.pyi") if not os.path.exists(fnam): alt_fnam = fnam.replace('.pyi', '/__init__.pyi') if os.path.exists(alt_fnam): diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index a17edbea24aa..de48c9ce2723 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -1167,8 +1167,7 @@ def test_config_file(self) -> None: runtime = "temp = 5\n" stub = "from decimal import Decimal\ntemp: Decimal\n" config_file = ( - "[mypy]\n" - "plugins={}/test-data/unit/plugins/decimal_to_int.py\n".format(root_dir) + f"[mypy]\nplugins={root_dir}/test-data/unit/plugins/decimal_to_int.py\n" ) output = run_stubtest(stub=stub, runtime=runtime, options=[]) assert remove_color_code(output) == ( diff --git a/mypy/test/testtransform.py b/mypy/test/testtransform.py index e1e3b6ab63ed..bd400b254ff4 100644 --- a/mypy/test/testtransform.py +++ b/mypy/test/testtransform.py @@ -72,5 +72,4 @@ def test_transform(testcase: DataDrivenTestCase) -> None: a = normalize_error_messages(a) assert_string_arrays_equal( testcase.output, a, - 'Invalid semantic analyzer output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid semantic analyzer output ({testcase.file}, line {testcase.line})') diff --git a/mypy/test/testtypegen.py b/mypy/test/testtypegen.py index c652b38ba6fe..a91cd0a2972d 100644 --- a/mypy/test/testtypegen.py +++ b/mypy/test/testtypegen.py @@ -68,5 +68,4 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: a = e.messages assert_string_arrays_equal( testcase.output, a, - 'Invalid type checker output ({}, line {})'.format(testcase.file, - testcase.line)) + f'Invalid type checker output ({testcase.file}, line {testcase.line})') diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 536e170a9644..d734a1cc330f 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -94,7 +94,8 @@ def analyze_type_alias(node: Expression, def no_subscript_builtin_alias(name: str, propose_alt: bool = True) -> str: - msg = '"{}" is not subscriptable'.format(name.split('.')[-1]) + class_name = name.split('.')[-1] + msg = f'"{class_name}" is not subscriptable' # This should never be called if the python_version is 3.9 or newer nongen_builtins = get_nongen_builtins((3, 8)) replacement = nongen_builtins[name] @@ -971,8 +972,7 @@ def analyze_callable_args(self, arglist: TypeList) -> Optional[Tuple[List[Type], # Looking it up already put an error message in return None elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR: - self.fail('Invalid argument constructor "{}"'.format( - found.fullname), arg) + self.fail(f'Invalid argument constructor "{found.fullname}"', arg) return None else: assert found.fullname is not None @@ -1322,8 +1322,7 @@ def fix_instance(t: Instance, fail: MsgCallback, note: MsgCallback, act = str(len(t.args)) if act == '0': act = 'none' - fail('"{}" expects {}, but {} given'.format( - t.type.name, s, act), t, code=codes.TYPE_ARG) + fail(f'"{t.type.name}" expects {s}, but {act} given', t, code=codes.TYPE_ARG) # Construct the correct number of type arguments, as # otherwise the type checker may crash as it expects # things to be right. diff --git a/mypy/types.py b/mypy/types.py index a958e6c67dcc..8f45e87b8fb9 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -2754,7 +2754,7 @@ def visit_callable_type(self, t: CallableType) -> str: if isinstance(var, TypeVarType): # We reimplement TypeVarType.__repr__ here in order to support id_mapper. if var.values: - vals = '({})'.format(', '.join(val.accept(self) for val in var.values)) + vals = f"({', '.join(val.accept(self) for val in var.values)})" vs.append(f'{var.name} in {vals}') elif not is_named_instance(var.upper_bound, 'builtins.object'): vs.append(f'{var.name} <: {var.upper_bound.accept(self)}') @@ -2763,7 +2763,7 @@ def visit_callable_type(self, t: CallableType) -> str: else: # For other TypeVarLikeTypes, just use the name vs.append(var.name) - s = '{} {}'.format('[{}]'.format(', '.join(vs)), s) + s = f"[{', '.join(vs)}] {s}" return f'def {s}' @@ -2771,7 +2771,7 @@ def visit_overloaded(self, t: Overloaded) -> str: a = [] for i in t.items: a.append(i.accept(self)) - return 'Overload({})'.format(', '.join(a)) + return f"Overload({', '.join(a)})" def visit_tuple_type(self, t: TupleType) -> str: s = self.list_str(t.items) diff --git a/mypy/util.py b/mypy/util.py index 1a3628458c48..c207fb7e18cd 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -743,7 +743,7 @@ def format_error( if blockers: msg += ' (errors prevented further checking)' else: - msg += ' (checked {} source file{})'.format(n_sources, 's' if n_sources != 1 else '') + msg += f" (checked {n_sources} source file{'s' if n_sources != 1 else ''})" if not use_color: return msg return self.style(msg, 'red', bold=True)