Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 36 additions & 36 deletions isort/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from io import StringIO
from itertools import chain
from pathlib import Path
from typing import Any, Optional, TextIO, Union, cast
from typing import Any, TextIO, cast
from warnings import warn

from isort import core
Expand Down Expand Up @@ -69,11 +69,11 @@ class ImportKey(Enum):

def sort_code_string(
code: str,
extension: Optional[str] = None,
extension: str | None = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
file_path: Path | None = None,
disregard_skip: bool = False,
show_diff: Union[bool, TextIO] = False,
show_diff: bool | TextIO = False,
**config_kwargs: Any,
) -> str:
"""Sorts any imports within the provided code string, returning a new string with them sorted.
Expand Down Expand Up @@ -105,10 +105,10 @@ def sort_code_string(

def check_code_string(
code: str,
show_diff: Union[bool, TextIO] = False,
extension: Optional[str] = None,
show_diff: bool | TextIO = False,
extension: str | None = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
file_path: Path | None = None,
disregard_skip: bool = False,
**config_kwargs: Any,
) -> bool:
Expand Down Expand Up @@ -138,11 +138,11 @@ def check_code_string(
def sort_stream(
input_stream: TextIO,
output_stream: TextIO,
extension: Optional[str] = None,
extension: str | None = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
file_path: Path | None = None,
disregard_skip: bool = False,
show_diff: Union[bool, TextIO] = False,
show_diff: bool | TextIO = False,
raise_on_skip: bool = True,
**config_kwargs: Any,
) -> bool:
Expand Down Expand Up @@ -240,10 +240,10 @@ def sort_stream(

def check_stream(
input_stream: TextIO,
show_diff: Union[bool, TextIO] = False,
extension: Optional[str] = None,
show_diff: bool | TextIO = False,
extension: str | None = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
file_path: Path | None = None,
disregard_skip: bool = False,
**config_kwargs: Any,
) -> bool:
Expand Down Expand Up @@ -306,12 +306,12 @@ def check_stream(


def check_file(
filename: Union[str, Path],
show_diff: Union[bool, TextIO] = False,
filename: str | Path,
show_diff: bool | TextIO = False,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
file_path: Path | None = None,
disregard_skip: bool = True,
extension: Optional[str] = None,
extension: str | None = None,
**config_kwargs: Any,
) -> bool:
"""Checks any imports within the provided file, returning `False` if any unsorted or
Expand Down Expand Up @@ -359,7 +359,7 @@ def _in_memory_output_stream_context() -> Iterator[TextIO]:


