Skip to content

Commit 012aa69

Browse files
authored
Merge pull request #2431 from DanielNoord/ruff-it-up
Target 3.10 with `ruff`
2 parents 933e382 + 89773db commit 012aa69

22 files changed

+125
-139
lines changed

isort/api.py

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from io import StringIO
2323
from itertools import chain
2424
from pathlib import Path
25-
from typing import Any, Optional, TextIO, Union, cast
25+
from typing import Any, TextIO, cast
2626
from warnings import warn
2727

2828
from isort import core
@@ -69,11 +69,11 @@ class ImportKey(Enum):
6969

7070
def sort_code_string(
7171
code: str,
72-
extension: Optional[str] = None,
72+
extension: str | None = None,
7373
config: Config = DEFAULT_CONFIG,
74-
file_path: Optional[Path] = None,
74+
file_path: Path | None = None,
7575
disregard_skip: bool = False,
76-
show_diff: Union[bool, TextIO] = False,
76+
show_diff: bool | TextIO = False,
7777
**config_kwargs: Any,
7878
) -> str:
7979
"""Sorts any imports within the provided code string, returning a new string with them sorted.
@@ -105,10 +105,10 @@ def sort_code_string(
105105

106106
def check_code_string(
107107
code: str,
108-
show_diff: Union[bool, TextIO] = False,
109-
extension: Optional[str] = None,
108+
show_diff: bool | TextIO = False,
109+
extension: str | None = None,
110110
config: Config = DEFAULT_CONFIG,
111-
file_path: Optional[Path] = None,
111+
file_path: Path | None = None,
112112
disregard_skip: bool = False,
113113
**config_kwargs: Any,
114114
) -> bool:
@@ -138,11 +138,11 @@ def check_code_string(
138138
def sort_stream(
139139
input_stream: TextIO,
140140
output_stream: TextIO,
141-
extension: Optional[str] = None,
141+
extension: str | None = None,
142142
config: Config = DEFAULT_CONFIG,
143-
file_path: Optional[Path] = None,
143+
file_path: Path | None = None,
144144
disregard_skip: bool = False,
145-
show_diff: Union[bool, TextIO] = False,
145+
show_diff: bool | TextIO = False,
146146
raise_on_skip: bool = True,
147147
**config_kwargs: Any,
148148
) -> bool:
@@ -240,10 +240,10 @@ def sort_stream(
240240

241241
def check_stream(
242242
input_stream: TextIO,
243-
show_diff: Union[bool, TextIO] = False,
244-
extension: Optional[str] = None,
243+
show_diff: bool | TextIO = False,
244+
extension: str | None = None,
245245
config: Config = DEFAULT_CONFIG,
246-
file_path: Optional[Path] = None,
246+
file_path: Path | None = None,
247247
disregard_skip: bool = False,
248248
**config_kwargs: Any,
249249
) -> bool:
@@ -306,12 +306,12 @@ def check_stream(
306306

307307

308308
def check_file(
309-
filename: Union[str, Path],
310-
show_diff: Union[bool, TextIO] = False,
309+
filename: str | Path,
310+
show_diff: bool | TextIO = False,
311311
config: Config = DEFAULT_CONFIG,
312-
file_path: Optional[Path] = None,
312+
file_path: Path | None = None,
313313
disregard_skip: bool = True,
314-
extension: Optional[str] = None,
314+
extension: str | None = None,
315315
**config_kwargs: Any,
316316
) -> bool:
317317
"""Checks any imports within the provided file, returning `False` if any unsorted or
@@ -359,7 +359,7 @@ def _in_memory_output_stream_context() -> Iterator[TextIO]:
359359

360360

