Skip to content

Commit 8fb2add

Browse files
authored
Use builtin generics (#4458)
uvx ruff check --output-format concise src --target-version py39 --select UP006 --fix --unsafe-fixes uvx ruff check --output-format concise src --target-version py39 --select F401 --fix plus some manual fixups
1 parent 2a45cec commit 8fb2add

27 files changed

+298
-377
lines changed

src/black/__init__.py

+34-38
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,13 @@
1414
from typing import (
1515
Any,
1616
Collection,
17-
Dict,
1817
Generator,
1918
Iterator,
20-
List,
2119
MutableMapping,
2220
Optional,
2321
Pattern,
2422
Sequence,
25-
Set,
2623
Sized,
27-
Tuple,
2824
Union,
2925
)
3026

@@ -176,7 +172,7 @@ def read_pyproject_toml(
176172
"line-ranges", "Cannot use line-ranges in the pyproject.toml file."
177173
)
178174

179-
default_map: Dict[str, Any] = {}
175+
default_map: dict[str, Any] = {}
180176
if ctx.default_map:
181177
default_map.update(ctx.default_map)
182178
default_map.update(config)
@@ -186,9 +182,9 @@ def read_pyproject_toml(
186182

187183

188184
def spellcheck_pyproject_toml_keys(
189-
ctx: click.Context, config_keys: List[str], config_file_path: str
185+
ctx: click.Context, config_keys: list[str], config_file_path: str
190186
) -> None:
191-
invalid_keys: List[str] = []
187+
invalid_keys: list[str] = []
192188
available_config_options = {param.name for param in ctx.command.params}
193189
for key in config_keys:
194190
if key not in available_config_options:
@@ -202,8 +198,8 @@ def spellcheck_pyproject_toml_keys(
202198

203199

204200
def target_version_option_callback(
205-
c: click.Context, p: Union[click.Option, click.Parameter], v: Tuple[str, ...]
206-
) -> List[TargetVersion]:
201+
c: click.Context, p: Union[click.Option, click.Parameter], v: tuple[str, ...]
202+
) -> list[TargetVersion]:
207203
"""Compute the target versions from a --target-version flag.
208204
209205
This is its own function because mypy couldn't infer the type correctly
@@ -213,8 +209,8 @@ def target_version_option_callback(
213209

214210

215211
def enable_unstable_feature_callback(
216-
c: click.Context, p: Union[click.Option, click.Parameter], v: Tuple[str, ...]
217-
) -> List[Preview]:
212+
c: click.Context, p: Union[click.Option, click.Parameter], v: tuple[str, ...]
213+
) -> list[Preview]:
218214
"""Compute the features from an --enable-unstable-feature flag."""
219215
return [Preview[val] for val in v]
220216

@@ -519,7 +515,7 @@ def main( # noqa: C901
519515
ctx: click.Context,
520516
code: Optional[str],
521517
line_length: int,
522-
target_version: List[TargetVersion],
518+
target_version: list[TargetVersion],
523519
check: bool,
524520
diff: bool,
525521
line_ranges: Sequence[str],
@@ -533,7 +529,7 @@ def main( # noqa: C901
533529
skip_magic_trailing_comma: bool,
534530
preview: bool,
535531
unstable: bool,
536-
enable_unstable_feature: List[Preview],
532+
enable_unstable_feature: list[Preview],
537533
quiet: bool,
538534
verbose: bool,
539535
required_version: Optional[str],
@@ -543,7 +539,7 @@ def main( # noqa: C901
543539
force_exclude: Optional[Pattern[str]],
544540
stdin_filename: Optional[str],
545541
workers: Optional[int],
546-
src: Tuple[str, ...],
542+
src: tuple[str, ...],
547543
config: Optional[str],
548544
) -> None:
549545
"""The uncompromising code formatter."""
@@ -643,7 +639,7 @@ def main( # noqa: C901
643639
enabled_features=set(enable_unstable_feature),
644640
)
645641

646-
lines: List[Tuple[int, int]] = []
642+
lines: list[tuple[int, int]] = []
647643
if line_ranges:
648644
if ipynb:
649645
err("Cannot use --line-ranges with ipynb files.")
@@ -733,7 +729,7 @@ def main( # noqa: C901
733729
def get_sources(
734730
*,
735731
root: Path,
736-
src: Tuple[str, ...],
732+
src: tuple[str, ...],
737733
quiet: bool,
738734
verbose: bool,
739735
include: Pattern[str],
@@ -742,14 +738,14 @@ def get_sources(
742738
force_exclude: Optional[Pattern[str]],
743739
report: "Report",
744740
stdin_filename: Optional[str],
745-
) -> Set[Path]:
741+
) -> set[Path]:
746742
"""Compute the set of files to be formatted."""
747-
sources: Set[Path] = set()
743+
sources: set[Path] = set()
748744

749745
assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
750746
using_default_exclude = exclude is None
751747
exclude = re_compile_maybe_verbose(DEFAULT_EXCLUDES) if exclude is None else exclude
752-
gitignore: Optional[Dict[Path, PathSpec]] = None
748+
gitignore: Optional[dict[Path, PathSpec]] = None
753749
root_gitignore = get_gitignore(root)
754750

755751
for s in src:
@@ -841,7 +837,7 @@ def reformat_code(
841837
mode: Mode,
842838
report: Report,
843839
*,
844-
lines: Collection[Tuple[int, int]] = (),
840+
lines: Collection[tuple[int, int]] = (),
845841
) -> None:
846842
"""
847843
Reformat and print out `content` without spawning child processes.
@@ -874,7 +870,7 @@ def reformat_one(
874870
mode: Mode,
875871
report: "Report",
876872
*,
877-
lines: Collection[Tuple[int, int]] = (),
873+
lines: Collection[tuple[int, int]] = (),
878874
) -> None:
879875
"""Reformat a single file under `src` without spawning child processes.
880876
@@ -930,7 +926,7 @@ def format_file_in_place(
930926
write_back: WriteBack = WriteBack.NO,
931927
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
932928
*,
933-
lines: Collection[Tuple[int, int]] = (),
929+
lines: Collection[tuple[int, int]] = (),
934930
) -> bool:
935931
"""Format file under `src` path. Return True if changed.
936932
@@ -997,7 +993,7 @@ def format_stdin_to_stdout(
997993
content: Optional[str] = None,
998994
write_back: WriteBack = WriteBack.NO,
999995
mode: Mode,
1000-
lines: Collection[Tuple[int, int]] = (),
996+
lines: Collection[tuple[int, int]] = (),
1001997
) -> bool:
1002998
"""Format file on stdin. Return True if changed.
1003999
@@ -1048,7 +1044,7 @@ def check_stability_and_equivalence(
10481044
dst_contents: str,
10491045
*,
10501046
mode: Mode,
1051-
lines: Collection[Tuple[int, int]] = (),
1047+
lines: Collection[tuple[int, int]] = (),
10521048
) -> None:
10531049
"""Perform stability and equivalence checks.
10541050
@@ -1065,7 +1061,7 @@ def format_file_contents(
10651061
*,
10661062
fast: bool,
10671063
mode: Mode,
1068-
lines: Collection[Tuple[int, int]] = (),
1064+
lines: Collection[tuple[int, int]] = (),
10691065
) -> FileContent:
10701066
"""Reformat contents of a file and return new contents.
10711067
@@ -1196,7 +1192,7 @@ def format_ipynb_string(src_contents: str, *, fast: bool, mode: Mode) -> FileCon
11961192

11971193

11981194
def format_str(
1199-
src_contents: str, *, mode: Mode, lines: Collection[Tuple[int, int]] = ()
1195+
src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()
12001196
) -> str:
12011197
"""Reformat a string and return new contents.
12021198
@@ -1243,10 +1239,10 @@ def f(
12431239

12441240

12451241
def _format_str_once(
1246-
src_contents: str, *, mode: Mode, lines: Collection[Tuple[int, int]] = ()
1242+
src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()
12471243
) -> str:
12481244
src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
1249-
dst_blocks: List[LinesBlock] = []
1245+
dst_blocks: list[LinesBlock] = []
12501246
if mode.target_versions:
12511247
versions = mode.target_versions
12521248
else:
@@ -1296,7 +1292,7 @@ def _format_str_once(
12961292
return "".join(dst_contents)
12971293

12981294

1299-
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
1295+
def decode_bytes(src: bytes) -> tuple[FileContent, Encoding, NewLine]:
13001296
"""Return a tuple of (decoded_contents, encoding, newline).
13011297
13021298
`newline` is either CRLF or LF but `decoded_contents` is decoded with
@@ -1314,8 +1310,8 @@ def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
13141310

13151311

13161312
def get_features_used( # noqa: C901
1317-
node: Node, *, future_imports: Optional[Set[str]] = None
1318-
) -> Set[Feature]:
1313+
node: Node, *, future_imports: Optional[set[str]] = None
1314+
) -> set[Feature]:
13191315
"""Return a set of (relatively) new Python features used in this file.
13201316
13211317
Currently looking for:
@@ -1333,7 +1329,7 @@ def get_features_used( # noqa: C901
13331329
- except* clause;
13341330
- variadic generics;
13351331
"""
1336-
features: Set[Feature] = set()
1332+
features: set[Feature] = set()
13371333
if future_imports:
13381334
features |= {
13391335
FUTURE_FLAG_TO_FEATURE[future_import]
@@ -1471,20 +1467,20 @@ def _contains_asexpr(node: Union[Node, Leaf]) -> bool:
14711467

14721468

14731469
def detect_target_versions(
1474-
node: Node, *, future_imports: Optional[Set[str]] = None
1475-
) -> Set[TargetVersion]:
1470+
node: Node, *, future_imports: Optional[set[str]] = None
1471+
) -> set[TargetVersion]:
14761472
"""Detect the version to target based on the nodes used."""
14771473
features = get_features_used(node, future_imports=future_imports)
14781474
return {
14791475
version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
14801476
}
14811477

14821478

1483-
def get_future_imports(node: Node) -> Set[str]:
1479+
def get_future_imports(node: Node) -> set[str]:
14841480
"""Return a set of __future__ imports in the file."""
1485-
imports: Set[str] = set()
1481+
imports: set[str] = set()
14861482

1487-
def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
1483+
def get_imports_from_children(children: list[LN]) -> Generator[str, None, None]:
14881484
for child in children:
14891485
if isinstance(child, Leaf):
14901486
if child.type == token.NAME:
@@ -1571,7 +1567,7 @@ def assert_equivalent(src: str, dst: str) -> None:
15711567

15721568

15731569
def assert_stable(
1574-
src: str, dst: str, mode: Mode, *, lines: Collection[Tuple[int, int]] = ()
1570+
src: str, dst: str, mode: Mode, *, lines: Collection[tuple[int, int]] = ()
15751571
) -> None:
15761572
"""Raise AssertionError if `dst` reformats differently the second time."""
15771573
if lines:

src/black/_width_table.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
# Generated by make_width_table.py
22
# wcwidth 0.2.6
33
# Unicode 15.0.0
4-
from typing import Final, List, Tuple
4+
from typing import Final
55

6-
WIDTH_TABLE: Final[List[Tuple[int, int, int]]] = [
6+
WIDTH_TABLE: Final[list[tuple[int, int, int]]] = [
77
(0, 0, 0),
88
(1, 31, -1),
99
(127, 159, -1),

src/black/brackets.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Builds on top of nodes.py to track brackets."""
22

33
from dataclasses import dataclass, field
4-
from typing import Dict, Final, Iterable, List, Optional, Sequence, Set, Tuple, Union
4+
from typing import Final, Iterable, Optional, Sequence, Union
55

66
from black.nodes import (
77
BRACKET,
@@ -60,12 +60,12 @@ class BracketTracker:
6060
"""Keeps track of brackets on a line."""
6161

6262
depth: int = 0
63-
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = field(default_factory=dict)
64-
delimiters: Dict[LeafID, Priority] = field(default_factory=dict)
63+
bracket_match: dict[tuple[Depth, NodeType], Leaf] = field(default_factory=dict)
64+
delimiters: dict[LeafID, Priority] = field(default_factory=dict)
6565
previous: Optional[Leaf] = None
66-
_for_loop_depths: List[int] = field(default_factory=list)
67-
_lambda_argument_depths: List[int] = field(default_factory=list)
68-
invisible: List[Leaf] = field(default_factory=list)
66+
_for_loop_depths: list[int] = field(default_factory=list)
67+
_lambda_argument_depths: list[int] = field(default_factory=list)
68+
invisible: list[Leaf] = field(default_factory=list)
6969

7070
def mark(self, leaf: Leaf) -> None:
7171
"""Mark `leaf` with bracket-related metadata. Keep track of delimiters.
@@ -353,7 +353,7 @@ def max_delimiter_priority_in_atom(node: LN) -> Priority:
353353
return 0
354354

355355

356-
def get_leaves_inside_matching_brackets(leaves: Sequence[Leaf]) -> Set[LeafID]:
356+
def get_leaves_inside_matching_brackets(leaves: Sequence[Leaf]) -> set[LeafID]:
357357
"""Return leaves that are inside matching brackets.
358358
359359
The input `leaves` can have non-matching brackets at the head or tail parts.

src/black/cache.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import tempfile
88
from dataclasses import dataclass, field
99
from pathlib import Path
10-
from typing import Dict, Iterable, NamedTuple, Set, Tuple
10+
from typing import Iterable, NamedTuple
1111

1212
from platformdirs import user_cache_dir
1313

@@ -55,7 +55,7 @@ def get_cache_file(mode: Mode) -> Path:
5555
class Cache:
5656
mode: Mode
5757
cache_file: Path
58-
file_data: Dict[str, FileData] = field(default_factory=dict)
58+
file_data: dict[str, FileData] = field(default_factory=dict)
5959

6060
@classmethod
6161
def read(cls, mode: Mode) -> Self:
@@ -76,7 +76,7 @@ def read(cls, mode: Mode) -> Self:
7676

7777
with cache_file.open("rb") as fobj:
7878
try:
79-
data: Dict[str, Tuple[float, int, str]] = pickle.load(fobj)
79+
data: dict[str, tuple[float, int, str]] = pickle.load(fobj)
8080
file_data = {k: FileData(*v) for k, v in data.items()}
8181
except (pickle.UnpicklingError, ValueError, IndexError):
8282
return cls(mode, cache_file)
@@ -114,14 +114,14 @@ def is_changed(self, source: Path) -> bool:
114114
return True
115115
return False
116116

117-
def filtered_cached(self, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
117+
def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]:
118118
"""Split an iterable of paths in `sources` into two sets.
119119
120120
The first contains paths of files that modified on disk or are not in the
121121
cache. The other contains paths to non-modified files.
122122
"""
123-
changed: Set[Path] = set()
124-
done: Set[Path] = set()
123+
changed: set[Path] = set()
124+
done: set[Path] = set()
125125
for src in sources:
126126
if self.is_changed(src):
127127
changed.add(src)
@@ -140,7 +140,7 @@ def write(self, sources: Iterable[Path]) -> None:
140140
dir=str(self.cache_file.parent), delete=False
141141
) as f:
142142
# We store raw tuples in the cache because it's faster.
143-
data: Dict[str, Tuple[float, int, str]] = {
143+
data: dict[str, tuple[float, int, str]] = {
144144
k: (*v,) for k, v in self.file_data.items()
145145
}
146146
pickle.dump(data, f, protocol=4)

0 commit comments

Comments
 (0)