Skip to content

Commit d616f2b

Browse files
authored
Update typing for Python 3.7 (1) (#1555)
1 parent 58bbe0f commit d616f2b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+1185
-1170
lines changed

astroid/_ast.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,19 @@
22
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
33
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
44

5+
from __future__ import annotations
6+
57
import ast
68
import sys
79
import types
810
from functools import partial
9-
from typing import Dict, List, NamedTuple, Optional, Type
11+
from typing import NamedTuple
1012

1113
from astroid.const import PY38_PLUS, Context
1214

1315
if sys.version_info >= (3, 8):
1416
# On Python 3.8, typed_ast was merged back into `ast`
15-
_ast_py3: Optional[types.ModuleType] = ast
17+
_ast_py3: types.ModuleType | None = ast
1618
else:
1719
try:
1820
import typed_ast.ast3 as _ast_py3
@@ -21,17 +23,17 @@
2123

2224

2325
class FunctionType(NamedTuple):
24-
argtypes: List[ast.expr]
26+
argtypes: list[ast.expr]
2527
returns: ast.expr
2628

2729

2830
class ParserModule(NamedTuple):
2931
module: types.ModuleType
30-
unary_op_classes: Dict[Type[ast.unaryop], str]
31-
cmp_op_classes: Dict[Type[ast.cmpop], str]
32-
bool_op_classes: Dict[Type[ast.boolop], str]
33-
bin_op_classes: Dict[Type[ast.operator], str]
34-
context_classes: Dict[Type[ast.expr_context], Context]
32+
unary_op_classes: dict[type[ast.unaryop], str]
33+
cmp_op_classes: dict[type[ast.cmpop], str]
34+
bool_op_classes: dict[type[ast.boolop], str]
35+
bin_op_classes: dict[type[ast.operator], str]
36+
context_classes: dict[type[ast.expr_context], Context]
3537

3638
def parse(self, string: str, type_comments: bool = True) -> ast.Module:
3739
if self.module is _ast_py3:
@@ -46,7 +48,7 @@ def parse(self, string: str, type_comments: bool = True) -> ast.Module:
4648
return parse_func(string)
4749

4850

49-
def parse_function_type_comment(type_comment: str) -> Optional[FunctionType]:
51+
def parse_function_type_comment(type_comment: str) -> FunctionType | None:
5052
"""Given a correct type comment, obtain a FunctionType object"""
5153
if _ast_py3 is None:
5254
return None
@@ -78,13 +80,13 @@ def get_parser_module(type_comments: bool = True) -> ParserModule:
7880

7981
def _unary_operators_from_module(
8082
module: types.ModuleType,
81-
) -> Dict[Type[ast.unaryop], str]:
83+
) -> dict[type[ast.unaryop], str]:
8284
return {module.UAdd: "+", module.USub: "-", module.Not: "not", module.Invert: "~"}
8385

8486

