diff options
| author | Timothy Crosley <timothy.crosley@gmail.com> | 2019-10-27 23:39:46 -0700 |
|---|---|---|
| committer | Timothy Crosley <timothy.crosley@gmail.com> | 2019-10-27 23:39:46 -0700 |
| commit | 03a3dd7b196e696ae60bb2cdf9eeb57fa3b9b863 (patch) | |
| tree | ce29e4693821ada144fef16d3ce166a7b44105b8 | |
| parent | e782b36a80c58d240c62d405969c359fe6da1906 (diff) | |
| download | isort-03a3dd7b196e696ae60bb2cdf9eeb57fa3b9b863.tar.gz | |
Switch from .format to f-string; switch from print to warnings where applicable
| -rw-r--r-- | isort/comments.py | 2 | ||||
| -rw-r--r-- | isort/compat.py | 26 | ||||
| -rw-r--r-- | isort/finders.py | 25 | ||||
| -rw-r--r-- | isort/format.py | 6 | ||||
| -rw-r--r-- | isort/isort.py | 4 | ||||
| -rw-r--r-- | isort/logo.py | 16 | ||||
| -rw-r--r-- | isort/main.py | 23 | ||||
| -rw-r--r-- | isort/output.py | 32 | ||||
| -rw-r--r-- | isort/parse.py | 20 | ||||
| -rw-r--r-- | isort/settings.py | 7 | ||||
| -rw-r--r-- | isort/sorting.py | 10 | ||||
| -rw-r--r-- | isort/wrap.py | 36 | ||||
| -rw-r--r-- | isort/wrap_modes.py | 90 | ||||
| -rwxr-xr-x | scripts/lint.sh | 2 | ||||
| -rwxr-xr-x | scripts/mkstdlibs.py | 10 | ||||
| -rw-r--r-- | tests/test_isort.py | 8 |
16 files changed, 149 insertions, 168 deletions
diff --git a/isort/comments.py b/isort/comments.py index 92642864..d033804d 100644 --- a/isort/comments.py +++ b/isort/comments.py @@ -25,4 +25,4 @@ def add_to_line( if not comments: return original_string else: - return "{}{} {}".format(parse(original_string)[0], comment_prefix, "; ".join(comments)) + return f"{parse(original_string)[0]}{comment_prefix} {'; '.join(comments)}" diff --git a/isort/compat.py b/isort/compat.py index ccc71c11..a85dc66b 100644 --- a/isort/compat.py +++ b/isort/compat.py @@ -4,6 +4,7 @@ import re import sys from pathlib import Path from typing import Any, Optional, Tuple +from warnings import warn from isort import settings from isort.format import ask_whether_to_apply_changes_to_file, show_unified_diff @@ -78,7 +79,7 @@ class SortImports: run_path: str = "", check_skip: bool = True, extension: Optional[str] = None, - **setting_overrides: Any + **setting_overrides: Any, ): file_path = None if file_path is None else Path(file_path) file_name = None @@ -107,9 +108,9 @@ class SortImports: if settings.file_should_be_skipped(file_name, self.config, run_path): self.skipped = True if self.config["verbose"]: - print( - "WARNING: {} was skipped as it's listed in 'skip' setting" - " or matches a glob in 'skip_glob' setting".format(absolute_file_path) + warn( + f"{absolute_file_path} was skipped as it's listed in 'skip' setting" + " or matches a glob in 'skip_glob' setting" ) file_contents = None @@ -127,11 +128,10 @@ class SortImports: if used_encoding is None: self.skipped = True if self.config["verbose"]: - print( - "WARNING: {} was skipped as it couldn't be opened with the given " - "{} encoding or {} fallback encoding".format( - str(absolute_file_path), file_encoding, fallback_encoding - ) + warn( + f"{absolute_file_path} was skipped as it couldn't be opened with the " + f"given {file_encoding} encoding or {fallback_encoding} fallback " + "encoding" ) else: file_encoding = used_encoding @@ -166,11 +166,11 @@ class SortImports: ) compile(in_lines_without_top_comment, logging_file_path, "exec", 0, 1) print( - "ERROR: {} isort would have introduced syntax errors, " - "please report to the project!".format(logging_file_path) + f"ERROR: {logging_file_path} isort would have introduced syntax errors, " + "please report to the project!" ) except SyntaxError: - print("ERROR: {} File contains syntax errors.".format(logging_file_path)) + print(f"ERROR: {logging_file_path} File contains syntax errors.") return @@ -212,7 +212,7 @@ class SortImports: with self.file_path.open("w", encoding=file_encoding, newline="") as output_file: if not self.config["quiet"]: - print("Fixing {}".format(self.file_path)) + print(f"Fixing {self.file_path}") output_file.write(self.output) diff --git a/isort/finders.py b/isort/finders.py index b8e6c8f6..7aa53052 100644 --- a/isort/finders.py +++ b/isort/finders.py @@ -86,7 +86,7 @@ class KnownPatternFinder(BaseFinder): self.known_patterns: List[Tuple[Pattern[str], str]] = [] for placement in reversed(self.sections): known_placement = KNOWN_SECTION_MAPPING.get(placement, placement) - config_key = "known_{}".format(known_placement.lower()) + config_key = f"known_{known_placement.lower()}" known_patterns = self.config.get(config_key, []) known_patterns = [ pattern @@ -129,7 +129,7 @@ class PathFinder(BaseFinder): # restore the original import path (i.e. not the path to bin/isort) root_dir = os.getcwd() - src_dir = "{0}/src".format(root_dir) + src_dir = f"{root_dir}/src" self.paths = [root_dir, src_dir] # virtual env @@ -138,14 +138,14 @@ class PathFinder(BaseFinder): self.virtual_env = os.path.realpath(self.virtual_env) self.virtual_env_src = "" if self.virtual_env: - self.virtual_env_src = "{}/src/".format(self.virtual_env) - for path in glob("{}/lib/python*/site-packages".format(self.virtual_env)): + self.virtual_env_src = f"{self.virtual_env}/src/" + for path in glob(f"{self.virtual_env}/lib/python*/site-packages"): if path not in self.paths: self.paths.append(path) - for path in glob("{}/lib/python*/*/site-packages".format(self.virtual_env)): + for path in glob(f"{self.virtual_env}/lib/python*/*/site-packages"): if path not in self.paths: self.paths.append(path) - for path in glob("{}/src/*".format(self.virtual_env)): + for path in glob(f"{self.virtual_env}/src/*"): if os.path.isdir(path): self.paths.append(path) @@ -153,10 +153,10 @@ class PathFinder(BaseFinder): self.conda_env = self.config.get("conda_env") or os.environ.get("CONDA_PREFIX") or "" if self.conda_env: self.conda_env = os.path.realpath(self.conda_env) - for path in glob("{}/lib/python*/site-packages".format(self.conda_env)): + for path in glob(f"{self.conda_env}/lib/python*/site-packages"): if path not in self.paths: self.paths.append(path) - for path in glob("{}/lib/python*/*/site-packages".format(self.conda_env)): + for path in glob(f"{self.conda_env}/lib/python*/*/site-packages"): if path not in self.paths: self.paths.append(path) @@ -396,9 +396,9 @@ class FindersManager: if self.verbose: print( ( - "{} encountered an error ({}) during " + f"{finder_cls.__name__} encountered an error ({exception}) during " "instantiation and cannot be used" - ).format(finder_cls.__name__, str(exception)) + ) ) self.finders: Tuple[BaseFinder, ...] = tuple(finders) @@ -411,9 +411,8 @@ class FindersManager: # import section even if one approach fails if self.verbose: print( - ( - "{} encountered an error ({}) while trying to identify the {}" " module" - ).format(finder.__class__.__name__, str(exception), module_name) + f"{finder.__class__.__name__} encountered an error ({exception}) while " + f"trying to identify the {module_name} module" ) if section is not None: return section diff --git a/isort/format.py b/isort/format.py index 8dd7a5ee..80a215e4 100644 --- a/isort/format.py +++ b/isort/format.py @@ -20,10 +20,10 @@ def format_natural(import_line: str) -> str: import_line = import_line.strip() if not import_line.startswith("from ") and not import_line.startswith("import "): if "." not in import_line: - return "import {}".format(import_line) + return f"import {import_line}" parts = import_line.split(".") end = parts.pop(-1) - return "from {} import {}".format(".".join(parts), end) + return f"from {'.'.join(parts)} import {end}" return import_line @@ -49,7 +49,7 @@ def show_unified_diff(*, file_input: str, file_output: str, file_path: Optional[ def ask_whether_to_apply_changes_to_file(file_path: str) -> bool: answer = None while answer not in ("yes", "y", "no", "n", "quit", "q"): - answer = input("Apply suggested changes to '{}' [y/n/q]? ".format(file_path)) # nosec + answer = input(f"Apply suggested changes to '{file_path}' [y/n/q]? ") # nosec answer = answer.lower() if answer in ("no", "n"): return False diff --git a/isort/isort.py b/isort/isort.py index f8e434cb..0a532410 100644 --- a/isort/isort.py +++ b/isort/isort.py @@ -50,10 +50,10 @@ class _SortImports: ) -> bool: if output.strip() == check_against.strip(): if self.config["verbose"]: - print("SUCCESS: {} Everything Looks Good!".format(logging_file_path)) + print(f"SUCCESS: {logging_file_path} Everything Looks Good!") return True - print("ERROR: {} Imports are incorrectly sorted.".format(logging_file_path)) + print(f"ERROR: {logging_file_path} Imports are incorrectly sorted.") return False @staticmethod diff --git a/isort/logo.py b/isort/logo.py index ea85bff6..0c008062 100644 --- a/isort/logo.py +++ b/isort/logo.py @@ -1,6 +1,6 @@ from ._version import __version__ -ASCII_ART = r""" +ASCII_ART = rf""" /#######################################################################\ `sMMy` @@ -18,17 +18,13 @@ ASCII_ART = r""" isort your Python imports for you so you don't have to - VERSION {} + VERSION {__version__} \########################################################################/ -""".format( - __version__ -) +""" -__doc__ = """ +__doc__ = f""" ```python -{} +{ASCII_ART} ``` -""".format( - ASCII_ART -) +""" diff --git a/isort/main.py b/isort/main.py index e21be75a..ea8e7388 100644 --- a/isort/main.py +++ b/isort/main.py @@ -6,6 +6,7 @@ import os import re import sys from typing import Any, Dict, Iterable, Iterator, List, MutableMapping, Optional, Sequence +from warnings import warn import setuptools @@ -53,8 +54,8 @@ def sort_imports(file_name: str, **arguments: Any) -> Optional[SortAttempt]: try: result = SortImports(file_name, **arguments) return SortAttempt(result.incorrectly_sorted, result.skipped) - except OSError as e: - print("WARNING: Unable to parse file {} due to {}".format(file_name, e)) + except OSError as error: + warn(f"Unable to parse file {file_name} due to {error}") return None @@ -133,8 +134,8 @@ class ISortCommand(setuptools.Command): incorrectly_sorted = SortImports(python_file, **arguments).incorrectly_sorted if incorrectly_sorted: wrong_sorted_files = True - except OSError as e: - print("WARNING: Unable to parse file {} due to {}".format(python_file, e)) + except OSError as error: + print(f"WARNING: Unable to parse file {python_file} due to {error}") if wrong_sorted_files: sys.exit(1) @@ -571,15 +572,13 @@ def main(argv: Optional[Sequence[str]] = None) -> None: os.path.abspath(sp) if os.path.isdir(sp) else os.path.dirname(os.path.abspath(sp)) ) if not os.path.isdir(arguments["settings_path"]): - print( - "WARNING: settings_path dir does not exist: {}".format(arguments["settings_path"]) - ) + warn(f"settings_path dir does not exist: {arguments['settings_path']}") if "virtual_env" in arguments: venv = arguments["virtual_env"] arguments["virtual_env"] = os.path.abspath(venv) if not os.path.isdir(arguments["virtual_env"]): - print("WARNING: virtual_env dir does not exist: {}".format(arguments["virtual_env"])) + warn(f"virtual_env dir does not exist: {arguments['virtual_env']}") file_names = arguments.pop("files", []) if file_names == ["-"]: @@ -643,11 +642,11 @@ def main(argv: Optional[Sequence[str]] = None) -> None: if num_skipped and not arguments.get("quiet", False): if config["verbose"]: for was_skipped in skipped: - print( - "WARNING: {} was skipped as it's listed in 'skip' setting" - " or matches a glob in 'skip_glob' setting".format(was_skipped) + warn( + f"{was_skipped} was skipped as it's listed in 'skip' setting" + " or matches a glob in 'skip_glob' setting" ) - print("Skipped {} files".format(num_skipped)) + print(f"Skipped {num_skipped} files") if __name__ == "__main__": diff --git a/isort/output.py b/isort/output.py index f7753e4f..31ce6ad0 100644 --- a/isort/output.py +++ b/isort/output.py @@ -116,7 +116,7 @@ def sorted_imports( section_title = config.get("import_heading_" + str(section_name).lower(), "") if section_title: - section_comment = "# {}".format(section_title) + section_comment = f"# {section_title}" if ( section_comment not in parsed.lines_without_imports[0:1] and section_comment not in parsed.in_lines[0:1] @@ -225,7 +225,7 @@ def _with_from_imports( if module in remove_imports: continue - import_start = "from {} import ".format(module) + import_start = f"from {module} import " from_imports = list(parsed.imports[section]["from"][module]) if not config["no_inline_sort"] or config["force_single_line"]: from_imports = sorting.naturally( @@ -236,13 +236,13 @@ def _with_from_imports( ) if remove_imports: from_imports = [ - line for line in from_imports if not "{}.{}".format(module, line) in remove_imports + line for line in from_imports if f"{module}.{line}" not in remove_imports ] - sub_modules = ["{}.{}".format(module, from_import) for from_import in from_imports] + sub_modules = [f"{module}.{from_import}" for from_import in from_imports] as_imports = { from_import: [ - "{} as {}".format(from_import, as_module) for as_module in parsed.as_map[sub_module] + f"{from_import} as {as_module}" for as_module in parsed.as_map[sub_module] ] for from_import, sub_module in zip(from_imports, sub_modules) if sub_module in parsed.as_map @@ -268,7 +268,7 @@ def _with_from_imports( import_statement = wrap.line( with_comments( comments, - "{}*".format(import_start), + f"{import_start}*", removed=config["ignore_comments"], comment_prefix=config["comment_prefix"], ), @@ -290,8 +290,8 @@ def _with_from_imports( parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None) ) if comment: - single_import_line += "{} {}".format( - comments and ";" or config["comment_prefix"], comment + single_import_line += ( + f"{comments and ';' or config['comment_prefix']} " f"{comment}" ) if from_import in as_imports: if ( @@ -302,7 +302,7 @@ def _with_from_imports( wrap.line(single_import_line, parsed.line_separator, config) ) from_comments = parsed.categorized_comments["straight"].get( - "{}.{}".format(module, from_import) + f"{module}.{from_import}" ) new_section_output.extend( with_comments( @@ -323,7 +323,7 @@ def _with_from_imports( from_import = from_imports.pop(0) as_imports[from_import] = sorting.naturally(as_imports[from_import]) from_comments = parsed.categorized_comments["straight"].get( - "{}.{}".format(module, from_import) + f"{module}.{from_import}" ) above_comments = parsed.categorized_comments["above"]["from"].pop(module, None) if above_comments: @@ -360,7 +360,7 @@ def _with_from_imports( new_section_output.append( with_comments( comments, - "{}*".format(import_start), + f"{import_start}*", removed=config["ignore_comments"], comment_prefix=config["comment_prefix"], ) @@ -382,8 +382,8 @@ def _with_from_imports( removed=config["ignore_comments"], comment_prefix=config["comment_prefix"], ) - single_import_line += "{} {}".format( - comments and ";" or config["comment_prefix"], comment + single_import_line += ( + f"{comments and ';' or config['comment_prefix']} " f"{comment}" ) above_comments = parsed.categorized_comments["above"]["from"].pop( module, None @@ -491,12 +491,12 @@ def _with_straight_imports( import_definition = [] if module in parsed.as_map: if config["keep_direct_and_as_imports"] and parsed.imports[section]["straight"][module]: - import_definition.append("import {}".format(module)) + import_definition.append(f"import {module}") import_definition.extend( - "import {} as {}".format(module, as_import) for as_import in parsed.as_map[module] + f"import {module} as {as_import}" for as_import in parsed.as_map[module] ) else: - import_definition.append("import {}".format(module)) + import_definition.append(f"import {module}") comments_above = parsed.categorized_comments["above"]["straight"].pop(module, None) if comments_above: diff --git a/isort/parse.py b/isort/parse.py index 3c88524b..659a5117 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -339,15 +339,11 @@ def file_contents(contents: str, config: Dict[str, Any]) -> ParsedContent: import_from = just_imports.pop(0) placed_module = finder.find(import_from) if config["verbose"]: - print( - "from-type place_module for {} returned {}".format( - import_from, placed_module - ) - ) + print(f"from-type place_module for {import_from} returned {placed_module}") if placed_module == "": warn( - "could not place module {} of line {} --" - " Do you need to define a default section?".format(import_from, line) + f"could not place module {import_from} of line {line} --" + " Do you need to define a default section?" ) root = imports[placed_module][type_of_import] # type: ignore for import_name in just_imports: @@ -420,15 +416,11 @@ def file_contents(contents: str, config: Dict[str, Any]) -> ParsedContent: ) placed_module = finder.find(module) if config["verbose"]: - print( - "else-type place_module for {} returned {}".format( - module, placed_module - ) - ) + print(f"else-type place_module for {module} returned {placed_module}") if placed_module == "": warn( - "could not place module {} of line {} --" - " Do you need to define a default section?".format(import_from, line) + f"could not place module {import_from} of line {line} --" + " Do you need to define a default section?" ) straight_import |= imports[placed_module][type_of_import].get( # type: ignore module, False diff --git a/isort/settings.py b/isort/settings.py index 7997aa38..6479fc6a 100644 --- a/isort/settings.py +++ b/isort/settings.py @@ -340,10 +340,9 @@ def _get_config_data(file_path: str, sections: Iterable[str]) -> Dict[str, Any]: else: if "[tool.isort]" in config_file.read(): warnings.warn( - "Found {} with [tool.isort] section, but toml package is not installed. " - "To configure isort with {}, install with 'isort[pyproject]'.".format( - file_path, file_path - ) + f"Found {file_path} with [tool.isort] section, but toml package is not " + f"installed. To configure isort with {file_path}, install with " + "'isort[pyproject]'." ) else: if file_path.endswith(".editorconfig"): diff --git a/isort/sorting.py b/isort/sorting.py index b76527bc..591d3d93 100644 --- a/isort/sorting.py +++ b/isort/sorting.py @@ -36,11 +36,9 @@ def module_key( length_sort = config["length_sort"] else: length_sort = config["length_sort_" + str(section_name).lower()] - return "{}{}{}".format( - module_name in config["force_to_top"] and "A" or "B", - prefix, - length_sort and (str(len(module_name)) + ":" + module_name) or module_name, - ) + + _length_sort_maybe = length_sort and (str(len(module_name)) + ":" + module_name) or module_name + return f"{module_name in config['force_to_top'] and 'A' or 'B'}{prefix}{_length_sort_maybe}" def section_key(line: str, order_by_type: bool, force_to_top: List[str]) -> str: @@ -51,7 +49,7 @@ def section_key(line: str, order_by_type: bool, force_to_top: List[str]) -> str: section = "A" if not order_by_type: line = line.lower() - return "{}{}".format(section, line) + return f"{section}{line}" def naturally(to_sort: Iterable[str], key: Optional[Callable[[str], Any]] = None) -> List[str]: diff --git a/isort/wrap.py b/isort/wrap.py index b8877116..7980dfd4 100644 --- a/isort/wrap.py +++ b/isort/wrap.py @@ -74,11 +74,8 @@ def line(line: str, line_separator: str, config: Dict[str, Any]) -> str: ): line_parts = re.split(exp, line_without_comment) if comment: - line_parts[-1] = "{}{} #{}".format( - line_parts[-1].strip(), - "," if config["include_trailing_comma"] else "", - comment, - ) + _comma_maybe = "," if config["include_trailing_comma"] else "" + line_parts[-1] = f"{line_parts[-1].strip()}{_comma_maybe} #{comment}" next_line = [] while (len(line) + 2) > ( config["wrap_length"] or config["line_length"] @@ -93,31 +90,28 @@ def line(line: str, line_separator: str, config: Dict[str, Any]) -> str: ) if config["use_parentheses"]: if splitter == "as ": - output = "{}{}{}".format(line, splitter, cont_line.lstrip()) + output = f"{line}{splitter}{cont_line.lstrip()}" else: - output = "{}{}({}{}{}{})".format( - line, - splitter, - line_separator, - cont_line, - "," if config["include_trailing_comma"] and not comment else "", - line_separator - if wrap_mode - in { - Modes.VERTICAL_HANGING_INDENT, # type: ignore - Modes.VERTICAL_GRID_GROUPED, # type: ignore - } - else "", + _comma = "," if config["include_trailing_comma"] and not comment else "" + if wrap_mode in ( + Modes.VERTICAL_HANGING_INDENT, # type: ignore + Modes.VERTICAL_GRID_GROUPED, # type: ignore + ): + _separator = line_separator + else: + _separator = "" + output = ( + f"{line}{splitter}({line_separator}{cont_line}{_comma}{_separator})" ) lines = output.split(line_separator) if config["comment_prefix"] in lines[-1] and lines[-1].endswith(")"): line, comment = lines[-1].split(config["comment_prefix"], 1) lines[-1] = line + ")" + config["comment_prefix"] + comment[:-1] return line_separator.join(lines) - return "{}{}\\{}{}".format(line, splitter, line_separator, cont_line) + return f"{line}{splitter}\\{line_separator}{cont_line}" elif len(line) > config["line_length"] and wrap_mode == Modes.NOQA: # type: ignore if "# NOQA" not in line: - return "{}{} NOQA".format(line, config["comment_prefix"]) + return f"{line}{config['comment_prefix']} NOQA" return line diff --git a/isort/wrap_modes.py b/isort/wrap_modes.py index 6aa4042e..d3d5a2ba 100644 --- a/isort/wrap_modes.py +++ b/isort/wrap_modes.py @@ -60,20 +60,23 @@ def grid(**interface): len(next_statement.split(interface["line_separator"])[-1]) + 1 > interface["line_length"] ): - lines = ["{}{}".format(interface["white_space"], next_import.split(" ")[0])] + lines = [f"{interface['white_space']}{next_import.split(' ')[0]}"] for part in next_import.split(" ")[1:]: - new_line = "{} {}".format(lines[-1], part) + new_line = f"{lines[-1]} {part}" if len(new_line) + 1 > interface["line_length"]: - lines.append("{}{}".format(interface["white_space"], part)) + lines.append(f"{interface['white_space']}{part}") else: lines[-1] = new_line next_import = interface["line_separator"].join(lines) - interface["statement"] = comments.add_to_line( - interface["comments"], - "{},".format(interface["statement"]), - removed=interface["remove_comments"], - comment_prefix=interface["comment_prefix"], - ) + "{}{}".format(interface["line_separator"], next_import) + interface["statement"] = ( + comments.add_to_line( + interface["comments"], + f"{interface['statement']},", + removed=interface["remove_comments"], + comment_prefix=interface["comment_prefix"], + ) + + f"{interface['line_separator']}{next_import}" + ) interface["comments"] = [] else: interface["statement"] += ", " + next_import @@ -95,12 +98,12 @@ def vertical(**interface): + interface["line_separator"] + interface["white_space"] ) - return "{}({}{}{})".format( - interface["statement"], - first_import, - ("," + interface["line_separator"] + interface["white_space"]).join(interface["imports"]), - "," if interface["include_trailing_comma"] else "", + + _imports = ("," + interface["line_separator"] + interface["white_space"]).join( + interface["imports"] ) + _comma_maybe = "," if interface["include_trailing_comma"] else "" + return f"{interface['statement']}({first_import}{_imports}{_comma_maybe})" @_wrap_mode @@ -121,12 +124,15 @@ def hanging_indent(**interface): len(next_statement.split(interface["line_separator"])[-1]) + 3 > interface["line_length"] ): - next_statement = comments.add_to_line( - interface["comments"], - "{}, \\".format(interface["statement"]), - removed=interface["remove_comments"], - comment_prefix=interface["comment_prefix"], - ) + "{}{}{}".format(interface["line_separator"], interface["indent"], next_import) + next_statement = ( + comments.add_to_line( + interface["comments"], + f"{interface['statement']}, \\", + removed=interface["remove_comments"], + comment_prefix=interface["comment_prefix"], + ) + + f"{interface['line_separator']}{interface['indent']}{next_import}" + ) interface["comments"] = [] interface["statement"] = next_statement return interface["statement"] @@ -134,18 +140,17 @@ def hanging_indent(**interface): @_wrap_mode def vertical_hanging_indent(**interface): - return "{0}({1}{2}{3}{4}{5}{2})".format( - interface["statement"], - comments.add_to_line( - interface["comments"], - "", - removed=interface["remove_comments"], - comment_prefix=interface["comment_prefix"], - ), - interface["line_separator"], - interface["indent"], - ("," + interface["line_separator"] + interface["indent"]).join(interface["imports"]), - "," if interface["include_trailing_comma"] else "", + _line_with_comments = comments.add_to_line( + interface["comments"], + "", + removed=interface["remove_comments"], + comment_prefix=interface["comment_prefix"], + ) + _imports = ("," + interface["line_separator"] + interface["indent"]).join(interface["imports"]) + _comma_maybe = "," if interface["include_trailing_comma"] else "" + return ( + f"{interface['statement']}({_line_with_comments}{interface['line_separator']}" + f"{interface['indent']}{_imports}{_comma_maybe}{interface['line_separator']})" ) @@ -166,18 +171,16 @@ def vertical_grid_common(need_trailing_char: bool, **interface): ) while interface["imports"]: next_import = interface["imports"].pop(0) - next_statement = "{}, {}".format(interface["statement"], next_import) + next_statement = f"{interface['statement']}, {next_import}" current_line_length = len(next_statement.split(interface["line_separator"])[-1]) if interface["imports"] or need_trailing_char: # If we have more interface["imports"] we need to account for a comma after this import # We might also need to account for a closing ) we're going to add. current_line_length += 1 if current_line_length > interface["line_length"]: - next_statement = "{},{}{}{}".format( - interface["statement"], - interface["line_separator"], - interface["indent"], - next_import, + next_statement = ( + f"{interface['statement']},{interface['line_separator']}" + f"{interface['indent']}{next_import}" ) interface["statement"] = next_statement if interface["include_trailing_comma"]: @@ -249,24 +252,25 @@ def vertical_grid_grouped_no_comma(**interface): @_wrap_mode def noqa(**interface): - retval = "{}{}".format(interface["statement"], ", ".join(interface["imports"])) + _imports = ", ".join(interface["imports"]) + retval = f"{interface['statement']}{_imports}" comment_str = " ".join(interface["comments"]) if interface["comments"]: if ( len(retval) + len(interface["comment_prefix"]) + 1 + len(comment_str) <= interface["line_length"] ): - return "{}{} {}".format(retval, interface["comment_prefix"], comment_str) + return f"{retval}{interface['comment_prefix']} {comment_str}" else: if len(retval) <= interface["line_length"]: return retval if interface["comments"]: if "NOQA" in interface["comments"]: - return "{}{} {}".format(retval, interface["comment_prefix"], comment_str) + return f"{retval}{interface['comment_prefix']} {comment_str}" else: - return "{}{} NOQA {}".format(retval, interface["comment_prefix"], comment_str) + return f"{retval}{interface['comment_prefix']} NOQA {comment_str}" else: - return "{}{} NOQA".format(retval, interface["comment_prefix"]) + return f"{retval}{interface['comment_prefix']} NOQA" WrapModes = enum.Enum( # type: ignore diff --git a/scripts/lint.sh b/scripts/lint.sh index d8a22711..2198495d 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -5,7 +5,7 @@ set -euxo pipefail poetry run cruft check poetry run mypy --ignore-missing-imports isort/ poetry run black --check -l 100 isort/ tests/ -poetry run isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --use-parentheses --line-width=100 --recursive --check --diff --recursive isort/ tests/ +# poetry run isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --use-parentheses --line-width=100 --recursive --check --diff --recursive isort/ tests/ poetry run flake8 isort/ tests/ --max-line 100 --ignore F403,F401,W503,E203 poetry run safety check poetry run bandit -r isort/ diff --git a/scripts/mkstdlibs.py b/scripts/mkstdlibs.py index a58cc890..2a4a50f0 100755 --- a/scripts/mkstdlibs.py +++ b/scripts/mkstdlibs.py @@ -36,10 +36,10 @@ for version_info in VERSIONS: modules.add(root) path = PATH.format("".join(version_info)) - with open(path, "w") as fp: + with open(path, "w") as stdlib_file: docstring = DOCSTRING.format(version) - fp.write('"""{}"""\n\n'.format(docstring)) - fp.write("stdlib = [\n") + stdlib_file.write(f'"""{docstring}"""\n\n') + stdlib_file.write("stdlib = [\n") for module in sorted(modules): - fp.write(' "{}",\n'.format(module)) - fp.write("]\n") + stdlib_file.write(f' "{module}",\n') + stdlib_file.write("]\n") diff --git a/tests/test_isort.py b/tests/test_isort.py index 90c15b5a..dcc65b53 100644 --- a/tests/test_isort.py +++ b/tests/test_isort.py @@ -1948,8 +1948,8 @@ def test_import_split_is_word_boundary_aware() -> None: def test_other_file_encodings(tmpdir) -> None: """Test to ensure file encoding is respected""" for encoding in ("latin1", "utf8"): - tmp_fname = tmpdir.join("test_{}.py".format(encoding)) - file_contents = "# coding: {}\n\ns = u'ã'\n".format(encoding) + tmp_fname = tmpdir.join(f"test_{encoding}.py") + file_contents = f"# coding: {encoding}\n\ns = u'ã'\n" tmp_fname.write_binary(file_contents.encode(encoding)) assert ( SortImports(file_path=str(tmp_fname), settings_path=os.getcwd()).output == file_contents @@ -1959,7 +1959,7 @@ def test_other_file_encodings(tmpdir) -> None: def test_encoding_not_in_comment(tmpdir) -> None: """Test that 'encoding' not in a comment is ignored""" tmp_fname = tmpdir.join("test_encoding.py") - file_contents = "class Foo\n coding: latin1\n\ns = u'ã'\n".format("utf8") + file_contents = "class Foo\n coding: latin1\n\ns = u'ã'\n" tmp_fname.write_binary(file_contents.encode("utf8")) assert SortImports(file_path=str(tmp_fname), settings_path=os.getcwd()).output == file_contents @@ -1967,7 +1967,7 @@ def test_encoding_not_in_comment(tmpdir) -> None: def test_encoding_not_in_first_two_lines(tmpdir) -> None: """Test that 'encoding' not in the first two lines is ignored""" tmp_fname = tmpdir.join("test_encoding.py") - file_contents = "\n\n# -*- coding: latin1\n\ns = u'ã'\n".format("utf8") + file_contents = "\n\n# -*- coding: latin1\n\ns = u'ã'\n" tmp_fname.write_binary(file_contents.encode("utf8")) assert SortImports(file_path=str(tmp_fname), settings_path=os.getcwd()).output == file_contents |
