Skip to content

Commit 82aaf64

Browse files
cyyeverpytorchmergebot
authored andcommitted
[3/N] Apply py39 ruff fixes (pytorch#142115)
Fixes #ISSUE_NUMBER Pull Request resolved: pytorch#142115 Approved by: https://github.com/ezyang
1 parent f7e621c commit 82aaf64

31 files changed

+137
-91
lines changed

tools/autograd/gen_annotated_fn_args.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import os
2121
import textwrap
2222
from collections import defaultdict
23-
from typing import Any, Sequence, TYPE_CHECKING
23+
from typing import Any, TYPE_CHECKING
2424

2525
import torchgen.api.python as python
2626
from torchgen.context import with_native_function
@@ -39,6 +39,8 @@
3939

4040

4141
if TYPE_CHECKING:
42+
from collections.abc import Sequence
43+
4244
from torchgen.model import Argument, BaseOperatorName, NativeFunction
4345

4446

tools/autograd/gen_autograd_functions.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from __future__ import annotations
99

10-
from typing import Sequence
10+
from typing import TYPE_CHECKING
1111

1212
from torchgen.api.autograd import (
1313
Derivative,
@@ -47,6 +47,10 @@
4747
from .gen_inplace_or_view_type import VIEW_FUNCTIONS
4848

4949

50+
if TYPE_CHECKING:
51+
from collections.abc import Sequence
52+
53+
5054
FUNCTION_DECLARATION = CodeTemplate(
5155
"""\
5256
#ifdef _WIN32

tools/autograd/gen_python_functions.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
import itertools
3737
import re
3838
from collections import defaultdict
39-
from typing import Callable, Iterable, Sequence
39+
from typing import Callable, TYPE_CHECKING
4040

4141
import yaml
4242

@@ -76,6 +76,10 @@
7676
from .gen_trace_type import should_trace
7777

7878

79+
if TYPE_CHECKING:
80+
from collections.abc import Iterable, Sequence
81+
82+
7983
#
8084
# declarations blocklist
8185
# We skip codegen for these functions, for various reasons.

tools/autograd/gen_trace_type.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import itertools
4-
from typing import Sequence
4+
from typing import TYPE_CHECKING
55

66
from torchgen.api import cpp
77
from torchgen.api.types import DispatcherSignature
@@ -11,6 +11,10 @@
1111
from torchgen.utils import FileManager
1212

1313

14+
if TYPE_CHECKING:
15+
from collections.abc import Sequence
16+
17+
1418
# Note [Manual Backend kernels]
1519
# For these ops, we want to manually register to dispatch key Backend and
1620
# skip codegen-ed registeration to all keys before Backend.

tools/autograd/gen_variable_type.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from __future__ import annotations
3030

3131
import re
32-
from typing import Callable, Sequence
32+
from typing import Callable, TYPE_CHECKING
3333

3434
from torchgen.api import cpp
3535
from torchgen.api.autograd import (
@@ -105,6 +105,10 @@
105105
)
106106

107107

108+
if TYPE_CHECKING:
109+
from collections.abc import Sequence
110+
111+
108112
# We don't set or modify grad_fn on these methods. Generally, they return
109113
# tensors that have requires_grad=False. In-place functions listed here will
110114
# not examine or modify requires_grad or grad_fn.

tools/autograd/load_derivatives.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
from __future__ import annotations
77

88
import re
9-
from collections import defaultdict
10-
from typing import Any, Counter, Dict, Sequence, Set, Tuple
9+
from collections import Counter, defaultdict
10+
from typing import Any, TYPE_CHECKING
1111

1212
import yaml
1313

@@ -53,7 +53,11 @@
5353
from torchgen.yaml_utils import YamlLoader
5454

5555

56-
DerivativeRet = Tuple[Dict[FunctionSchema, Dict[str, DifferentiabilityInfo]], Set[str]]
56+
if TYPE_CHECKING:
57+
from collections.abc import Sequence
58+
59+
60+
DerivativeRet = tuple[dict[FunctionSchema, dict[str, DifferentiabilityInfo]], set[str]]
5761

5862
_GLOBAL_LOAD_DERIVATIVE_CACHE: dict[tuple[str, str], DerivativeRet] = {}
5963

@@ -631,7 +635,7 @@ def set_up_derivatives(
631635
raise RuntimeError(
632636
f"Not supported: for {specification},"
633637
f"output_differentiability must either be "
634-
f"List[bool] or a List[str] where each str is a "
638+
f"list[bool] or a list[str] where each str is a "
635639
f"condition. In the case where it is a condition, "
636640
f"we only support single-output functions. "
637641
f"Please file us an issue. "

tools/code_analyzer/gen_op_registration_allowlist.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,11 @@
1212

1313
import argparse
1414
from collections import defaultdict
15-
from typing import Dict, Set
1615

1716
import yaml
1817

1918

20-
DepGraph = Dict[str, Set[str]]
19+
DepGraph = dict[str, set[str]]
2120

2221

2322
def canonical_name(opname: str) -> str:

tools/code_coverage/package/tool/print_report.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
import os
44
import subprocess
5-
from typing import IO, Tuple
5+
from typing import IO
66

77
from ..oss.utils import get_pytorch_folder
88
from ..util.setting import SUMMARY_FOLDER_DIR, TestList, TestStatusType
99

1010

11-
CoverageItem = Tuple[str, float, int, int]
11+
CoverageItem = tuple[str, float, int, int]
1212

1313

1414
def key_by_percentage(x: CoverageItem) -> float:

tools/code_coverage/package/tool/summarize_jsons.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from .parser.coverage_record import CoverageRecord
3232

3333

34-
# coverage_records: Dict[str, LineInfo] = {}
34+
# coverage_records: dict[str, LineInfo] = {}
3535
covered_lines: dict[str, set[int]] = {}
3636
uncovered_lines: dict[str, set[int]] = {}
3737
tests_type: TestStatusType = {"success": set(), "partial": set(), "fail": set()}

tools/code_coverage/package/util/setting.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import os
44
from enum import Enum
5-
from typing import Dict, List, Set
65

76

87
# <project folder>
@@ -43,8 +42,8 @@ def __init__(
4342
self.test_type = test_type
4443

4544

46-
TestList = List[Test]
47-
TestStatusType = Dict[str, Set[str]]
45+
TestList = list[Test]
46+
TestStatusType = dict[str, set[str]]
4847

4948

5049
# option

tools/extract_scripts.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66
import re
77
import sys
88
from pathlib import Path
9-
from typing import Any, Dict
9+
from typing import Any
1010
from typing_extensions import TypedDict # Python 3.11+
1111

1212
import yaml
1313

1414

15-
Step = Dict[str, Any]
15+
Step = dict[str, Any]
1616

1717

1818
class Script(TypedDict):

tools/jit/gen_unboxing.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import sys
88
from dataclasses import dataclass
99
from pathlib import Path
10-
from typing import Literal, Sequence, TYPE_CHECKING
10+
from typing import Literal, TYPE_CHECKING
1111

1212
import yaml
1313

@@ -22,6 +22,8 @@
2222

2323

2424
if TYPE_CHECKING:
25+
from collections.abc import Sequence
26+
2527
from torchgen.selective_build.selector import SelectiveBuilder
2628

2729

tools/linter/adapters/no_workflows_on_fork.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import re
2323
from enum import Enum
2424
from pathlib import Path
25-
from typing import Any, Callable, Dict, List, NamedTuple, Optional
25+
from typing import Any, Callable, NamedTuple, Optional
2626

2727
from yaml import load
2828

@@ -77,11 +77,11 @@ def gen_lint_message(
7777
)
7878

7979

80-
def check_file(filename: str) -> List[LintMessage]:
80+
def check_file(filename: str) -> list[LintMessage]:
8181
logging.debug("Checking file %s", filename)
8282

8383
workflow = load_yaml(Path(filename))
84-
bad_jobs: Dict[str, Optional[str]] = {}
84+
bad_jobs: dict[str, Optional[str]] = {}
8585
if type(workflow) is not dict:
8686
return []
8787

@@ -106,7 +106,7 @@ def check_file(filename: str) -> List[LintMessage]:
106106
pass
107107
else:
108108
if_statement = str(if_statement)
109-
valid_checks: List[Callable[[str], bool]] = [
109+
valid_checks: list[Callable[[str], bool]] = [
110110
lambda x: "github.repository == 'pytorch/pytorch'" in x
111111
and "github.event_name != 'schedule' || github.repository == 'pytorch/pytorch'"
112112
not in x,

tools/linter/adapters/workflow_consistency_linter.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,15 @@
1111
from collections import defaultdict
1212
from enum import Enum
1313
from pathlib import Path
14-
from typing import Any, Iterable, NamedTuple
14+
from typing import Any, NamedTuple, TYPE_CHECKING
1515

1616
from yaml import dump, load
1717

1818

19+
if TYPE_CHECKING:
20+
from collections.abc import Iterable
21+
22+
1923
# Safely load fast C Yaml loader/dumper if they are available
2024
try:
2125
from yaml import CSafeLoader as Loader

tools/nightly.py

+5-10
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,11 @@
5050
from datetime import datetime
5151
from pathlib import Path
5252
from platform import system as platform_system
53-
from typing import (
54-
Any,
55-
Callable,
56-
cast,
57-
Generator,
58-
Iterable,
59-
Iterator,
60-
NamedTuple,
61-
TypeVar,
62-
)
53+
from typing import Any, Callable, cast, NamedTuple, TYPE_CHECKING, TypeVar
54+
55+
56+
if TYPE_CHECKING:
57+
from collections.abc import Generator, Iterable, Iterator
6358

6459

6560
try:

tools/nightly_hotpatch.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import sys
88
import tempfile
99
import urllib.request
10-
from typing import cast, List, NoReturn, Optional
10+
from typing import cast, NoReturn, Optional
1111

1212

1313
def parse_arguments() -> argparse.Namespace:
@@ -74,7 +74,7 @@ def get_pytorch_path() -> str:
7474
try:
7575
import torch
7676

77-
torch_paths: List[str] = cast(List[str], torch.__path__)
77+
torch_paths: list[str] = cast(list[str], torch.__path__)
7878
torch_path: str = torch_paths[0]
7979
parent_path: str = os.path.dirname(torch_path)
8080
print(f"PyTorch is installed at: {torch_path}")
@@ -114,9 +114,10 @@ def download_patch(pr_number: int, repo_url: str, download_dir: str) -> str:
114114
patch_file = os.path.join(download_dir, f"pr-{pr_number}.patch")
115115
print(f"Downloading PR #{pr_number} patch from {patch_url}...")
116116
try:
117-
with urllib.request.urlopen(patch_url) as response, open(
118-
patch_file, "wb"
119-
) as out_file:
117+
with (
118+
urllib.request.urlopen(patch_url) as response,
119+
open(patch_file, "wb") as out_file,
120+
):
120121
shutil.copyfileobj(response, out_file)
121122
if not os.path.isfile(patch_file):
122123
print(f"Failed to download patch for PR #{pr_number}")

tools/onnx/gen_diagnostics.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
import string
1818
import subprocess
1919
import textwrap
20-
from typing import Any, Mapping, Sequence
20+
from collections.abc import Mapping, Sequence
21+
from typing import Any
2122

2223
import yaml
2324

@@ -56,7 +57,7 @@ def format( # type: ignore[override]
5657
self,
5758
level: infra.Level,
5859
{message_arguments}
59-
) -> Tuple[infra.Rule, infra.Level, str]:
60+
) -> tuple[infra.Rule, infra.Level, str]:
6061
\"\"\"Returns a tuple of (Rule, Level, message) for this Rule.
6162
6263
Message template: {message_template}

tools/packaging/split_wheel.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
import subprocess
2727
import sys
2828
from pathlib import Path
29-
from typing import Dict, List, Optional
29+
from typing import Optional
3030

3131

3232
logging.basicConfig(
@@ -56,7 +56,7 @@ def requirements_installed() -> bool:
5656
return False
5757

5858

59-
def setup_py(cmd_args: List[str], extra_env: Optional[Dict[str, str]] = None) -> None:
59+
def setup_py(cmd_args: list[str], extra_env: Optional[dict[str, str]] = None) -> None:
6060
if extra_env is None:
6161
extra_env = {}
6262
cmd = [sys.executable, str(SETUP_PY_PATH), *cmd_args]

0 commit comments

Comments
 (0)