8587
def _binary_operators_from_module(
8688
module: types.ModuleType,
87-
) -> Dict[Type[ast.operator], str]:
89+
) -> dict[type[ast.operator], str]:
8890
binary_operators = {
8991
module.Add: "+",
9092
module.BitAnd: "&",
@@ -105,13 +107,13 @@ def _binary_operators_from_module(
105107

106108
def _bool_operators_from_module(
107109
module: types.ModuleType,
108-
) -> Dict[Type[ast.boolop], str]:
110+
) -> dict[type[ast.boolop], str]:
109111
return {module.And: "and", module.Or: "or"}
110112

111113

112114
def _compare_operators_from_module(
113115
module: types.ModuleType,
114-
) -> Dict[Type[ast.cmpop], str]:
116+
) -> dict[type[ast.cmpop], str]:
115117
return {
116118
module.Eq: "==",
117119
module.Gt: ">",
@@ -128,7 +130,7 @@ def _compare_operators_from_module(
128130

129131
def _contexts_from_module(
130132
module: types.ModuleType,
131-
) -> Dict[Type[ast.expr_context], Context]:
133+
) -> dict[type[ast.expr_context], Context]:
132134
return {
133135
module.Load: Context.Load,
134136
module.Store: Context.Store,

astroid/arguments.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
33
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
44

5-
from typing import Optional, Set
5+
from __future__ import annotations
66

77
from astroid import nodes
88
from astroid.bases import Instance
@@ -36,7 +36,7 @@ def __init__(
3636
self.argument_context_map = argument_context_map
3737
args = callcontext.args
3838
keywords = callcontext.keywords
39-
self.duplicated_keywords: Set[str] = set()
39+
self.duplicated_keywords: set[str] = set()
4040
self._unpacked_args = self._unpack_args(args, context=context)
4141
self._unpacked_kwargs = self._unpack_keywords(keywords, context=context)
4242

@@ -50,7 +50,7 @@ def __init__(
5050
}
5151

5252
@classmethod
53-
def from_call(cls, call_node, context: Optional[InferenceContext] = None):
53+
def from_call(cls, call_node, context: InferenceContext | None = None):
5454
"""Get a CallSite object from the given Call node.
5555
5656
context will be used to force a single inference path.

astroid/brain/brain_builtin_inference.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@
44

55
"""Astroid hooks for various builtins."""
66

7+
from __future__ import annotations
8+
79
import itertools
810
from functools import partial
9-
from typing import Iterator, Optional
11+
from typing import Iterator
1012

1113
from astroid import arguments, helpers, inference_tip, nodes, objects, util
1214
from astroid.builder import AstroidBuilder
@@ -534,7 +536,7 @@ def infer_callable(node, context=None):
534536

535537

536538
def infer_property(
537-
node: nodes.Call, context: Optional[InferenceContext] = None
539+
node: nodes.Call, context: InferenceContext | None = None
538540
) -> objects.Property:
539541
"""Understand `property` class
540542
@@ -894,7 +896,7 @@ def _build_dict_with_elements(elements):
894896

895897

896898
def _infer_copy_method(
897-
node: nodes.Call, context: Optional[InferenceContext] = None
899+
node: nodes.Call, context: InferenceContext | None = None
898900
) -> Iterator[nodes.NodeNG]:
899901
assert isinstance(node.func, nodes.Attribute)
900902
inferred_orig, inferred_copy = itertools.tee(node.func.expr.infer(context=context))

astroid/brain/brain_dataclasses.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,11 @@
1212
- https://lovasoa.github.io/marshmallow_dataclass/
1313
1414
"""
15+
16+
from __future__ import annotations
17+
1518
import sys
16-
from typing import FrozenSet, Generator, List, Optional, Tuple, Union
19+
from typing import Generator, Tuple, Union
1720

1821
from astroid import context, inference_tip
1922
from astroid.builder import parse
@@ -179,7 +182,7 @@ def _check_generate_dataclass_init(node: ClassDef) -> bool:
179182
)
180183

181184

182-
def _generate_dataclass_init(assigns: List[AnnAssign]) -> str:
185+
def _generate_dataclass_init(assigns: list[AnnAssign]) -> str:
183186
"""Return an init method for a dataclass given the targets."""
184187
target_names = []
185188
params = []
@@ -234,7 +237,7 @@ def _generate_dataclass_init(assigns: List[AnnAssign]) -> str:
234237

235238

236239
def infer_dataclass_attribute(
237-
node: Unknown, ctx: Optional[context.InferenceContext] = None
240+
node: Unknown, ctx: context.InferenceContext | None = None
238241
) -> Generator:
239242
"""Inference tip for an Unknown node that was dynamically generated to
240243
represent a dataclass attribute.
@@ -257,7 +260,7 @@ def infer_dataclass_attribute(
257260

258261

259262
def infer_dataclass_field_call(
260-
node: Call, ctx: Optional[context.InferenceContext] = None
263+
node: Call, ctx: context.InferenceContext | None = None
261264
) -> Generator:
262265
"""Inference tip for dataclass field calls."""
263266
if not isinstance(node.parent, (AnnAssign, Assign)):
@@ -276,7 +279,7 @@ def infer_dataclass_field_call(
276279

277280

278281
def _looks_like_dataclass_decorator(
279-
node: NodeNG, decorator_names: FrozenSet[str] = DATACLASSES_DECORATORS
282+
node: NodeNG, decorator_names: frozenset[str] = DATACLASSES_DECORATORS
280283
) -> bool:
281284
"""Return True if node looks like a dataclass decorator.
282285
@@ -423,7 +426,7 @@ def _is_init_var(node: NodeNG) -> bool:
423426

424427

425428
def _infer_instance_from_annotation(
426-
node: NodeNG, ctx: Optional[context.InferenceContext] = None
429+
node: NodeNG, ctx: context.InferenceContext | None = None
427430
) -> Generator:
428431
"""Infer an instance corresponding to the type annotation represented by node.
429432

astroid/brain/brain_functools.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
44

55
"""Astroid hooks for understanding functools library module."""
6+
7+
from __future__ import annotations
8+
69
from functools import partial
710
from itertools import chain
8-
from typing import Iterator, Optional
11+
from typing import Iterator
912

1013
from astroid import BoundMethod, arguments, extract_node, helpers, nodes, objects
1114
from astroid.context import InferenceContext
@@ -63,7 +66,7 @@ def _transform_lru_cache(node, context=None) -> None:
6366

6467

6568
def _functools_partial_inference(
66-
node: nodes.Call, context: Optional[InferenceContext] = None
69+
node: nodes.Call, context: InferenceContext | None = None
6770
) -> Iterator[objects.PartialFunction]:
6871
call = arguments.CallSite.from_call(node, context=context)
6972
number_of_positional = len(call.positional_arguments)

astroid/brain/brain_namedtuple_enum.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
"""Astroid hooks for the Python standard library."""
66

7+
from __future__ import annotations
8+
79
import functools
810
import keyword
911
from textwrap import dedent
10-
from typing import Iterator, List, Optional, Tuple
12+
from typing import Iterator
1113

1214
import astroid
1315
from astroid import arguments, inference_tip, nodes, util
@@ -71,9 +73,9 @@ def _extract_namedtuple_arg_or_keyword( # pylint: disable=inconsistent-return-s
7173
def infer_func_form(
7274
node: nodes.Call,
7375
base_type: nodes.NodeNG,
74-
context: Optional[InferenceContext] = None,
76+
context: InferenceContext | None = None,
7577
enum: bool = False,
76-
) -> Tuple[nodes.ClassDef, str, List[str]]:
78+
) -> tuple[nodes.ClassDef, str, list[str]]:
7779
"""Specific inference function for namedtuple or Python 3 enum."""
7880
# node is a Call node, class name as first argument and generated class
7981
# attributes as second argument
@@ -177,7 +179,7 @@ def _looks_like(node, name):
177179

178180

179181
def infer_named_tuple(
180-
node: nodes.Call, context: Optional[InferenceContext] = None
182+
node: nodes.Call, context: InferenceContext | None = None
181183
) -> Iterator[nodes.ClassDef]:
182184
"""Specific inference function for namedtuple Call node"""
183185
tuple_base_name = nodes.Name(name="tuple", parent=node.root())
@@ -503,7 +505,7 @@ def infer_typing_namedtuple_function(node, context=None):
503505

504506

505507
def infer_typing_namedtuple(
506-
node: nodes.Call, context: Optional[InferenceContext] = None
508+
node: nodes.Call, context: InferenceContext | None = None
507509
) -> Iterator[nodes.ClassDef]:
508510
"""Infer a typing.NamedTuple(...) call."""
509511
# This is essentially a namedtuple with different arguments

astroid/brain/brain_numpy_utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
44

55
"""Different utilities for the numpy brains"""
6-
from typing import Tuple
6+
7+
from __future__ import annotations
78

89
from astroid.builder import extract_node
910
from astroid.nodes.node_classes import Attribute, Import, Name, NodeNG
@@ -20,7 +21,7 @@ def numpy_supports_type_hints() -> bool:
2021
return np_ver and np_ver > NUMPY_VERSION_TYPE_HINTS_SUPPORT
2122

2223

23-
def _get_numpy_version() -> Tuple[str, str, str]:
24+
def _get_numpy_version() -> tuple[str, str, str]:
2425
"""
2526
Return the numpy version number if numpy can be imported. Otherwise returns
2627
('0', '0', '0')

astroid/brain/brain_re.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
33
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
44

5-
from typing import Optional
5+
from __future__ import annotations
66

77
from astroid import context, inference_tip, nodes
88
from astroid.brain.helpers import register_module_extender
@@ -74,9 +74,7 @@ def _looks_like_pattern_or_match(node: nodes.Call) -> bool:
7474
)
7575

7676

77-
def infer_pattern_match(
78-
node: nodes.Call, ctx: Optional[context.InferenceContext] = None
79-
):
77+
def infer_pattern_match(node: nodes.Call, ctx: context.InferenceContext | None = None):
8078
"""Infer re.Pattern and re.Match as classes. For PY39+ add `__class_getitem__`."""
8179
class_def = nodes.ClassDef(
8280
name=node.parent.targets[0].name,

astroid/brain/brain_typing.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
44

55
"""Astroid hooks for typing.py support."""
6+
7+
from __future__ import annotations
8+
69
import typing
710
from functools import partial
811

@@ -140,7 +143,7 @@ def _looks_like_typing_subscript(node):
140143

141144

142145
def infer_typing_attr(
143-
node: Subscript, ctx: typing.Optional[context.InferenceContext] = None
146+
node: Subscript, ctx: context.InferenceContext | None = None
144147
) -> typing.Iterator[ClassDef]:
145148
"""Infer a typing.X[...] subscript"""
146149
try:
@@ -179,22 +182,22 @@ def infer_typing_attr(
179182

180183

181184
def _looks_like_typedDict( # pylint: disable=invalid-name
182-
node: typing.Union[FunctionDef, ClassDef],
185+
node: FunctionDef | ClassDef,
183186
) -> bool:
184187
"""Check if node is TypedDict FunctionDef."""
185188
return node.qname() in {"typing.TypedDict", "typing_extensions.TypedDict"}
186189

187190

188191
def infer_old_typedDict( # pylint: disable=invalid-name
189-
node: ClassDef, ctx: typing.Optional[context.InferenceContext] = None
192+
node: ClassDef, ctx: context.InferenceContext | None = None
190193
) -> typing.Iterator[ClassDef]:
191194
func_to_add = _extract_single_node("dict")
192195
node.locals["__call__"] = [func_to_add]
193196
return iter([node])
194197

195198

196199
def infer_typedDict( # pylint: disable=invalid-name
197-
node: FunctionDef, ctx: typing.Optional[context.InferenceContext] = None
200+
node: FunctionDef, ctx: context.InferenceContext | None = None
198201
) -> typing.Iterator[ClassDef]:
199202
"""Replace TypedDict FunctionDef with ClassDef."""
200203
class_def = ClassDef(
@@ -254,7 +257,7 @@ def full_raiser(origin_func, attr, *args, **kwargs):
254257

255258

256259
def infer_typing_alias(
257-
node: Call, ctx: typing.Optional[context.InferenceContext] = None
260+
node: Call, ctx: context.InferenceContext | None = None
258261
) -> typing.Iterator[ClassDef]:
259262
"""
260263
Infers the call to _alias function
@@ -342,7 +345,7 @@ def _looks_like_special_alias(node: Call) -> bool:
342345

343346

344347
def infer_special_alias(
345-
node: Call, ctx: typing.Optional[context.InferenceContext] = None
348+
node: Call, ctx: context.InferenceContext | None = None
346349
) -> typing.Iterator[ClassDef]:
347350
"""Infer call to tuple alias as new subscriptable class typing.Tuple."""
348351
if not (
@@ -377,7 +380,7 @@ def _looks_like_typing_cast(node: Call) -> bool:
377380

378381

379382
def infer_typing_cast(
380-
node: Call, ctx: typing.Optional[context.InferenceContext] = None
383+
node: Call, ctx: context.InferenceContext | None = None
381384
) -> typing.Iterator[NodeNG]:
382385
"""Infer call to cast() returning same type as casted-from var"""
383386
if not isinstance(node.func, (Name, Attribute)):

0 commit comments

Comments
 (0)