Replace remaining aliases to built-in types (#4485)

This commit is contained in:
Matej Aleksandrov 2024-10-15 01:37:58 +02:00 committed by GitHub
parent fff747d61b
commit 484a669699
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 51 additions and 68 deletions

View File

@ -10,7 +10,7 @@
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache, partial from functools import lru_cache, partial
from pathlib import Path from pathlib import Path
from typing import Generator, List, NamedTuple, Optional, Tuple, Union, cast from typing import Generator, NamedTuple, Optional, Union, cast
from urllib.request import urlopen, urlretrieve from urllib.request import urlopen, urlretrieve
PYPI_INSTANCE = "https://pypi.org/pypi" PYPI_INSTANCE = "https://pypi.org/pypi"
@ -54,7 +54,7 @@ def get_pypi_download_url(package: str, version: Optional[str]) -> str:
return cast(str, source["url"]) return cast(str, source["url"])
def get_top_packages() -> List[str]: def get_top_packages() -> list[str]:
with urlopen(PYPI_TOP_PACKAGES) as page: with urlopen(PYPI_TOP_PACKAGES) as page:
result = json.load(page) result = json.load(page)
@ -150,7 +150,7 @@ def git_switch_branch(
subprocess.run(args, cwd=repo) subprocess.run(args, cwd=repo)
def init_repos(options: Namespace) -> Tuple[Path, ...]: def init_repos(options: Namespace) -> tuple[Path, ...]:
options.output.mkdir(exist_ok=True) options.output.mkdir(exist_ok=True)
if options.top_packages: if options.top_packages:
@ -206,7 +206,7 @@ def format_repo_with_version(
git_switch_branch(black_version.version, repo=black_repo) git_switch_branch(black_version.version, repo=black_repo)
git_switch_branch(current_branch, repo=repo, new=True, from_branch=from_branch) git_switch_branch(current_branch, repo=repo, new=True, from_branch=from_branch)
format_cmd: List[Union[Path, str]] = [ format_cmd: list[Union[Path, str]] = [
black_runner(black_version.version, black_repo), black_runner(black_version.version, black_repo),
(black_repo / "black.py").resolve(), (black_repo / "black.py").resolve(),
".", ".",
@ -222,7 +222,7 @@ def format_repo_with_version(
return current_branch return current_branch
def format_repos(repos: Tuple[Path, ...], options: Namespace) -> None: def format_repos(repos: tuple[Path, ...], options: Namespace) -> None:
black_versions = tuple( black_versions = tuple(
BlackVersion(*version.split(":")) for version in options.versions BlackVersion(*version.split(":")) for version in options.versions
) )

View File

@ -18,12 +18,12 @@
import sys import sys
from os.path import basename, dirname, join from os.path import basename, dirname, join
from typing import Iterable, Tuple from typing import Iterable
import wcwidth # type: ignore[import-not-found] import wcwidth # type: ignore[import-not-found]
def make_width_table() -> Iterable[Tuple[int, int, int]]: def make_width_table() -> Iterable[tuple[int, int, int]]:
start_codepoint = -1 start_codepoint = -1
end_codepoint = -1 end_codepoint = -1
range_width = -2 range_width = -2
@ -53,9 +53,9 @@ def main() -> None:
f.write(f"""# Generated by {basename(__file__)} f.write(f"""# Generated by {basename(__file__)}
# wcwidth {wcwidth.__version__} # wcwidth {wcwidth.__version__}
# Unicode {wcwidth.list_versions()[-1]} # Unicode {wcwidth.list_versions()[-1]}
from typing import Final, List, Tuple from typing import Final
WIDTH_TABLE: Final[List[Tuple[int, int, int]]] = [ WIDTH_TABLE: Final[list[tuple[int, int, int]]] = [
""") """)
for triple in make_width_table(): for triple in make_width_table():
f.write(f" {triple!r},\n") f.write(f" {triple!r},\n")

View File

@ -18,7 +18,7 @@
import logging import logging
import re import re
from functools import lru_cache from functools import lru_cache
from typing import TYPE_CHECKING, FrozenSet, List, Set from typing import TYPE_CHECKING
import pytest import pytest
@ -46,8 +46,8 @@
from _pytest.nodes import Node from _pytest.nodes import Node
ALL_POSSIBLE_OPTIONAL_MARKERS = StashKey[FrozenSet[str]]() ALL_POSSIBLE_OPTIONAL_MARKERS = StashKey[frozenset[str]]()
ENABLED_OPTIONAL_MARKERS = StashKey[FrozenSet[str]]() ENABLED_OPTIONAL_MARKERS = StashKey[frozenset[str]]()
def pytest_addoption(parser: "Parser") -> None: def pytest_addoption(parser: "Parser") -> None:
@ -69,7 +69,7 @@ def pytest_configure(config: "Config") -> None:
""" """
ot_ini = config.inicfg.get("optional-tests") or [] ot_ini = config.inicfg.get("optional-tests") or []
ot_markers = set() ot_markers = set()
ot_run: Set[str] = set() ot_run: set[str] = set()
if isinstance(ot_ini, str): if isinstance(ot_ini, str):
ot_ini = ot_ini.strip().split("\n") ot_ini = ot_ini.strip().split("\n")
marker_re = re.compile(r"^\s*(?P<no>no_)?(?P<marker>\w+)(:\s*(?P<description>.*))?") marker_re = re.compile(r"^\s*(?P<no>no_)?(?P<marker>\w+)(:\s*(?P<description>.*))?")
@ -103,7 +103,7 @@ def pytest_configure(config: "Config") -> None:
store[ENABLED_OPTIONAL_MARKERS] = frozenset(ot_run) store[ENABLED_OPTIONAL_MARKERS] = frozenset(ot_run)
def pytest_collection_modifyitems(config: "Config", items: "List[Node]") -> None: def pytest_collection_modifyitems(config: "Config", items: "list[Node]") -> None:
store = config._store store = config._store
all_possible_optional_markers = store[ALL_POSSIBLE_OPTIONAL_MARKERS] all_possible_optional_markers = store[ALL_POSSIBLE_OPTIONAL_MARKERS]
enabled_optional_markers = store[ENABLED_OPTIONAL_MARKERS] enabled_optional_markers = store[ENABLED_OPTIONAL_MARKERS]
@ -120,7 +120,7 @@ def pytest_collection_modifyitems(config: "Config", items: "List[Node]") -> None
@lru_cache @lru_cache
def skip_mark(tests: FrozenSet[str]) -> "MarkDecorator": def skip_mark(tests: frozenset[str]) -> "MarkDecorator":
names = ", ".join(sorted(tests)) names = ", ".join(sorted(tests))
return pytest.mark.skip(reason=f"Marked with disabled optional tests ({names})") return pytest.mark.skip(reason=f"Marked with disabled optional tests ({names})")

View File

@ -17,19 +17,7 @@
from pathlib import Path, WindowsPath from pathlib import Path, WindowsPath
from platform import system from platform import system
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from typing import ( from typing import Any, Callable, Iterator, Optional, Sequence, TypeVar, Union
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Set,
Type,
TypeVar,
Union,
)
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import click import click
@ -107,11 +95,11 @@ class FakeContext(click.Context):
"""A fake click Context for when calling functions that need it.""" """A fake click Context for when calling functions that need it."""
def __init__(self) -> None: def __init__(self) -> None:
self.default_map: Dict[str, Any] = {} self.default_map: dict[str, Any] = {}
self.params: Dict[str, Any] = {} self.params: dict[str, Any] = {}
self.command: click.Command = black.main self.command: click.Command = black.main
# Dummy root, since most of the tests don't care about it # Dummy root, since most of the tests don't care about it
self.obj: Dict[str, Any] = {"root": PROJECT_ROOT} self.obj: dict[str, Any] = {"root": PROJECT_ROOT}
class FakeParameter(click.Parameter): class FakeParameter(click.Parameter):
@ -129,7 +117,7 @@ def __init__(self) -> None:
def invokeBlack( def invokeBlack(
args: List[str], exit_code: int = 0, ignore_config: bool = True args: list[str], exit_code: int = 0, ignore_config: bool = True
) -> None: ) -> None:
runner = BlackRunner() runner = BlackRunner()
if ignore_config: if ignore_config:
@ -933,7 +921,7 @@ def test_get_features_used(self) -> None:
"with ((a, ((b as c)))): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS} "with ((a, ((b as c)))): pass", {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
) )
def check_features_used(self, source: str, expected: Set[Feature]) -> None: def check_features_used(self, source: str, expected: set[Feature]) -> None:
node = black.lib2to3_parse(source) node = black.lib2to3_parse(source)
actual = black.get_features_used(node) actual = black.get_features_used(node)
msg = f"Expected {expected} but got {actual} for {source!r}" msg = f"Expected {expected} but got {actual} for {source!r}"
@ -1365,7 +1353,7 @@ def test_reformat_one_with_stdin_empty(self) -> None:
] ]
def _new_wrapper( def _new_wrapper(
output: io.StringIO, io_TextIOWrapper: Type[io.TextIOWrapper] output: io.StringIO, io_TextIOWrapper: type[io.TextIOWrapper]
) -> Callable[[Any, Any], io.TextIOWrapper]: ) -> Callable[[Any, Any], io.TextIOWrapper]:
def get_output(*args: Any, **kwargs: Any) -> io.TextIOWrapper: def get_output(*args: Any, **kwargs: Any) -> io.TextIOWrapper:
if args == (sys.stdout.buffer,): if args == (sys.stdout.buffer,):
@ -2350,7 +2338,7 @@ def test_read_cache_line_lengths(self) -> None:
def test_cache_key(self) -> None: def test_cache_key(self) -> None:
# Test that all members of the mode enum affect the cache key. # Test that all members of the mode enum affect the cache key.
for field in fields(Mode): for field in fields(Mode):
values: List[Any] values: list[Any]
if field.name == "target_versions": if field.name == "target_versions":
values = [ values = [
{TargetVersion.PY312}, {TargetVersion.PY312},
@ -2463,7 +2451,7 @@ def test_gitignore_exclude(self) -> None:
gitignore = PathSpec.from_lines( gitignore = PathSpec.from_lines(
"gitwildmatch", ["exclude/", ".definitely_exclude"] "gitwildmatch", ["exclude/", ".definitely_exclude"]
) )
sources: List[Path] = [] sources: list[Path] = []
expected = [ expected = [
Path(path / "b/dont_exclude/a.py"), Path(path / "b/dont_exclude/a.py"),
Path(path / "b/dont_exclude/a.pyi"), Path(path / "b/dont_exclude/a.pyi"),
@ -2491,7 +2479,7 @@ def test_nested_gitignore(self) -> None:
exclude = re.compile(r"") exclude = re.compile(r"")
root_gitignore = black.files.get_gitignore(path) root_gitignore = black.files.get_gitignore(path)
report = black.Report() report = black.Report()
expected: List[Path] = [ expected: list[Path] = [
Path(path / "x.py"), Path(path / "x.py"),
Path(path / "root/b.py"), Path(path / "root/b.py"),
Path(path / "root/c.py"), Path(path / "root/c.py"),

View File

@ -7,7 +7,7 @@
import re import re
from itertools import islice from itertools import islice
from pathlib import Path from pathlib import Path
from typing import Optional, Sequence, Set from typing import Optional, Sequence
import pytest import pytest
@ -17,7 +17,7 @@
def check_feature_list( def check_feature_list(
lines: Sequence[str], expected_feature_names: Set[str], label: str lines: Sequence[str], expected_feature_names: set[str], label: str
) -> Optional[str]: ) -> Optional[str]:
start_index = lines.index(f"(labels/{label}-features)=\n") start_index = lines.index(f"(labels/{label}-features)=\n")
if start_index == -1: if start_index == -1:

View File

@ -1,7 +1,5 @@
"""Test the black.ranges module.""" """Test the black.ranges module."""
from typing import List, Tuple
import pytest import pytest
from black.ranges import adjusted_lines, sanitized_lines from black.ranges import adjusted_lines, sanitized_lines
@ -11,7 +9,7 @@
"lines", "lines",
[[(1, 1)], [(1, 3)], [(1, 1), (3, 4)]], [[(1, 1)], [(1, 3)], [(1, 1), (3, 4)]],
) )
def test_no_diff(lines: List[Tuple[int, int]]) -> None: def test_no_diff(lines: list[tuple[int, int]]) -> None:
source = """\ source = """\
import re import re
@ -32,7 +30,7 @@ def func():
[(0, 8), (3, 1)], [(0, 8), (3, 1)],
], ],
) )
def test_invalid_lines(lines: List[Tuple[int, int]]) -> None: def test_invalid_lines(lines: list[tuple[int, int]]) -> None:
original_source = """\ original_source = """\
import re import re
def foo(arg): def foo(arg):
@ -83,7 +81,7 @@ def func(arg1, arg2, arg3):
], ],
) )
def test_removals( def test_removals(
lines: List[Tuple[int, int]], adjusted: List[Tuple[int, int]] lines: list[tuple[int, int]], adjusted: list[tuple[int, int]]
) -> None: ) -> None:
original_source = """\ original_source = """\
1. first line 1. first line
@ -118,7 +116,7 @@ def test_removals(
], ],
) )
def test_additions( def test_additions(
lines: List[Tuple[int, int]], adjusted: List[Tuple[int, int]] lines: list[tuple[int, int]], adjusted: list[tuple[int, int]]
) -> None: ) -> None:
original_source = """\ original_source = """\
1. first line 1. first line
@ -154,7 +152,7 @@ def test_additions(
([(9, 10), (1, 1)], [(1, 1), (9, 9)]), ([(9, 10), (1, 1)], [(1, 1), (9, 9)]),
], ],
) )
def test_diffs(lines: List[Tuple[int, int]], adjusted: List[Tuple[int, int]]) -> None: def test_diffs(lines: list[tuple[int, int]], adjusted: list[tuple[int, int]]) -> None:
original_source = """\ original_source = """\
1. import re 1. import re
2. def foo(arg): 2. def foo(arg):
@ -231,7 +229,7 @@ def test_diffs(lines: List[Tuple[int, int]], adjusted: List[Tuple[int, int]]) ->
], ],
) )
def test_sanitize( def test_sanitize(
lines: List[Tuple[int, int]], sanitized: List[Tuple[int, int]] lines: list[tuple[int, int]], sanitized: list[tuple[int, int]]
) -> None: ) -> None:
source = """\ source = """\
1. import re 1. import re

