Skip to content

Commit 6d322e2

Browse files
TYP: use from __future__ import annotations more - batch 4 (#41896)
1 parent e34603d commit 6d322e2

File tree

10 files changed

+81
-103
lines changed

10 files changed

+81
-103
lines changed

pandas/compat/numpy/function.py

+18-21
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,9 @@
1515
methods that are spread throughout the codebase. This module will make it
1616
easier to adjust to future upstream changes in the analogous numpy signatures.
1717
"""
18-
from typing import (
19-
Any,
20-
Dict,
21-
Optional,
22-
Union,
23-
)
18+
from __future__ import annotations
19+
20+
from typing import Any
2421

2522
from numpy import ndarray
2623

@@ -41,7 +38,7 @@ def __init__(
4138
self,
4239
defaults,
4340
fname=None,
44-
method: Optional[str] = None,
41+
method: str | None = None,
4542
max_fname_arg_count=None,
4643
):
4744
self.fname = fname
@@ -55,7 +52,7 @@ def __call__(
5552
kwargs,
5653
fname=None,
5754
max_fname_arg_count=None,
58-
method: Optional[str] = None,
55+
method: str | None = None,
5956
) -> None:
6057
if args or kwargs:
6158
fname = self.fname if fname is None else fname
@@ -119,7 +116,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs):
119116
return skipna
120117

121118

122-
ARGSORT_DEFAULTS: Dict[str, Optional[Union[int, str]]] = {}
119+
ARGSORT_DEFAULTS: dict[str, int | str | None] = {}
123120
ARGSORT_DEFAULTS["axis"] = -1
124121
ARGSORT_DEFAULTS["kind"] = "quicksort"
125122
ARGSORT_DEFAULTS["order"] = None
@@ -132,7 +129,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs):
132129

133130
# two different signatures of argsort, this second validation for when the
134131
# `kind` param is supported
135-
ARGSORT_DEFAULTS_KIND: Dict[str, Optional[int]] = {}
132+
ARGSORT_DEFAULTS_KIND: dict[str, int | None] = {}
136133
ARGSORT_DEFAULTS_KIND["axis"] = -1
137134
ARGSORT_DEFAULTS_KIND["order"] = None
138135
validate_argsort_kind = CompatValidator(
@@ -155,7 +152,7 @@ def validate_argsort_with_ascending(ascending, args, kwargs):
155152
return ascending
156153

157154

158-
CLIP_DEFAULTS: Dict[str, Any] = {"out": None}
155+
CLIP_DEFAULTS: dict[str, Any] = {"out": None}
159156
validate_clip = CompatValidator(
160157
CLIP_DEFAULTS, fname="clip", method="both", max_fname_arg_count=3
161158
)
@@ -176,7 +173,7 @@ def validate_clip_with_axis(axis, args, kwargs):
176173
return axis
177174

178175

179-
CUM_FUNC_DEFAULTS: Dict[str, Any] = {}
176+
CUM_FUNC_DEFAULTS: dict[str, Any] = {}
180177
CUM_FUNC_DEFAULTS["dtype"] = None
181178
CUM_FUNC_DEFAULTS["out"] = None
182179
validate_cum_func = CompatValidator(
@@ -201,7 +198,7 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
201198
return skipna
202199

203200

204-
ALLANY_DEFAULTS: Dict[str, Optional[bool]] = {}
201+
ALLANY_DEFAULTS: dict[str, bool | None] = {}
205202
ALLANY_DEFAULTS["dtype"] = None
206203
ALLANY_DEFAULTS["out"] = None
207204
ALLANY_DEFAULTS["keepdims"] = False
@@ -224,28 +221,28 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
224221
MINMAX_DEFAULTS, fname="max", method="both", max_fname_arg_count=1
225222
)
226223

227-
RESHAPE_DEFAULTS: Dict[str, str] = {"order": "C"}
224+
RESHAPE_DEFAULTS: dict[str, str] = {"order": "C"}
228225
validate_reshape = CompatValidator(
229226
RESHAPE_DEFAULTS, fname="reshape", method="both", max_fname_arg_count=1
230227
)
231228

232-
REPEAT_DEFAULTS: Dict[str, Any] = {"axis": None}
229+
REPEAT_DEFAULTS: dict[str, Any] = {"axis": None}
233230
validate_repeat = CompatValidator(
234231
REPEAT_DEFAULTS, fname="repeat", method="both", max_fname_arg_count=1
235232
)
236233

237-
ROUND_DEFAULTS: Dict[str, Any] = {"out": None}
234+
ROUND_DEFAULTS: dict[str, Any] = {"out": None}
238235
validate_round = CompatValidator(
239236
ROUND_DEFAULTS, fname="round", method="both", max_fname_arg_count=1
240237
)
241238

242-
SORT_DEFAULTS: Dict[str, Optional[Union[int, str]]] = {}
239+
SORT_DEFAULTS: dict[str, int | str | None] = {}
243240
SORT_DEFAULTS["axis"] = -1
244241
SORT_DEFAULTS["kind"] = "quicksort"
245242
SORT_DEFAULTS["order"] = None
246243
validate_sort = CompatValidator(SORT_DEFAULTS, fname="sort", method="kwargs")
247244

248-
STAT_FUNC_DEFAULTS: Dict[str, Optional[Any]] = {}
245+
STAT_FUNC_DEFAULTS: dict[str, Any | None] = {}
249246
STAT_FUNC_DEFAULTS["dtype"] = None
250247
STAT_FUNC_DEFAULTS["out"] = None
251248

@@ -279,13 +276,13 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
279276
MEDIAN_DEFAULTS, fname="median", method="both", max_fname_arg_count=1
280277
)
281278

282-
STAT_DDOF_FUNC_DEFAULTS: Dict[str, Optional[bool]] = {}
279+
STAT_DDOF_FUNC_DEFAULTS: dict[str, bool | None] = {}
283280
STAT_DDOF_FUNC_DEFAULTS["dtype"] = None
284281
STAT_DDOF_FUNC_DEFAULTS["out"] = None
285282
STAT_DDOF_FUNC_DEFAULTS["keepdims"] = False
286283
validate_stat_ddof_func = CompatValidator(STAT_DDOF_FUNC_DEFAULTS, method="kwargs")
287284

288-
TAKE_DEFAULTS: Dict[str, Optional[str]] = {}
285+
TAKE_DEFAULTS: dict[str, str | None] = {}
289286
TAKE_DEFAULTS["out"] = None
290287
TAKE_DEFAULTS["mode"] = "raise"
291288
validate_take = CompatValidator(TAKE_DEFAULTS, fname="take", method="kwargs")
@@ -392,7 +389,7 @@ def validate_resampler_func(method: str, args, kwargs) -> None:
392389
raise TypeError("too many arguments passed in")
393390

394391

395-
def validate_minmax_axis(axis: Optional[int], ndim: int = 1) -> None:
392+
def validate_minmax_axis(axis: int | None, ndim: int = 1) -> None:
396393
"""
397394
Ensure that the axis argument passed to min, max, argmin, or argmax is zero
398395
or None, as otherwise it will be incorrectly ignored.

pandas/core/array_algos/replace.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
"""
22
Methods used by Block.replace and related methods.
33
"""
4+
from __future__ import annotations
5+
46
import operator
57
import re
68
from typing import (
79
Any,
8-
Optional,
910
Pattern,
10-
Union,
1111
)
1212

1313
import numpy as np
@@ -42,8 +42,8 @@ def should_use_regex(regex: bool, to_replace: Any) -> bool:
4242

4343

4444
def compare_or_regex_search(
45-
a: ArrayLike, b: Union[Scalar, Pattern], regex: bool, mask: np.ndarray
46-
) -> Union[ArrayLike, bool]:
45+
a: ArrayLike, b: Scalar | Pattern, regex: bool, mask: np.ndarray
46+
) -> ArrayLike | bool:
4747
"""
4848
Compare two array_like inputs of the same shape or two scalar values
4949
@@ -65,7 +65,7 @@ def compare_or_regex_search(
6565
return ~mask
6666

6767
def _check_comparison_types(
68-
result: Union[ArrayLike, bool], a: ArrayLike, b: Union[Scalar, Pattern]
68+
result: ArrayLike | bool, a: ArrayLike, b: Scalar | Pattern
6969
):
7070
"""
7171
Raises an error if the two arrays (a,b) cannot be compared.
@@ -115,7 +115,7 @@ def _check_comparison_types(
115115
return result
116116

117117

118-
def replace_regex(values: ArrayLike, rx: re.Pattern, value, mask: Optional[np.ndarray]):
118+
def replace_regex(values: ArrayLike, rx: re.Pattern, value, mask: np.ndarray | None):
119119
"""
120120
Parameters
121121
----------

pandas/core/computation/expr.py

+9-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
:func:`~pandas.eval` parsers.
33
"""
4+
from __future__ import annotations
45

56
import ast
67
from functools import (
@@ -11,10 +12,6 @@
1112
import tokenize
1213
from typing import (
1314
Callable,
14-
Optional,
15-
Set,
16-
Tuple,
17-
Type,
1815
TypeVar,
1916
)
2017

@@ -50,7 +47,7 @@
5047
import pandas.io.formats.printing as printing
5148

5249

53-
def _rewrite_assign(tok: Tuple[int, str]) -> Tuple[int, str]:
50+
def _rewrite_assign(tok: tuple[int, str]) -> tuple[int, str]:
5451
"""
5552
Rewrite the assignment operator for PyTables expressions that use ``=``
5653
as a substitute for ``==``.
@@ -69,7 +66,7 @@ def _rewrite_assign(tok: Tuple[int, str]) -> Tuple[int, str]:
6966
return toknum, "==" if tokval == "=" else tokval
7067

7168

72-
def _replace_booleans(tok: Tuple[int, str]) -> Tuple[int, str]:
69+
def _replace_booleans(tok: tuple[int, str]) -> tuple[int, str]:
7370
"""
7471
Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise
7572
precedence is changed to boolean precedence.
@@ -94,7 +91,7 @@ def _replace_booleans(tok: Tuple[int, str]) -> Tuple[int, str]:
9491
return toknum, tokval
9592

9693

97-
def _replace_locals(tok: Tuple[int, str]) -> Tuple[int, str]:
94+
def _replace_locals(tok: tuple[int, str]) -> tuple[int, str]:
9895
"""
9996
Replace local variables with a syntactically valid name.
10097
@@ -271,7 +268,7 @@ def f(self, *args, **kwargs):
271268
_T = TypeVar("_T", bound="BaseExprVisitor")
272269

273270

274-
def disallow(nodes: Set[str]) -> Callable[[Type[_T]], Type[_T]]:
271+
def disallow(nodes: set[str]) -> Callable[[type[_T]], type[_T]]:
275272
"""
276273
Decorator to disallow certain nodes from parsing. Raises a
277274
NotImplementedError instead.
@@ -281,7 +278,7 @@ def disallow(nodes: Set[str]) -> Callable[[Type[_T]], Type[_T]]:
281278
callable
282279
"""
283280

284-
def disallowed(cls: Type[_T]) -> Type[_T]:
281+
def disallowed(cls: type[_T]) -> type[_T]:
285282
cls.unsupported_nodes = ()
286283
for node in nodes:
287284
new_method = _node_not_implemented(node)
@@ -352,7 +349,7 @@ class BaseExprVisitor(ast.NodeVisitor):
352349
preparser : callable
353350
"""
354351

355-
const_type: Type[Term] = Constant
352+
const_type: type[Term] = Constant
356353
term_type = Term
357354

358355
binary_ops = CMP_OPS_SYMS + BOOL_OPS_SYMS + ARITH_OPS_SYMS
@@ -390,7 +387,7 @@ class BaseExprVisitor(ast.NodeVisitor):
390387
ast.NotIn: ast.NotIn,
391388
}
392389

393-
unsupported_nodes: Tuple[str, ...]
390+
unsupported_nodes: tuple[str, ...]
394391

395392
def __init__(self, env, engine, parser, preparser=_preparse):
396393
self.env = env
@@ -798,7 +795,7 @@ def __init__(
798795
expr,
799796
engine: str = "numexpr",
800797
parser: str = "pandas",
801-
env: Optional[Scope] = None,
798+
env: Scope | None = None,
802799
level: int = 0,
803800
):
804801
self.expr = expr

pandas/core/computation/expressions.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,9 @@
55
Offer fast expression evaluation through numexpr
66
77
"""
8+
from __future__ import annotations
9+
810
import operator
9-
from typing import (
10-
List,
11-
Optional,
12-
Set,
13-
)
1411
import warnings
1512

1613
import numpy as np
@@ -25,11 +22,11 @@
2522
if NUMEXPR_INSTALLED:
2623
import numexpr as ne
2724

28-
_TEST_MODE: Optional[bool] = None
29-
_TEST_RESULT: List[bool] = []
25+
_TEST_MODE: bool | None = None
26+
_TEST_RESULT: list[bool] = []
3027
USE_NUMEXPR = NUMEXPR_INSTALLED
31-
_evaluate: Optional[FuncType] = None
32-
_where: Optional[FuncType] = None
28+
_evaluate: FuncType | None = None
29+
_where: FuncType | None = None
3330

3431
# the set of dtypes that we will allow pass to numexpr
3532
_ALLOWED_DTYPES = {
@@ -79,7 +76,7 @@ def _can_use_numexpr(op, op_str, a, b, dtype_check):
7976
# required min elements (otherwise we are adding overhead)
8077
if a.size > _MIN_ELEMENTS:
8178
# check for dtype compatibility
82-
dtypes: Set[str] = set()
79+
dtypes: set[str] = set()
8380
for o in [a, b]:
8481
# ndarray and Series Case
8582
if hasattr(o, "dtype"):
@@ -277,7 +274,7 @@ def _store_test_result(used_numexpr: bool) -> None:
277274
_TEST_RESULT.append(used_numexpr)
278275

279276

280-
def get_test_result() -> List[bool]:
277+
def get_test_result() -> list[bool]:
281278
"""
282279
Get test result and reset test_results.
283280
"""

pandas/core/dtypes/common.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"""
22
Common type operations.
33
"""
4+
from __future__ import annotations
45

56
from typing import (
67
Any,
78
Callable,
8-
Union,
99
)
1010
import warnings
1111

@@ -102,7 +102,7 @@ def ensure_float(arr):
102102
ensure_object = algos.ensure_object
103103

104104

105-
def ensure_str(value: Union[bytes, Any]) -> str:
105+
def ensure_str(value: bytes | Any) -> str:
106106
"""
107107
Ensure that bytes and non-strings get converted into ``str`` objects.
108108
"""
@@ -113,7 +113,7 @@ def ensure_str(value: Union[bytes, Any]) -> str:
113113
return value
114114

115115

116-
def ensure_python_int(value: Union[int, np.integer]) -> int:
116+
def ensure_python_int(value: int | np.integer) -> int:
117117
"""
118118
Ensure that a value is a python int.
119119

pandas/core/indexes/timedeltas.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
""" implement the TimedeltaIndex """
2+
from __future__ import annotations
23

34
from pandas._libs import (
45
index as libindex,

pandas/io/parsers/python_parser.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,7 @@
1818
import numpy as np
1919

2020
import pandas._libs.lib as lib
21-
from pandas._typing import (
22-
FilePathOrBuffer,
23-
Union,
24-
)
21+
from pandas._typing import FilePathOrBuffer
2522
from pandas.errors import (
2623
EmptyDataError,
2724
ParserError,
@@ -42,7 +39,7 @@
4239

4340

4441
class PythonParser(ParserBase):
45-
def __init__(self, f: Union[FilePathOrBuffer, list], **kwds):
42+
def __init__(self, f: FilePathOrBuffer | list, **kwds):
4643
"""
4744
Workhorse function for processing nested list into DataFrame
4845
"""

0 commit comments

Comments
 (0)