Skip to content

Commit a255775

Browse files
authored
Merge pull request #2353 from cclauss/some-ruff-optimizations
Apply some ruff rules
2 parents e169a70 + a394f3a commit a255775

17 files changed

+60
-64
lines changed

isort/core.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
from .settings import FILE_SKIP_COMMENTS
1313

1414
CIMPORT_IDENTIFIERS = ("cimport ", "cimport*", "from.cimport")
15-
IMPORT_START_IDENTIFIERS = ("from ", "from.import", "import ", "import*") + CIMPORT_IDENTIFIERS
15+
IMPORT_START_IDENTIFIERS = ("from ", "from.import", "import ", "import*", *CIMPORT_IDENTIFIERS)
1616
DOCSTRING_INDICATORS = ('"""', "'''")
17-
COMMENT_INDICATORS = DOCSTRING_INDICATORS + ("'", '"', "#")
17+
COMMENT_INDICATORS = (*DOCSTRING_INDICATORS, "'", '"', "#")
1818
CODE_SORT_COMMENTS = (
1919
"# isort: list",
2020
"# isort: dict",
@@ -180,11 +180,11 @@ def process(
180180
add_imports = [
181181
import_to_add
182182
for import_to_add in add_imports
183-
if not import_to_add == import_not_to_add
183+
if import_to_add != import_not_to_add
184184
]
185185

186186
if (
187-
(index == 0 or (index in (1, 2) and not contains_imports))
187+
(index == 0 or (index in {1, 2} and not contains_imports))
188188
and stripped_line.startswith("#")
189189
and stripped_line not in config.section_comments
190190
and stripped_line not in CODE_SORT_COMMENTS
@@ -199,11 +199,9 @@ def process(
199199
first_comment_index_end = index - 1
200200

201201
was_in_quote = bool(in_quote)
202-
if (not stripped_line.startswith("#") or in_quote) and '"' in line or "'" in line:
202+
if ((not stripped_line.startswith("#") or in_quote) and '"' in line) or "'" in line:
203203
char_index = 0
204-
if first_comment_index_start == -1 and (
205-
line.startswith('"') or line.startswith("'")
206-
):
204+
if first_comment_index_start == -1 and line.startswith(('"', "'")):
207205
first_comment_index_start = index
208206
while char_index < len(line):
209207
if line[char_index] == "\\":
@@ -287,9 +285,8 @@ def process(
287285
indent = line[: -len(line.lstrip())]
288286
elif not (stripped_line or contains_imports):
289287
not_imports = True
290-
elif (
291-
not stripped_line
292-
or stripped_line.startswith("#")
288+
elif not stripped_line or (
289+
stripped_line.startswith("#")
293290
and (not indent or indent + line.lstrip() == line)
294291
and not config.treat_all_comments_as_code
295292
and stripped_line not in config.treat_comments_as_code
@@ -477,7 +474,7 @@ def process(
477474
output_stream.write(new_line)
478475
stripped_line = new_line.strip().split("#")[0]
479476

480-
if stripped_line.startswith("raise") or stripped_line.startswith("yield"):
477+
if stripped_line.startswith(("raise", "yield")):
481478
while stripped_line.endswith("\\"):
482479
new_line = input_stream.readline()
483480
if not new_line:

isort/deprecated/finders.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -236,10 +236,9 @@ def _load_mapping() -> Optional[Dict[str, str]]:
236236

237237
def _load_names(self) -> List[str]:
238238
"""Return list of thirdparty modules from requirements"""
239-
names = []
239+
names: List[str] = []
240240
for path in self._get_files():
241-
for name in self._get_names(path):
242-
names.append(self._normalize_name(name))
241+
names.extend(self._normalize_name(name) for name in self._get_names(path))
243242
return names
244243

245244
@staticmethod
@@ -298,7 +297,7 @@ def _get_files_from_dir(self, path: str) -> Iterator[str]:
298297
@classmethod
299298
@lru_cache(maxsize=16)
300299
def _get_files_from_dir_cached(cls, path: str) -> List[str]:
301-
results = []
300+
results: List[str] = []
302301

303302
for fname in os.listdir(path):
304303
if "requirements" not in fname:
@@ -308,9 +307,11 @@ def _get_files_from_dir_cached(cls, path: str) -> List[str]:
308307
# *requirements*/*.{txt,in}
309308
if os.path.isdir(full_path):
310309
for subfile_name in os.listdir(full_path):
311-
for ext in cls.exts:
312-
if subfile_name.endswith(ext):
313-
results.append(os.path.join(full_path, subfile_name))
310+
results.extend(
311+
os.path.join(full_path, subfile_name)
312+
for ext in cls.ext # type: ignore[attr-defined]
313+
if subfile_name.endswith(ext)
314+
)
314315
continue
315316

316317
# *requirements*.{txt,in}
@@ -329,13 +330,11 @@ def _get_names(self, path: str) -> Iterator[str]:
329330
@classmethod
330331
@lru_cache(maxsize=16)
331332
def _get_names_cached(cls, path: str) -> List[str]:
332-
result = []
333+
result: List[str] = []
333334

334335
with chdir(os.path.dirname(path)):
335336
requirements = parse_requirements(Path(path))
336-
for req in requirements.values():
337-
if req.name:
338-
result.append(req.name)
337+
result.extend(req.name for req in requirements.values() if req.name)
339338

340339
return result
341340

isort/identify.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def imports(
6161
continue
6262

6363
stripped_line = raw_line.strip().split("#")[0]
64-
if stripped_line.startswith("raise") or stripped_line.startswith("yield"):
64+
if stripped_line.startswith(("raise", "yield")):
6565
if stripped_line == "yield":
6666
while not stripped_line or stripped_line == "yield":
6767
try:

isort/literal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def _list(value: List[Any], printer: ISortPrettyPrinter) -> str:
9696

9797
@register_type("unique-list", list)
9898
def _unique_list(value: List[Any], printer: ISortPrettyPrinter) -> str:
99-
return printer.pformat(list(sorted(set(value))))
99+
return printer.pformat(sorted(set(value)))
100100

101101

102102
@register_type("set", set)

isort/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -876,7 +876,7 @@ def _build_arg_parser() -> argparse.ArgumentParser:
876876
"--python-version",
877877
action="store",
878878
dest="py_version",
879-
choices=tuple(VALID_PY_TARGETS) + ("auto",),
879+
choices=(*tuple(VALID_PY_TARGETS), "auto"),
880880
help="Tells isort to set the known standard library based on the specified Python "
881881
"version. Default is to assume any Python 3 version could be the target, and use a union "
882882
"of all stdlib modules across versions. If auto is specified, the version of the "

isort/output.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def sorted_imports(
4141
parsed.imports[section].get("straight", {})
4242
)
4343
parsed.imports["no_sections"]["from"].update(parsed.imports[section].get("from", {}))
44-
sections = base_sections + ("no_sections",)
44+
sections = (*base_sections, "no_sections")
4545

4646
output: List[str] = []
4747
seen_headings: Set[str] = set()
@@ -338,7 +338,7 @@ def _with_from_imports(
338338
)
339339
if comment:
340340
single_import_line += (
341-
f"{comments and ';' or config.comment_prefix} " f"{comment}"
341+
f"{(comments and ';') or config.comment_prefix} " f"{comment}"
342342
)
343343
if from_import in as_imports:
344344
if (
@@ -467,7 +467,7 @@ def _with_from_imports(
467467
comment_prefix=config.comment_prefix,
468468
)
469469
single_import_line += (
470-
f"{use_comments and ';' or config.comment_prefix} " f"{comment}"
470+
f"{(use_comments and ';') or config.comment_prefix} " f"{comment}"
471471
)
472472
output.append(wrap.line(single_import_line, parsed.line_separator, config))
473473

@@ -662,7 +662,7 @@ def _ensure_newline_before_comment(output: List[str]) -> List[str]:
662662
def is_comment(line: Optional[str]) -> bool:
663663
return line.startswith("#") if line else False
664664

665-
for line, prev_line in zip(output, [None] + output): # type: ignore
665+
for line, prev_line in zip(output, [None, *output]):
666666
if is_comment(line) and prev_line != "" and not is_comment(prev_line):
667667
new_output.append("")
668668
new_output.append(line)
@@ -672,5 +672,5 @@ def is_comment(line: Optional[str]) -> bool:
672672
def _with_star_comments(parsed: parse.ParsedContent, module: str, comments: List[str]) -> List[str]:
673673
star_comment = parsed.categorized_comments["nested"].get(module, {}).pop("*", None)
674674
if star_comment:
675-
return comments + [star_comment]
675+
return [*comments, star_comment]
676676
return comments

isort/parse.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
493493
and "isort:imports-" not in last
494494
and "isort: imports-" not in last
495495
and not config.treat_all_comments_as_code
496-
and not last.strip() in config.treat_comments_as_code
496+
and last.strip() not in config.treat_comments_as_code
497497
):
498498
categorized_comments["above"]["from"].setdefault(import_from, []).insert(
499499
0, out_lines.pop(-1)
@@ -545,7 +545,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte
545545
and "isort:imports-" not in last
546546
and "isort: imports-" not in last
547547
and not config.treat_all_comments_as_code
548-
and not last.strip() in config.treat_comments_as_code
548+
and last.strip() not in config.treat_comments_as_code
549549
):
550550
categorized_comments["above"]["straight"].setdefault(module, []).insert(
551551
0, out_lines.pop(-1)

isort/place.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def _src_path(
7171
src_paths = config.src_paths
7272

7373
root_module_name, *nested_module = name.split(".", 1)
74-
new_prefix = prefix + (root_module_name,)
74+
new_prefix = (*prefix, root_module_name)
7575
namespace = ".".join(new_prefix)
7676

7777
for src_path in src_paths:

isort/settings.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ def __init__(
437437
if section in SECTION_DEFAULTS:
438438
continue
439439

440-
if not section.lower() in known_other:
440+
if section.lower() not in known_other:
441441
config_keys = ", ".join(known_other.keys())
442442
warn(
443443
f"`sections` setting includes {section}, but no known_{section.lower()} "
@@ -852,15 +852,12 @@ def _get_config_data(file_path: str, sections: Tuple[str, ...]) -> Dict[str, Any
852852
for section in sections:
853853
if section.startswith("*.{") and section.endswith("}"):
854854
extension = section[len("*.{") : -1]
855-
for config_key in config.keys():
855+
for config_key in config:
856856
if (
857857
config_key.startswith("*.{")
858858
and config_key.endswith("}")
859859
and extension
860-
in map(
861-
lambda text: text.strip(),
862-
config_key[len("*.{") : -1].split(","), # noqa
863-
)
860+
in (text.strip() for text in config_key[len("*.{") : -1].split(","))
864861
):
865862
settings.update(config.items(config_key))
866863

@@ -877,10 +874,10 @@ def _get_config_data(file_path: str, sections: Tuple[str, ...]) -> Dict[str, Any
877874
indent_size = settings.pop("tab_width", "").strip()
878875

879876
if indent_style == "space":
880-
settings["indent"] = " " * (indent_size and int(indent_size) or 4)
877+
settings["indent"] = " " * ((indent_size and int(indent_size)) or 4)
881878

882879
elif indent_style == "tab":
883-
settings["indent"] = "\t" * (indent_size and int(indent_size) or 1)
880+
settings["indent"] = "\t" * ((indent_size and int(indent_size)) or 1)
884881

885882
max_line_length = settings.pop("max_line_length", "").strip()
886883
if max_line_length and (max_line_length == "off" or max_line_length.isdigit()):
@@ -890,7 +887,7 @@ def _get_config_data(file_path: str, sections: Tuple[str, ...]) -> Dict[str, Any
890887
settings = {
891888
key: value
892889
for key, value in settings.items()
893-
if key in _DEFAULT_SETTINGS.keys() or key.startswith(KNOWN_PREFIX)
890+
if key in _DEFAULT_SETTINGS or key.startswith(KNOWN_PREFIX)
894891
}
895892

896893
for key, value in settings.items():

isort/sorting.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def module_key(
5151
or str(section_name).lower() in config.length_sort_sections
5252
)
5353
_length_sort_maybe = (str(len(module_name)) + ":" + module_name) if length_sort else module_name
54-
return f"{module_name in config.force_to_top and 'A' or 'B'}{prefix}{_length_sort_maybe}"
54+
return f"{(module_name in config.force_to_top and 'A') or 'B'}{prefix}{_length_sort_maybe}"
5555

5656

5757
def section_key(line: str, config: Config) -> str:
@@ -90,7 +90,7 @@ def section_key(line: str, config: Config) -> str:
9090
module_name = module_name.lower()
9191
if not config.order_by_type:
9292
names = names.lower()
93-
line = " import ".join([module_name, names])
93+
line = f"{module_name} import {names}"
9494
elif not config.case_sensitive:
9595
line = line.lower()
9696
elif not config.order_by_type:

isort/wrap_modes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def hanging_indent_with_parentheses(**interface: Any) -> str:
333333
while interface["imports"]:
334334
next_import = interface["imports"].pop(0)
335335
if (
336-
not interface["line_separator"] in interface["statement"]
336+
interface["line_separator"] not in interface["statement"]
337337
and "#" in interface["statement"]
338338
): # pragma: no cover # TODO: fix, this is because of test run inconsistency.
339339
line, comments = interface["statement"].split("#", 1)

scripts/build_profile_docs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121

2222
def format_profile(profile_name: str, profile: Dict[str, Any]) -> str:
23-
options = "\n".join(f" - **{name}**: `{repr(value)}`" for name, value in profile.items())
23+
options = "\n".join(f" - **{name}**: `{value!r}`" for name, value in profile.items())
2424
return f"""
2525
#{profile_name}
2626

tests/integration/test_hypothesmith.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def configs(**force_strategies: st.SearchStrategy) -> st.SearchStrategy:
6363
"default_section": st.sampled_from(sorted(isort.settings.KNOWN_SECTION_MAPPING)),
6464
"force_grid_wrap": st.integers(0, 20),
6565
"profile": st.sampled_from(sorted(isort.settings.profiles)),
66-
"py_version": st.sampled_from(("auto",) + isort.settings.VALID_PY_TARGETS),
66+
"py_version": st.sampled_from(("auto", *isort.settings.VALID_PY_TARGETS)),
6767
}
6868
kwargs = {**inferred_kwargs, **specific, **force_strategies}
6969
return st.fixed_dictionaries({}, optional=kwargs).map(_as_config)

tests/integration/test_setting_combinations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def configs() -> st.SearchStrategy:
5858
"force_grid_wrap": st.integers(0, 20),
5959
"profile": st.sampled_from(sorted(isort.settings.profiles)),
6060
"sort_order": st.sampled_from(sorted(("native", "natural", "natural_plus"))),
61-
"py_version": st.sampled_from(("auto",) + isort.settings.VALID_PY_TARGETS),
61+
"py_version": st.sampled_from(("auto", *isort.settings.VALID_PY_TARGETS)),
6262
}
6363
kwargs = {**inferred_kwargs, **specific}
6464
return st.fixed_dictionaries({}, optional=kwargs).map(_as_config)

tests/unit/test_deprecated_finders.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def __init__(self, *args, **kwargs):
2121

2222
with patch(
2323
"isort.deprecated.finders.FindersManager._default_finders_classes",
24-
FindersManager._default_finders_classes + (ExceptionOnInit,), # type: ignore
24+
(*FindersManager._default_finders_classes, ExceptionOnInit),
2525
):
2626
assert FindersManager(settings.Config(verbose=True))
2727

tests/unit/test_hooks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def test_git_hook(src_dir):
6666
"isort.hooks.get_lines", MagicMock(return_value=[os.path.join(src_dir, "main.py")])
6767
) as run_mock:
6868

69-
class FakeProcessResponse(object):
69+
class FakeProcessResponse:
7070
stdout = b"# isort: skip-file\nimport b\nimport a\n"
7171

7272
with patch("subprocess.run", MagicMock(return_value=FakeProcessResponse())) as run_mock:

0 commit comments

Comments
 (0)