View File

@ -4,7 +4,6 @@
import sys import sys
import textwrap import textwrap
from dataclasses import dataclass from dataclasses import dataclass
from typing import List
import black import black
from blib2to3.pgen2 import token, tokenize from blib2to3.pgen2 import token, tokenize
@ -18,10 +17,10 @@ class Token:
end: tokenize.Coord end: tokenize.Coord
def get_tokens(text: str) -> List[Token]: def get_tokens(text: str) -> list[Token]:
"""Return the tokens produced by the tokenizer.""" """Return the tokens produced by the tokenizer."""
readline = io.StringIO(text).readline readline = io.StringIO(text).readline
tokens: List[Token] = [] tokens: list[Token] = []
def tokeneater( def tokeneater(
type: int, string: str, start: tokenize.Coord, end: tokenize.Coord, line: str type: int, string: str, start: tokenize.Coord, end: tokenize.Coord, line: str
@ -32,7 +31,7 @@ def tokeneater(
return tokens return tokens
def assert_tokenizes(text: str, tokens: List[Token]) -> None: def assert_tokenizes(text: str, tokens: list[Token]) -> None:
"""Assert that the tokenizer produces the expected tokens.""" """Assert that the tokenizer produces the expected tokens."""
actual_tokens = get_tokens(text) actual_tokens = get_tokens(text)
assert actual_tokens == tokens assert actual_tokens == tokens

View File

@ -1,11 +1,9 @@
from typing import List, Tuple
from black.trans import iter_fexpr_spans from black.trans import iter_fexpr_spans
def test_fexpr_spans() -> None: def test_fexpr_spans() -> None:
def check( def check(
string: str, expected_spans: List[Tuple[int, int]], expected_slices: List[str] string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str]
) -> None: ) -> None:
spans = list(iter_fexpr_spans(string)) spans = list(iter_fexpr_spans(string))

View File

@ -8,7 +8,7 @@
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from functools import partial from functools import partial
from pathlib import Path from pathlib import Path
from typing import Any, Collection, Iterator, List, Optional, Tuple from typing import Any, Collection, Iterator, Optional
import black import black
from black.const import DEFAULT_LINE_LENGTH from black.const import DEFAULT_LINE_LENGTH
@ -44,8 +44,8 @@
class TestCaseArgs: class TestCaseArgs:
mode: black.Mode = field(default_factory=black.Mode) mode: black.Mode = field(default_factory=black.Mode)
fast: bool = False fast: bool = False
minimum_version: Optional[Tuple[int, int]] = None minimum_version: Optional[tuple[int, int]] = None
lines: Collection[Tuple[int, int]] = () lines: Collection[tuple[int, int]] = ()
no_preview_line_length_1: bool = False no_preview_line_length_1: bool = False
@ -95,8 +95,8 @@ def assert_format(
mode: black.Mode = DEFAULT_MODE, mode: black.Mode = DEFAULT_MODE,
*, *,
fast: bool = False, fast: bool = False,
minimum_version: Optional[Tuple[int, int]] = None, minimum_version: Optional[tuple[int, int]] = None,
lines: Collection[Tuple[int, int]] = (), lines: Collection[tuple[int, int]] = (),
no_preview_line_length_1: bool = False, no_preview_line_length_1: bool = False,
) -> None: ) -> None:
"""Convenience function to check that Black formats as expected. """Convenience function to check that Black formats as expected.
@ -164,8 +164,8 @@ def _assert_format_inner(
mode: black.Mode = DEFAULT_MODE, mode: black.Mode = DEFAULT_MODE,
*, *,
fast: bool = False, fast: bool = False,
minimum_version: Optional[Tuple[int, int]] = None, minimum_version: Optional[tuple[int, int]] = None,
lines: Collection[Tuple[int, int]] = (), lines: Collection[tuple[int, int]] = (),
) -> None: ) -> None:
actual = black.format_str(source, mode=mode, lines=lines) actual = black.format_str(source, mode=mode, lines=lines)
if expected is not None: if expected is not None:
@ -195,7 +195,7 @@ def get_base_dir(data: bool) -> Path:
return DATA_DIR if data else PROJECT_ROOT return DATA_DIR if data else PROJECT_ROOT
def all_data_cases(subdir_name: str, data: bool = True) -> List[str]: def all_data_cases(subdir_name: str, data: bool = True) -> list[str]:
cases_dir = get_base_dir(data) / subdir_name cases_dir = get_base_dir(data) / subdir_name
assert cases_dir.is_dir() assert cases_dir.is_dir()
return [case_path.stem for case_path in cases_dir.iterdir()] return [case_path.stem for case_path in cases_dir.iterdir()]
@ -214,18 +214,18 @@ def get_case_path(
def read_data_with_mode( def read_data_with_mode(
subdir_name: str, name: str, data: bool = True subdir_name: str, name: str, data: bool = True
) -> Tuple[TestCaseArgs, str, str]: ) -> tuple[TestCaseArgs, str, str]:
"""read_data_with_mode('test_name') -> Mode(), 'input', 'output'""" """read_data_with_mode('test_name') -> Mode(), 'input', 'output'"""
return read_data_from_file(get_case_path(subdir_name, name, data)) return read_data_from_file(get_case_path(subdir_name, name, data))
def read_data(subdir_name: str, name: str, data: bool = True) -> Tuple[str, str]: def read_data(subdir_name: str, name: str, data: bool = True) -> tuple[str, str]:
"""read_data('test_name') -> 'input', 'output'""" """read_data('test_name') -> 'input', 'output'"""
_, input, output = read_data_with_mode(subdir_name, name, data) _, input, output = read_data_with_mode(subdir_name, name, data)
return input, output return input, output
def _parse_minimum_version(version: str) -> Tuple[int, int]: def _parse_minimum_version(version: str) -> tuple[int, int]:
major, minor = version.split(".") major, minor = version.split(".")
return int(major), int(minor) return int(major), int(minor)
@ -302,11 +302,11 @@ def parse_mode(flags_line: str) -> TestCaseArgs:
) )
def read_data_from_file(file_name: Path) -> Tuple[TestCaseArgs, str, str]: def read_data_from_file(file_name: Path) -> tuple[TestCaseArgs, str, str]:
with open(file_name, encoding="utf8") as test: with open(file_name, encoding="utf8") as test:
lines = test.readlines() lines = test.readlines()
_input: List[str] = [] _input: list[str] = []
_output: List[str] = [] _output: list[str] = []
result = _input result = _input
mode = TestCaseArgs() mode = TestCaseArgs()
for line in lines: for line in lines: