Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b6fd98d

Browse files
committed
pyupgrade --py310 except not profiling/ or tests/data/
1 parent bb142e7 commit b6fd98d

25 files changed

Lines changed: 196 additions & 204 deletions

action/main.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import sys
66
from pathlib import Path
77
from subprocess import PIPE, STDOUT, run
8-
from typing import Union
98

109
ACTION_PATH = Path(os.environ["GITHUB_ACTION_PATH"])
1110
ENV_PATH = ACTION_PATH / ".black-env"
@@ -95,7 +94,7 @@ def read_version_specifier_from_pyproject() -> str:
9594
return version
9695

9796

98-
def find_black_version_in_array(array: object) -> Union[str, None]:
97+
def find_black_version_in_array(array: object) -> str | None:
9998
if not isinstance(array, list):
10099
return None
101100
try:

gallery/gallery.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from concurrent.futures import ThreadPoolExecutor
1212
from functools import lru_cache, partial
1313
from pathlib import Path
14-
from typing import NamedTuple, Optional, Union, cast
14+
from typing import NamedTuple, Union, cast
1515
from urllib.request import urlopen, urlretrieve
1616

1717
PYPI_INSTANCE = "https://pypi.org/pypi"
@@ -28,10 +28,10 @@
2828

2929
class BlackVersion(NamedTuple):
3030
version: str
31-
config: Optional[str] = None
31+
config: str | None = None
3232

3333

34-
def get_pypi_download_url(package: str, version: Optional[str]) -> str:
34+
def get_pypi_download_url(package: str, version: str | None) -> str:
3535
with urlopen(PYPI_INSTANCE + f"/{package}/json") as page:
3636
metadata = json.load(page)
3737

@@ -62,7 +62,7 @@ def get_top_packages() -> list[str]:
6262
return [package["project"] for package in result["rows"]]
6363

6464

65-
def get_package_source(package: str, version: Optional[str]) -> str:
65+
def get_package_source(package: str, version: str | None) -> str:
6666
if package == "cpython":
6767
if version is None:
6868
version = "main"
@@ -93,7 +93,7 @@ def get_first_archive_member(archive: ArchiveKind) -> str:
9393
return archive.namelist()[0]
9494

9595

96-
def download_and_extract(package: str, version: Optional[str], directory: Path) -> Path:
96+
def download_and_extract(package: str, version: str | None, directory: Path) -> Path:
9797
source = get_package_source(package, version)
9898

9999
local_file, _ = urlretrieve(source, directory / f"{package}-src")
@@ -104,8 +104,8 @@ def download_and_extract(package: str, version: Optional[str], directory: Path)
104104

105105

106106
def get_package(
107-
package: str, version: Optional[str], directory: Path
108-
) -> Optional[Path]:
107+
package: str, version: str | None, directory: Path
108+
) -> Path | None:
109109
try:
110110
return download_and_extract(package, version, directory)
111111
except Exception:
@@ -140,7 +140,7 @@ def git_add_and_commit(msg: str, repo: Path) -> None:
140140

141141

142142
def git_switch_branch(
143-
branch: str, repo: Path, new: bool = False, from_branch: Optional[str] = None
143+
branch: str, repo: Path, new: bool = False, from_branch: str | None = None
144144
) -> None:
145145
args = ["git", "checkout"]
146146
if new:
@@ -198,7 +198,7 @@ def black_runner(version: str, black_repo: Path) -> Path:
198198