361361
@contextlib.contextmanager
362-
def _file_output_stream_context(filename: Union[str, Path], source_file: File) -> Iterator[TextIO]:
362+
def _file_output_stream_context(filename: str | Path, source_file: File) -> Iterator[TextIO]:
363363
tmp_file = _tmp_file(source_file)
364364
with tmp_file.open("w+", encoding=source_file.encoding, newline="") as output_stream:
365365
shutil.copymode(filename, tmp_file)
@@ -370,15 +370,15 @@ def _file_output_stream_context(filename: Union[str, Path], source_file: File) -
370370
# the main entrypoints so sort of expected to be complex.
371371
# skipcq: PY-R1000
372372
def sort_file(
373-
filename: Union[str, Path],
374-
extension: Optional[str] = None,
373+
filename: str | Path,
374+
extension: str | None = None,
375375
config: Config = DEFAULT_CONFIG,
376-
file_path: Optional[Path] = None,
376+
file_path: Path | None = None,
377377
disregard_skip: bool = True,
378378
ask_to_apply: bool = False,
379-
show_diff: Union[bool, TextIO] = False,
379+
show_diff: bool | TextIO = False,
380380
write_to_stdout: bool = False,
381-
output: Optional[TextIO] = None,
381+
output: TextIO | None = None,
382382
**config_kwargs: Any,
383383
) -> bool:
384384
"""Sorts and formats any groups of imports within the provided file or Path.
@@ -510,8 +510,8 @@ def sort_file(
510510
def find_imports_in_code(
511511
code: str,
512512
config: Config = DEFAULT_CONFIG,
513-
file_path: Optional[Path] = None,
514-
unique: Union[bool, ImportKey] = False,
513+
file_path: Path | None = None,
514+
unique: bool | ImportKey = False,
515515
top_only: bool = False,
516516
**config_kwargs: Any,
517517
) -> Iterator[identify.Import]:
@@ -537,10 +537,10 @@ def find_imports_in_code(
537537
def find_imports_in_stream(
538538
input_stream: TextIO,
539539
config: Config = DEFAULT_CONFIG,
540-
file_path: Optional[Path] = None,
541-
unique: Union[bool, ImportKey] = False,
540+
file_path: Path | None = None,
541+
unique: bool | ImportKey = False,
542542
top_only: bool = False,
543-
_seen: Optional[set[str]] = None,
543+
_seen: set[str] | None = None,
544544
**config_kwargs: Any,
545545
) -> Iterator[identify.Import]:
546546
"""Finds and returns all imports within the provided code stream.
@@ -577,10 +577,10 @@ def find_imports_in_stream(
577577

578578

579579
def find_imports_in_file(
580-
filename: Union[str, Path],
580+
filename: str | Path,
581581
config: Config = DEFAULT_CONFIG,
582-
file_path: Optional[Path] = None,
583-
unique: Union[bool, ImportKey] = False,
582+
file_path: Path | None = None,
583+
unique: bool | ImportKey = False,
584584
top_only: bool = False,
585585
**config_kwargs: Any,
586586
) -> Iterator[identify.Import]:
@@ -609,10 +609,10 @@ def find_imports_in_file(
609609

610610

611611
def find_imports_in_paths(
612-
paths: Iterator[Union[str, Path]],
612+
paths: Iterator[str | Path],
613613
config: Config = DEFAULT_CONFIG,
614-
file_path: Optional[Path] = None,
615-
unique: Union[bool, ImportKey] = False,
614+
file_path: Path | None = None,
615+
unique: bool | ImportKey = False,
616616
top_only: bool = False,
617617
**config_kwargs: Any,
618618
) -> Iterator[identify.Import]:
@@ -627,7 +627,7 @@ def find_imports_in_paths(
627627
- ****config_kwargs**: Any config modifications.
628628
"""
629629
config = _config(config=config, **config_kwargs)
630-
seen: Optional[set[str]] = set() if unique else None
630+
seen: set[str] | None = set() if unique else None
631631
yield from chain(
632632
*(
633633
find_imports_in_file(
@@ -639,7 +639,7 @@ def find_imports_in_paths(
639639

640640

641641
def _config(
642-
path: Optional[Path] = None, config: Config = DEFAULT_CONFIG, **config_kwargs: Any
642+
path: Path | None = None, config: Config = DEFAULT_CONFIG, **config_kwargs: Any
643643
) -> Config:
644644
if path and (
645645
config is DEFAULT_CONFIG

isort/comments.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
from typing import Optional
2-
3-
41
def parse(line: str) -> tuple[str, str]:
52
"""Parses import lines for comments and returns back the
63
import statement and the associated comment.
@@ -13,7 +10,7 @@ def parse(line: str) -> tuple[str, str]:
1310

1411

1512
def add_to_line(
16-
comments: Optional[list[str]],
13+
comments: list[str] | None,
1714
original_string: str = "",
1815
removed: bool = False,
1916
comment_prefix: str = "",

isort/core.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import textwrap
22
from io import StringIO
33
from itertools import chain
4-
from typing import TextIO, Union
4+
from typing import TextIO
55

66
import isort.literal
77
from isort.settings import DEFAULT_CONFIG, Config
@@ -67,7 +67,7 @@ def process(
6767
indent: str = ""
6868
isort_off: bool = False
6969
skip_file: bool = False
70-
code_sorting: Union[bool, str] = False
70+
code_sorting: bool | str = False
7171
code_sorting_section: str = ""
7272
code_sorting_indent: str = ""
7373
cimports: bool = False

isort/deprecated/finders.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from glob import glob
1616
from pathlib import Path
1717
from re import Pattern
18-
from typing import Optional
1918

2019
from isort import sections
2120
from isort.settings import KNOWN_SECTION_MAPPING, Config
@@ -50,12 +49,12 @@ def __init__(self, config: Config) -> None:
5049
self.config = config
5150

5251
@abstractmethod
53-
def find(self, module_name: str) -> Optional[str]:
52+
def find(self, module_name: str) -> str | None:
5453
raise NotImplementedError
5554

5655

5756
class ForcedSeparateFinder(BaseFinder):
58-
def find(self, module_name: str) -> Optional[str]:
57+
def find(self, module_name: str) -> str | None:
5958
for forced_separate in self.config.forced_separate:
6059
# Ensure all forced_separate patterns will match to end of string
6160
path_glob = forced_separate
@@ -68,7 +67,7 @@ def find(self, module_name: str) -> Optional[str]:
6867

6968

7069
class LocalFinder(BaseFinder):
71-
def find(self, module_name: str) -> Optional[str]:
70+
def find(self, module_name: str) -> str | None:
7271
if module_name.startswith("."):
7372
return "LOCALFOLDER"
7473
return None
@@ -107,7 +106,7 @@ def _parse_known_pattern(self, pattern: str) -> list[str]:
107106

108107
return patterns
109108

110-
def find(self, module_name: str) -> Optional[str]:
109+
def find(self, module_name: str) -> str | None:
111110
# Try to find most specific placement instruction match (if any)
112111
parts = module_name.split(".")
113112
module_names_to_check = (".".join(parts[:first_k]) for first_k in range(len(parts), 0, -1))
@@ -165,7 +164,7 @@ def __init__(self, config: Config, path: str = ".") -> None:
165164
if system_path not in self.paths:
166165
self.paths.append(system_path)
167166

168-
def find(self, module_name: str) -> Optional[str]:
167+
def find(self, module_name: str) -> str | None:
169168
for prefix in self.paths:
170169
package_path = "/".join((prefix, module_name.split(".")[0]))
171170
path_obj = Path(package_path).resolve()
@@ -219,7 +218,7 @@ def _get_files_from_dir(self, path: str) -> Iterator[str]:
219218
raise NotImplementedError
220219

221220
@staticmethod
222-
def _load_mapping() -> Optional[dict[str, str]]:
221+
def _load_mapping() -> dict[str, str] | None:
223222
"""Return list of mappings `package_name -> module_name`
224223
225224
Example:
@@ -272,7 +271,7 @@ def _normalize_name(self, name: str) -> str:
272271
name = self.mapping.get(name.replace("-", "_"), name)
273272
return name.lower().replace("-", "_")
274273

275-
def find(self, module_name: str) -> Optional[str]:
274+
def find(self, module_name: str) -> str | None:
276275
# required lib not installed yet
277276
if not self.enabled:
278277
return None
@@ -342,7 +341,7 @@ def _get_names_cached(cls, path: str) -> list[str]:
342341

343342

344343
class DefaultFinder(BaseFinder):
345-
def find(self, module_name: str) -> Optional[str]:
344+
def find(self, module_name: str) -> str | None:
346345
return self.config.default_section
347346

348347

@@ -357,7 +356,7 @@ class FindersManager:
357356
)
358357

359358
def __init__(
360-
self, config: Config, finder_classes: Optional[Iterable[type[BaseFinder]]] = None
359+
self, config: Config, finder_classes: Iterable[type[BaseFinder]] | None = None
361360
) -> None:
362361
self.verbose: bool = config.verbose
363362

@@ -376,7 +375,7 @@ def __init__(
376375
)
377376
self.finders: tuple[BaseFinder, ...] = tuple(finders)
378377

379-
def find(self, module_name: str) -> Optional[str]:
378+
def find(self, module_name: str) -> str | None:
380379
for finder in self.finders:
381380
try:
382381
section = finder.find(module_name)

isort/exceptions.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from functools import partial
44
from pathlib import Path
5-
from typing import Any, Union
5+
from typing import Any
66

77
from .profiles import profiles
88

@@ -113,7 +113,7 @@ class LiteralParsingFailure(ISortError):
113113
the given data structure.
114114
"""
115115

116-
def __init__(self, code: str, original_error: Union[Exception, type[Exception]]):
116+
def __init__(self, code: str, original_error: Exception | type[Exception]):
117117
super().__init__(
118118
f"isort failed to parse the given literal {code}. It's important to note "
119119
"that isort literal sorting only supports simple literals parsable by "
@@ -181,7 +181,7 @@ def __init__(self, unsupported_settings: dict[str, dict[str, str]]):
181181
class UnsupportedEncoding(ISortError):
182182
"""Raised when isort encounters an encoding error while trying to read a file"""
183183

184-
def __init__(self, filename: Union[str, Path]):
184+
def __init__(self, filename: str | Path):
185185
super().__init__(f"Unknown or unsupported encoding in {filename}")
186186
self.filename = filename
187187

isort/format.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from datetime import datetime
44
from difflib import unified_diff
55
from pathlib import Path
6-
from typing import Optional, TextIO
6+
from typing import TextIO
77

88
try:
99
import colorama
@@ -44,8 +44,8 @@ def show_unified_diff(
4444
*,
4545
file_input: str,
4646
file_output: str,
47-
file_path: Optional[Path],
48-
output: Optional[TextIO] = None,
47+
file_path: Path | None,
48+
output: TextIO | None = None,
4949
color_output: bool = False,
5050
) -> None:
5151
"""Shows a unified_diff for the provided input and output against the provided file path.
@@ -94,7 +94,7 @@ class BasicPrinter:
9494
ERROR = "ERROR"
9595
SUCCESS = "SUCCESS"
9696

97-
def __init__(self, error: str, success: str, output: Optional[TextIO] = None):
97+
def __init__(self, error: str, success: str, output: TextIO | None = None):
9898
self.output = output or sys.stdout
9999
self.success_message = success
100100
self.error_message = error
@@ -110,7 +110,7 @@ def diff_line(self, line: str) -> None:
110110

111111

112112
class ColoramaPrinter(BasicPrinter):
113-
def __init__(self, error: str, success: str, output: Optional[TextIO]):
113+
def __init__(self, error: str, success: str, output: TextIO | None):
114114
super().__init__(error, success, output=output)
115115

116116
# Note: this constants are instance variables instead ofs class variables
@@ -121,7 +121,7 @@ def __init__(self, error: str, success: str, output: Optional[TextIO]):
121121
self.REMOVED_LINE = colorama.Fore.RED
122122

123123
@staticmethod
124-
def style_text(text: str, style: Optional[str] = None) -> str:
124+
def style_text(text: str, style: str | None = None) -> str:
125125
if style is None:
126126
return text
127127
return style + text + str(colorama.Style.RESET_ALL)
@@ -136,7 +136,7 @@ def diff_line(self, line: str) -> None:
136136

137137

138138
def create_terminal_printer(
139-
color: bool, output: Optional[TextIO] = None, error: str = "", success: str = ""
139+
color: bool, output: TextIO | None = None, error: str = "", success: str = ""
140140
) -> BasicPrinter:
141141
if color and colorama_unavailable:
142142
no_colorama_message = (

0 commit comments

Comments
 (0)