Skip to content

Commit 5bb0610

Browse files
authored
Merge pull request #2422 from DanielNoord/random-cleanup
More cleanup
2 parents 26287fe + 6ad72fb commit 5bb0610

33 files changed

+283
-313
lines changed

isort/api.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,12 @@
1717
import contextlib
1818
import shutil
1919
import sys
20+
from collections.abc import Iterator
2021
from enum import Enum
2122
from io import StringIO
2223
from itertools import chain
2324
from pathlib import Path
24-
from typing import Any, Iterator, Optional, Set, TextIO, Union, cast
25+
from typing import Any, Optional, TextIO, Union, cast
2526
from warnings import warn
2627

2728
from isort import core
@@ -539,7 +540,7 @@ def find_imports_in_stream(
539540
file_path: Optional[Path] = None,
540541
unique: Union[bool, ImportKey] = False,
541542
top_only: bool = False,
542-
_seen: Optional[Set[str]] = None,
543+
_seen: Optional[set[str]] = None,
543544
**config_kwargs: Any,
544545
) -> Iterator[identify.Import]:
545546
"""Finds and returns all imports within the provided code stream.
@@ -559,7 +560,7 @@ def find_imports_in_stream(
559560
if not unique:
560561
yield from identified_imports
561562

562-
seen: Set[str] = set() if _seen is None else _seen
563+
seen: set[str] = set() if _seen is None else _seen
563564
for identified_import in identified_imports:
564565
if unique in (True, ImportKey.ALIAS):
565566
key = identified_import.statement()
@@ -626,7 +627,7 @@ def find_imports_in_paths(
626627
- ****config_kwargs**: Any config modifications.
627628
"""
628629
config = _config(config=config, **config_kwargs)
629-
seen: Optional[Set[str]] = set() if unique else None
630+
seen: Optional[set[str]] = set() if unique else None
630631
yield from chain(
631632
*(
632633
find_imports_in_file(

isort/comments.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
from typing import List, Optional, Tuple
1+
from typing import Optional
22

33

4-
def parse(line: str) -> Tuple[str, str]:
4+
def parse(line: str) -> tuple[str, str]:
55
"""Parses import lines for comments and returns back the
66
import statement and the associated comment.
77
"""
@@ -13,7 +13,7 @@ def parse(line: str) -> Tuple[str, str]:
1313

1414

1515
def add_to_line(
16-
comments: Optional[List[str]],
16+
comments: Optional[list[str]],
1717
original_string: str = "",
1818
removed: bool = False,
1919
comment_prefix: str = "",
@@ -25,7 +25,7 @@ def add_to_line(
2525
if not comments:
2626
return original_string
2727

28-
unique_comments: List[str] = []
28+
unique_comments: list[str] = []
2929
for comment in comments:
3030
if comment not in unique_comments:
3131
unique_comments.append(comment)

isort/core.py

Lines changed: 4 additions & 4 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 List, TextIO, Union
4+
from typing import TextIO, Union
55

66
import isort.literal
77
from isort.settings import DEFAULT_CONFIG, Config
@@ -53,7 +53,7 @@ def process(
5353
was provided in the input_stream, otherwise `False`.
5454
"""
5555
line_separator: str = config.line_ending
56-
add_imports: List[str] = [format_natural(addition) for addition in config.add_imports]
56+
add_imports: list[str] = [format_natural(addition) for addition in config.add_imports]
5757
import_section: str = ""
5858
next_import_section: str = ""
5959
next_cimports: bool = False
@@ -74,8 +74,8 @@ def process(
7474
made_changes: bool = False
7575
stripped_line: str = ""
7676
end_of_file: bool = False
77-
verbose_output: List[str] = []
78-
lines_before: List[str] = []
77+
verbose_output: list[str] = []
78+
lines_before: list[str] = []
7979
is_reexport: bool = False
8080
reexport_rollback: int = 0
8181

isort/deprecated/finders.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88
import sys
99
import sysconfig
1010
from abc import ABCMeta, abstractmethod
11+
from collections.abc import Iterable, Iterator, Sequence
1112
from contextlib import contextmanager
1213
from fnmatch import fnmatch
1314
from functools import lru_cache
1415
from glob import glob
1516
from pathlib import Path
16-
from typing import Dict, Iterable, Iterator, List, Optional, Pattern, Sequence, Tuple, Type
17+
from re import Pattern
18+
from typing import Optional
1719

1820
from isort import sections
1921
from isort.settings import KNOWN_SECTION_MAPPING, Config
@@ -76,7 +78,7 @@ class KnownPatternFinder(BaseFinder):
7678
def __init__(self, config: Config) -> None:
7779
super().__init__(config)
7880

79-
self.known_patterns: List[Tuple[Pattern[str], str]] = []
81+
self.known_patterns: list[tuple[Pattern[str], str]] = []
8082
for placement in reversed(config.sections):
8183
known_placement = KNOWN_SECTION_MAPPING.get(placement, placement).lower()
8284
config_key = f"known_{known_placement}"
@@ -92,7 +94,7 @@ def __init__(self, config: Config) -> None:
9294
regexp = "^" + known_pattern.replace("*", ".*").replace("?", ".?") + "$"
9395
self.known_patterns.append((re.compile(regexp), placement))
9496

95-
def _parse_known_pattern(self, pattern: str) -> List[str]:
97+
def _parse_known_pattern(self, pattern: str) -> list[str]:
9698
"""Expand pattern if identified as a directory and return found sub packages"""
9799
if pattern.endswith(os.path.sep):
98100
patterns = [
@@ -217,7 +219,7 @@ def _get_files_from_dir(self, path: str) -> Iterator[str]:
217219
raise NotImplementedError
218220

219221
@staticmethod
220-
def _load_mapping() -> Optional[Dict[str, str]]:
222+
def _load_mapping() -> Optional[dict[str, str]]:
221223
"""Return list of mappings `package_name -> module_name`
222224
223225
Example:
@@ -228,15 +230,15 @@ def _load_mapping() -> Optional[Dict[str, str]]:
228230
path = os.path.dirname(inspect.getfile(pipreqs))
229231
path = os.path.join(path, "mapping")
230232
with open(path) as f:
231-
mappings: Dict[str, str] = {} # pypi_name: import_name
233+
mappings: dict[str, str] = {} # pypi_name: import_name
232234
for line in f:
233235
import_name, _, pypi_name = line.strip().partition(":")
234236
mappings[pypi_name] = import_name
235237
return mappings
236238

237-
def _load_names(self) -> List[str]:
239+
def _load_names(self) -> list[str]:
238240
"""Return list of thirdparty modules from requirements"""
239-
names: List[str] = []
241+
names: list[str] = []
240242
for path in self._get_files():
241243
names.extend(self._normalize_name(name) for name in self._get_names(path))
242244
return names
@@ -296,8 +298,8 @@ def _get_files_from_dir(self, path: str) -> Iterator[str]:
296298

297299
@classmethod
298300
@lru_cache(maxsize=16)
299-
def _get_files_from_dir_cached(cls, path: str) -> List[str]:
300-
results: List[str] = []
301+
def _get_files_from_dir_cached(cls, path: str) -> list[str]:
302+
results: list[str] = []
301303

302304
for fname in os.listdir(path):
303305
if "requirements" not in fname:
@@ -329,8 +331,8 @@ def _get_names(self, path: str) -> Iterator[str]:
329331

330332
@classmethod
331333
@lru_cache(maxsize=16)
332-
def _get_names_cached(cls, path: str) -> List[str]:
333-
result: List[str] = []
334+
def _get_names_cached(cls, path: str) -> list[str]:
335+
result: list[str] = []
334336

335337
with chdir(os.path.dirname(path)):
336338
requirements = parse_requirements(Path(path))
@@ -345,7 +347,7 @@ def find(self, module_name: str) -> Optional[str]:
345347

346348

347349
class FindersManager:
348-
_default_finders_classes: Sequence[Type[BaseFinder]] = (
350+
_default_finders_classes: Sequence[type[BaseFinder]] = (
349351
ForcedSeparateFinder,
350352
LocalFinder,
351353
KnownPatternFinder,
@@ -355,26 +357,24 @@ class FindersManager:
355357
)
356358

357359
def __init__(
358-
self, config: Config, finder_classes: Optional[Iterable[Type[BaseFinder]]] = None
360+
self, config: Config, finder_classes: Optional[Iterable[type[BaseFinder]]] = None
359361
) -> None:
360362
self.verbose: bool = config.verbose
361363

362364
if finder_classes is None:
363365
finder_classes = self._default_finders_classes
364-
finders: List[BaseFinder] = []
366+
finders: list[BaseFinder] = []
365367
for finder_cls in finder_classes:
366368
try:
367369
finders.append(finder_cls(config))
368370
except Exception as exception:
369371
# if one finder fails to instantiate isort can continue using the rest
370372
if self.verbose:
371373
print(
372-
(
373-
f"{finder_cls.__name__} encountered an error ({exception}) during "
374-
"instantiation and cannot be used"
375-
)
374+
f"{finder_cls.__name__} encountered an error ({exception}) during "
375+
"instantiation and cannot be used"
376376
)
377-
self.finders: Tuple[BaseFinder, ...] = tuple(finders)
377+
self.finders: tuple[BaseFinder, ...] = tuple(finders)
378378

379379
def find(self, module_name: str) -> Optional[str]:
380380
for finder in self.finders:

isort/exceptions.py

Lines changed: 4 additions & 4 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, Dict, List, Type, Union
5+
from typing import Any, Union
66

77
from .profiles import profiles
88

@@ -91,7 +91,7 @@ def __init__(self, profile: str):
9191
class SortingFunctionDoesNotExist(ISortError):
9292
"""Raised when the specified sorting function isn't available"""
9393

94-
def __init__(self, sort_order: str, available_sort_orders: List[str]):
94+
def __init__(self, sort_order: str, available_sort_orders: list[str]):
9595
super().__init__(
9696
f"Specified sort_order of {sort_order} does not exist. "
9797
f"Available sort_orders: {','.join(available_sort_orders)}."
@@ -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: Union[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 "
@@ -164,7 +164,7 @@ class UnsupportedSettings(ISortError):
164164
def _format_option(name: str, value: Any, source: str) -> str:
165165
return f"\t- {name} = {value} (source: '{source}')"
166166

167-
def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]):
167+
def __init__(self, unsupported_settings: dict[str, dict[str, str]]):
168168
errors = "\n".join(
169169
self._format_option(name, **option) for name, option in unsupported_settings.items()
170170
)

isort/files.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import os
2+
from collections.abc import Iterable, Iterator
23
from pathlib import Path
3-
from typing import Iterable, Iterator, List, Set
44

55
from isort.settings import Config
66

77

88
def find(
9-
paths: Iterable[str], config: Config, skipped: List[str], broken: List[str]
9+
paths: Iterable[str], config: Config, skipped: list[str], broken: list[str]
1010
) -> Iterator[str]:
1111
"""Fines and provides an iterator for all Python source files defined in paths."""
12-
visited_dirs: Set[Path] = set()
12+
visited_dirs: set[Path] = set()
1313

1414
for path in paths:
1515
if os.path.isdir(path):

isort/hooks.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
import os
88
import subprocess # nosec
99
from pathlib import Path
10-
from typing import List, Optional
10+
from typing import Optional
1111

1212
from isort import Config, api, exceptions
1313

1414

15-
def get_output(command: List[str]) -> str:
15+
def get_output(command: list[str]) -> str:
1616
"""Run a command and return raw output
1717
1818
:param str command: the command to run
@@ -22,7 +22,7 @@ def get_output(command: List[str]) -> str:
2222
return result.stdout.decode()
2323

2424

25-
def get_lines(command: List[str]) -> List[str]:
25+
def get_lines(command: list[str]) -> list[str]:
2626
"""Run a command and return lines of output
2727
2828
:param str command: the command to run
@@ -37,7 +37,7 @@ def git_hook(
3737
modify: bool = False,
3838
lazy: bool = False,
3939
settings_file: str = "",
40-
directories: Optional[List[str]] = None,
40+
directories: Optional[list[str]] = None,
4141
) -> int:
4242
"""Git pre-commit hook to check staged files for isort errors
4343

isort/identify.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,17 @@
22
Eventually this will likely replace parse.py
33
"""
44

5+
from collections.abc import Iterator
56
from functools import partial
67
from pathlib import Path
7-
from typing import Iterator, NamedTuple, Optional, TextIO, Tuple
8+
from typing import NamedTuple, Optional, TextIO
89

910
from isort.parse import normalize_line, skip_line, strip_syntax
1011

1112
from .comments import parse as parse_comments
1213
from .settings import DEFAULT_CONFIG, Config
1314

14-
STATEMENT_DECLARATIONS: Tuple[str, ...] = ("def ", "cdef ", "cpdef ", "class ", "@", "async def")
15+
STATEMENT_DECLARATIONS: tuple[str, ...] = ("def ", "cdef ", "cpdef ", "class ", "@", "async def")
1516

1617

1718
class Import(NamedTuple):

isort/io.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
import dataclasses
44
import re
55
import tokenize
6+
from collections.abc import Iterator
67
from contextlib import contextmanager
78
from io import BytesIO, StringIO, TextIOWrapper
89
from pathlib import Path
9-
from typing import Any, Callable, Iterator, TextIO, Union
10+
from typing import Any, Callable, TextIO, Union
1011

1112
from isort.exceptions import UnsupportedEncoding
1213

isort/literal.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import ast
22
from pprint import PrettyPrinter
3-
from typing import Any, Callable, Dict, List, Set, Tuple
3+
from typing import Any, Callable
44

55
from isort.exceptions import (
66
AssignmentsFormatMismatch,
@@ -17,7 +17,7 @@ def __init__(self, config: Config):
1717
super().__init__(width=config.line_length, compact=True)
1818

1919

20-
type_mapping: Dict[str, Tuple[type, Callable[[Any, ISortPrettyPrinter], str]]] = {}
20+
type_mapping: dict[str, tuple[type, Callable[[Any, ISortPrettyPrinter], str]]] = {}
2121

2222

2323
def assignments(code: str) -> str:
@@ -85,30 +85,30 @@ def wrap(
8585

8686

8787
@register_type("dict", dict)
88-
def _dict(value: Dict[Any, Any], printer: ISortPrettyPrinter) -> str:
88+
def _dict(value: dict[Any, Any], printer: ISortPrettyPrinter) -> str:
8989
return printer.pformat(dict(sorted(value.items(), key=lambda item: item[1])))
9090

9191

9292
@register_type("list", list)
93-
def _list(value: List[Any], printer: ISortPrettyPrinter) -> str:
93+
def _list(value: list[Any], printer: ISortPrettyPrinter) -> str:
9494
return printer.pformat(sorted(value))
9595

9696

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

101101

102102
@register_type("set", set)
103-
def _set(value: Set[Any], printer: ISortPrettyPrinter) -> str:
103+
def _set(value: set[Any], printer: ISortPrettyPrinter) -> str:
104104
return "{" + printer.pformat(tuple(sorted(value)))[1:-1] + "}"
105105

106106

107107
@register_type("tuple", tuple)
108-
def _tuple(value: Tuple[Any, ...], printer: ISortPrettyPrinter) -> str:
108+
def _tuple(value: tuple[Any, ...], printer: ISortPrettyPrinter) -> str:
109109
return printer.pformat(tuple(sorted(value)))
110110

111111

112112
@register_type("unique-tuple", tuple)
113-
def _unique_tuple(value: Tuple[Any, ...], printer: ISortPrettyPrinter) -> str:
113+
def _unique_tuple(value: tuple[Any, ...], printer: ISortPrettyPrinter) -> str:
114114
return printer.pformat(tuple(sorted(set(value))))

0 commit comments

Comments
 (0)