199199
def format_repo_with_version(
200200
repo: Path,
201-
from_branch: Optional[str],
201+
from_branch: str | None,
202202
black_repo: Path,
203203
black_version: BlackVersion,
204204
input_directory: Path,
@@ -207,7 +207,7 @@ def format_repo_with_version(
207207
git_switch_branch(black_version.version, repo=black_repo)
208208
git_switch_branch(current_branch, repo=repo, new=True, from_branch=from_branch)
209209

210-
format_cmd: list[Union[Path, str]] = [
210+
format_cmd: list[Path | str] = [
211211
black_runner(black_version.version, black_repo),
212212
(black_repo / "black.py").resolve(),
213213
".",

scripts/check_pre_commit_rev_in_example.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ def main(changes: str, source_version_control: str) -> None:
2121
changes_html = commonmark.commonmark(changes)
2222
changes_soup = BeautifulSoup(changes_html, "html.parser")
2323
headers = changes_soup.find_all("h2")
24-
latest_tag, *_ = [
24+
latest_tag, *_ = (
2525
header.string for header in headers if header.string != "Unreleased"
26-
]
26+
)
2727

2828
source_version_control_html = commonmark.commonmark(source_version_control)
2929
source_version_control_soup = BeautifulSoup(

src/black/__init__.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from json.decoder import JSONDecodeError
2020
from pathlib import Path
2121
from re import Pattern
22-
from typing import Any, Optional, Union
22+
from typing import Any
2323

2424
import click
2525
from click.core import ParameterSource
@@ -114,8 +114,8 @@ def from_configuration(
114114

115115

116116
def read_pyproject_toml(
117-
ctx: click.Context, param: click.Parameter, value: Optional[str]
118-
) -> Optional[str]:
117+
ctx: click.Context, param: click.Parameter, value: str | None
118+
) -> str | None:
119119
"""Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
120120
121121
Returns the path to a successfully found and read configuration file, None
@@ -193,7 +193,7 @@ def spellcheck_pyproject_toml_keys(
193193

194194

195195
def target_version_option_callback(
196-
c: click.Context, p: Union[click.Option, click.Parameter], v: tuple[str, ...]
196+
c: click.Context, p: click.Option | click.Parameter, v: tuple[str, ...]
197197
) -> list[TargetVersion]:
198198
"""Compute the target versions from a --target-version flag.
199199
@@ -204,7 +204,7 @@ def target_version_option_callback(
204204

205205

206206
def enable_unstable_feature_callback(
207-
c: click.Context, p: Union[click.Option, click.Parameter], v: tuple[str, ...]
207+
c: click.Context, p: click.Option | click.Parameter, v: tuple[str, ...]
208208
) -> list[Preview]:
209209
"""Compute the features from an --enable-unstable-feature flag."""
210210
return [Preview[val] for val in v]
@@ -224,8 +224,8 @@ def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
224224
def validate_regex(
225225
ctx: click.Context,
226226
param: click.Parameter,
227-
value: Optional[str],
228-
) -> Optional[Pattern[str]]:
227+
value: str | None,
228+
) -> Pattern[str] | None:
229229
try:
230230
return re_compile_maybe_verbose(value) if value is not None else None
231231
except re.error as e:
@@ -516,7 +516,7 @@ def validate_regex(
516516
@click.pass_context
517517
def main( # noqa: C901
518518
ctx: click.Context,
519-
code: Optional[str],
519+
code: str | None,
520520
line_length: int,
521521
target_version: list[TargetVersion],
522522
check: bool,
@@ -535,15 +535,15 @@ def main( # noqa: C901
535535
enable_unstable_feature: list[Preview],
536536
quiet: bool,
537537
verbose: bool,
538-
required_version: Optional[str],
538+
required_version: str | None,
539539
include: Pattern[str],
540-
exclude: Optional[Pattern[str]],
541-
extend_exclude: Optional[Pattern[str]],
542-
force_exclude: Optional[Pattern[str]],
543-
stdin_filename: Optional[str],
544-
workers: Optional[int],
540+
exclude: Pattern[str] | None,
541+
extend_exclude: Pattern[str] | None,
542+
force_exclude: Pattern[str] | None,
543+
stdin_filename: str | None,
544+
workers: int | None,
545545
src: tuple[str, ...],
546-
config: Optional[str],
546+
config: str | None,
547547
no_cache: bool,
548548
) -> None:
549549
"""The uncompromising code formatter."""
@@ -738,19 +738,19 @@ def get_sources(
738738
quiet: bool,
739739
verbose: bool,
740740
include: Pattern[str],
741-
exclude: Optional[Pattern[str]],
742-
extend_exclude: Optional[Pattern[str]],
743-
force_exclude: Optional[Pattern[str]],
741+
exclude: Pattern[str] | None,
742+
extend_exclude: Pattern[str] | None,
743+
force_exclude: Pattern[str] | None,
744744
report: "Report",
745-
stdin_filename: Optional[str],
745+
stdin_filename: str | None,
746746
) -> set[Path]:
747747
"""Compute the set of files to be formatted."""
748748
sources: set[Path] = set()
749749

750750
assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
751751
using_default_exclude = exclude is None
752752
exclude = re_compile_maybe_verbose(DEFAULT_EXCLUDES) if exclude is None else exclude
753-
gitignore: Optional[dict[Path, PathSpec]] = None
753+
gitignore: dict[Path, PathSpec] | None = None
754754
root_gitignore = get_gitignore(root)
755755

756756
for s in src:
@@ -994,7 +994,7 @@ def format_file_in_place(
994994
def format_stdin_to_stdout(
995995
fast: bool,
996996
*,
997-
content: Optional[str] = None,
997+
content: str | None = None,
998998
write_back: WriteBack = WriteBack.NO,
999999
mode: Mode,
10001000
lines: Collection[tuple[int, int]] = (),
@@ -1267,7 +1267,7 @@ def _format_str_once(
12671267
}
12681268
if supports_feature(versions, feature)
12691269
}
1270-
block: Optional[LinesBlock] = None
1270+
block: LinesBlock | None = None
12711271
for current_line in line_generator.visit(src_node):
12721272
block = elt.maybe_empty_lines(current_line)
12731273
dst_blocks.append(block)
@@ -1335,7 +1335,7 @@ def decode_bytes(src: bytes, mode: Mode) -> tuple[FileContent, Encoding, NewLine
13351335

13361336

13371337
def get_features_used( # noqa: C901
1338-
node: Node, *, future_imports: Optional[set[str]] = None
1338+
node: Node, *, future_imports: set[str] | None = None
13391339
) -> set[Feature]:
13401340
"""Return a set of (relatively) new Python features used in this file.
13411341
@@ -1496,7 +1496,7 @@ def get_features_used( # noqa: C901
14961496
return features
14971497

14981498

1499-
def _contains_asexpr(node: Union[Node, Leaf]) -> bool:
1499+
def _contains_asexpr(node: Node | Leaf) -> bool:
15001500
"""Return True if `node` contains an as-pattern."""
15011501
if node.type == syms.asexpr_test:
15021502
return True
@@ -1513,7 +1513,7 @@ def _contains_asexpr(node: Union[Node, Leaf]) -> bool:
15131513

15141514

15151515
def detect_target_versions(
1516-
node: Node, *, future_imports: Optional[set[str]] = None
1516+
node: Node, *, future_imports: set[str] | None = None
15171517
) -> set[TargetVersion]:
15181518
"""Detect the version to target based on the nodes used."""
15191519
features = get_features_used(node, future_imports=future_imports)

src/black/brackets.py

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

33
from collections.abc import Iterable, Sequence
44
from dataclasses import dataclass, field
5-
from typing import Final, Optional, Union
5+
from typing import Final, Union
66

77
from black.nodes import (
88
BRACKET,
@@ -63,7 +63,7 @@ class BracketTracker:
6363
depth: int = 0
6464
bracket_match: dict[tuple[Depth, NodeType], Leaf] = field(default_factory=dict)
6565
delimiters: dict[LeafID, Priority] = field(default_factory=dict)
66-
previous: Optional[Leaf] = None
66+
previous: Leaf | None = None
6767
_for_loop_depths: list[int] = field(default_factory=list)
6868
_lambda_argument_depths: list[int] = field(default_factory=list)
6969
invisible: list[Leaf] = field(default_factory=list)
@@ -211,7 +211,7 @@ def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
211211

212212
return False
213213

214-
def get_open_lsqb(self) -> Optional[Leaf]:
214+
def get_open_lsqb(self) -> Leaf | None:
215215
"""Return the most recent opening square bracket (if any)."""
216216
return self.bracket_match.get((self.depth - 1, token.RSQB))
217217

@@ -230,7 +230,7 @@ def is_split_after_delimiter(leaf: Leaf) -> Priority:
230230
return 0
231231

232232

233-
def is_split_before_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
233+
def is_split_before_delimiter(leaf: Leaf, previous: Leaf | None = None) -> Priority:
234234
"""Return the priority of the `leaf` delimiter, given a line break before it.
235235
236236
The delimiter priorities returned here are from those delimiters that would

src/black/comments.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from collections.abc import Collection, Iterator
33
from dataclasses import dataclass
44
from functools import lru_cache
5-
from typing import Final, Optional, Union
5+
from typing import Final, Union
66

77
from black.mode import Mode, Preview
88
from black.nodes import (
@@ -414,7 +414,7 @@ def _handle_regular_fmt_block(
414414
# leaf (possibly followed by a DEDENT).
415415
hidden_value = hidden_value[:-1]
416416

417-
first_idx: Optional[int] = None
417+
first_idx: int | None = None
418418
for ignored in ignored_nodes:
419419
index = ignored.remove()
420420
if first_idx is None:
@@ -445,7 +445,7 @@ def generate_ignored_nodes(
445445
if _contains_fmt_directive(comment.value, FMT_SKIP):
446446
yield from _generate_ignored_nodes_from_fmt_skip(leaf, comment, mode)
447447
return
448-
container: Optional[LN] = container_of(leaf)
448+
container: LN | None = container_of(leaf)
449449
while container is not None and container.type != token.ENDMARKER:
450450
if is_fmt_on(container, mode=mode):
451451
return
@@ -483,7 +483,7 @@ def generate_ignored_nodes(
483483
container = container.next_sibling
484484

485485

486-
def _find_compound_statement_context(parent: Node) -> Optional[Node]:
486+
def _find_compound_statement_context(parent: Node) -> Node | None:
487487
"""Return the body node of a compound statement if we should respect fmt: skip.
488488
489489
This handles one-line compound statements like:

src/black/concurrency.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor
1717
from multiprocessing import Manager
1818
from pathlib import Path
19-
from typing import Any, Optional
19+
from typing import Any
2020

2121
from mypy_extensions import mypyc_attr
2222

@@ -41,7 +41,7 @@ def maybe_install_uvloop() -> None:
4141
pass
4242

4343

44-
def cancel(tasks: Iterable["asyncio.Future[Any]"]) -> None:
44+
def cancel(tasks: Iterable[asyncio.Future[Any]]) -> None:
4545
"""asyncio signal handler that cancels all `tasks` and reports to stderr."""
4646
err("Aborted!")
4747
for task in tasks:
@@ -77,7 +77,7 @@ def reformat_many(
7777
write_back: WriteBack,
7878
mode: Mode,
7979
report: Report,
80-
workers: Optional[int],
80+
workers: int | None,
8181
no_cache: bool = False,
8282
) -> None:
8383
"""Reformat multiple files using a ProcessPoolExecutor."""
@@ -133,9 +133,9 @@ async def schedule_formatting(
133133
fast: bool,
134134
write_back: WriteBack,
135135
mode: Mode,
136-
report: "Report",
136+
report: Report,
137137
loop: asyncio.AbstractEventLoop,
138-
executor: "Executor",
138+
executor: Executor,
139139
no_cache: bool = False,
140140
) -> None:
141141
"""Run formatting of `sources` in parallel using the provided `executor`.

src/black/debug.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def visit_default(self, node: LN) -> Iterator[T]:
4444
self.out(f" {node.value!r}", fg="blue", bold=False)
4545

4646
@classmethod
47-
def show(cls, code: Union[str, Leaf, Node]) -> None:
47+
def show(cls, code: str | Leaf | Node) -> None:
4848
"""Pretty-print the lib2to3 AST of a given string of `code`.
4949
5050
Convenience method for debugging.

0 commit comments

Comments
 (0)