@contextlib.contextmanager
def _file_output_stream_context(filename: Union[str, Path], source_file: File) -> Iterator[TextIO]:
def _file_output_stream_context(filename: str | Path, source_file: File) -> Iterator[TextIO]:
tmp_file = _tmp_file(source_file)
with tmp_file.open("w+", encoding=source_file.encoding, newline="") as output_stream:
shutil.copymode(filename, tmp_file)
Expand All @@ -370,15 +370,15 @@ def _file_output_stream_context(filename: Union[str, Path], source_file: File) -
# the main entrypoints so sort of expected to be complex.
# skipcq: PY-R1000
def sort_file(
filename: Union[str, Path],
extension: Optional[str] = None,
filename: str | Path,
extension: str | None = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
file_path: Path | None = None,
disregard_skip: bool = True,
ask_to_apply: bool = False,
show_diff: Union[bool, TextIO] = False,
show_diff: bool | TextIO = False,
write_to_stdout: bool = False,
output: Optional[TextIO] = None,
output: TextIO | None = None,
**config_kwargs: Any,
) -> bool:
"""Sorts and formats any groups of imports within the provided file or Path.
Expand Down Expand Up @@ -510,8 +510,8 @@ def sort_file(
def find_imports_in_code(
code: str,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
file_path: Path | None = None,
unique: bool | ImportKey = False,
top_only: bool = False,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
Expand All @@ -537,10 +537,10 @@ def find_imports_in_code(
def find_imports_in_stream(
input_stream: TextIO,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
file_path: Path | None = None,
unique: bool | ImportKey = False,
top_only: bool = False,
_seen: Optional[set[str]] = None,
_seen: set[str] | None = None,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
"""Finds and returns all imports within the provided code stream.
Expand Down Expand Up @@ -577,10 +577,10 @@ def find_imports_in_stream(


def find_imports_in_file(
filename: Union[str, Path],
filename: str | Path,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
file_path: Path | None = None,
unique: bool | ImportKey = False,
top_only: bool = False,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
Expand Down Expand Up @@ -609,10 +609,10 @@ def find_imports_in_file(


def find_imports_in_paths(
paths: Iterator[Union[str, Path]],
paths: Iterator[str | Path],
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
unique: Union[bool, ImportKey] = False,
file_path: Path | None = None,
unique: bool | ImportKey = False,
top_only: bool = False,
**config_kwargs: Any,
) -> Iterator[identify.Import]:
Expand All @@ -627,7 +627,7 @@ def find_imports_in_paths(
- ****config_kwargs**: Any config modifications.
"""
config = _config(config=config, **config_kwargs)
seen: Optional[set[str]] = set() if unique else None
seen: set[str] | None = set() if unique else None
yield from chain(
*(
find_imports_in_file(
Expand All @@ -639,7 +639,7 @@ def find_imports_in_paths(


def _config(
path: Optional[Path] = None, config: Config = DEFAULT_CONFIG, **config_kwargs: Any
path: Path | None = None, config: Config = DEFAULT_CONFIG, **config_kwargs: Any
) -> Config:
if path and (
config is DEFAULT_CONFIG
Expand Down
5 changes: 1 addition & 4 deletions isort/comments.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from typing import Optional


def parse(line: str) -> tuple[str, str]:
"""Parses import lines for comments and returns back the
import statement and the associated comment.
Expand All @@ -13,7 +10,7 @@ def parse(line: str) -> tuple[str, str]:


def add_to_line(
comments: Optional[list[str]],
comments: list[str] | None,
original_string: str = "",
removed: bool = False,
comment_prefix: str = "",
Expand Down
4 changes: 2 additions & 2 deletions isort/core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import textwrap
from io import StringIO
from itertools import chain
from typing import TextIO, Union
from typing import TextIO

import isort.literal
from isort.settings import DEFAULT_CONFIG, Config
Expand Down Expand Up @@ -67,7 +67,7 @@ def process(
indent: str = ""
isort_off: bool = False
skip_file: bool = False
code_sorting: Union[bool, str] = False
code_sorting: bool | str = False
code_sorting_section: str = ""
code_sorting_indent: str = ""
cimports: bool = False
Expand Down
21 changes: 10 additions & 11 deletions isort/deprecated/finders.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from glob import glob
from pathlib import Path
from re import Pattern
from typing import Optional

from isort import sections
from isort.settings import KNOWN_SECTION_MAPPING, Config
Expand Down Expand Up @@ -50,12 +49,12 @@ def __init__(self, config: Config) -> None:
self.config = config

@abstractmethod
def find(self, module_name: str) -> Optional[str]:
def find(self, module_name: str) -> str | None:
raise NotImplementedError


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


class LocalFinder(BaseFinder):
def find(self, module_name: str) -> Optional[str]:
def find(self, module_name: str) -> str | None:
if module_name.startswith("."):
return "LOCALFOLDER"
return None
Expand Down Expand Up @@ -107,7 +106,7 @@ def _parse_known_pattern(self, pattern: str) -> list[str]:

return patterns

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

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

@staticmethod
def _load_mapping() -> Optional[dict[str, str]]:
def _load_mapping() -> dict[str, str] | None:
"""Return list of mappings `package_name -> module_name`

Example:
Expand Down Expand Up @@ -272,7 +271,7 @@ def _normalize_name(self, name: str) -> str:
name = self.mapping.get(name.replace("-", "_"), name)
return name.lower().replace("-", "_")

def find(self, module_name: str) -> Optional[str]:
def find(self, module_name: str) -> str | None:
# required lib not installed yet
if not self.enabled:
return None
Expand Down Expand Up @@ -342,7 +341,7 @@ def _get_names_cached(cls, path: str) -> list[str]:


class DefaultFinder(BaseFinder):
def find(self, module_name: str) -> Optional[str]:
def find(self, module_name: str) -> str | None:
return self.config.default_section


Expand All @@ -357,7 +356,7 @@ class FindersManager:
)

def __init__(
self, config: Config, finder_classes: Optional[Iterable[type[BaseFinder]]] = None
self, config: Config, finder_classes: Iterable[type[BaseFinder]] | None = None
) -> None:
self.verbose: bool = config.verbose

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

def find(self, module_name: str) -> Optional[str]:
def find(self, module_name: str) -> str | None:
for finder in self.finders:
try:
section = finder.find(module_name)
Expand Down
6 changes: 3 additions & 3 deletions isort/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from functools import partial
from pathlib import Path
from typing import Any, Union
from typing import Any

from .profiles import profiles

Expand Down Expand Up @@ -113,7 +113,7 @@ class LiteralParsingFailure(ISortError):
the given data structure.
"""

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

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

Expand Down
14 changes: 7 additions & 7 deletions isort/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from datetime import datetime
from difflib import unified_diff
from pathlib import Path
from typing import Optional, TextIO
from typing import TextIO

try:
import colorama
Expand Down Expand Up @@ -44,8 +44,8 @@ def show_unified_diff(
*,
file_input: str,
file_output: str,
file_path: Optional[Path],
output: Optional[TextIO] = None,
file_path: Path | None,
output: TextIO | None = None,
color_output: bool = False,
) -> None:
"""Shows a unified_diff for the provided input and output against the provided file path.
Expand Down Expand Up @@ -94,7 +94,7 @@ class BasicPrinter:
ERROR = "ERROR"
SUCCESS = "SUCCESS"

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


class ColoramaPrinter(BasicPrinter):
def __init__(self, error: str, success: str, output: Optional[TextIO]):
def __init__(self, error: str, success: str, output: TextIO | None):
super().__init__(error, success, output=output)

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

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


def create_terminal_printer(
color: bool, output: Optional[TextIO] = None, error: str = "", success: str = ""
color: bool, output: TextIO | None = None, error: str = "", success: str = ""
) -> BasicPrinter:
if color and colorama_unavailable:
no_colorama_message = (
Expand Down
Loading