Skip to content

Commit ce3bac9

Browse files
TYP: use from __future__ import annotations more (#41892)
1 parent 384f414 commit ce3bac9

File tree

9 files changed

+82
-104
lines changed

9 files changed

+82
-104
lines changed

pandas/io/json/_json.py

+24-26
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from abc import (
24
ABC,
35
abstractmethod,
@@ -10,10 +12,6 @@
1012
Any,
1113
Callable,
1214
Mapping,
13-
Optional,
14-
Tuple,
15-
Type,
16-
Union,
1715
)
1816

1917
import numpy as np
@@ -78,12 +76,12 @@
7876
def to_json(
7977
path_or_buf,
8078
obj: NDFrame,
81-
orient: Optional[str] = None,
79+
orient: str | None = None,
8280
date_format: str = "epoch",
8381
double_precision: int = 10,
8482
force_ascii: bool = True,
8583
date_unit: str = "ms",
86-
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
84+
default_handler: Callable[[Any], JSONSerializable] | None = None,
8785
lines: bool = False,
8886
compression: CompressionOptions = "infer",
8987
index: bool = True,
@@ -102,7 +100,7 @@ def to_json(
102100
if orient == "table" and isinstance(obj, Series):
103101
obj = obj.to_frame(name=obj.name or "values")
104102

105-
writer: Type[Writer]
103+
writer: type[Writer]
106104
if orient == "table" and isinstance(obj, DataFrame):
107105
writer = JSONTableWriter
108106
elif isinstance(obj, Series):
@@ -143,13 +141,13 @@ class Writer(ABC):
143141
def __init__(
144142
self,
145143
obj,
146-
orient: Optional[str],
144+
orient: str | None,
147145
date_format: str,
148146
double_precision: int,
149147
ensure_ascii: bool,
150148
date_unit: str,
151149
index: bool,
152-
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
150+
default_handler: Callable[[Any], JSONSerializable] | None = None,
153151
indent: int = 0,
154152
):
155153
self.obj = obj
@@ -187,7 +185,7 @@ def write(self):
187185

188186
@property
189187
@abstractmethod
190-
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
188+
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
191189
"""Object to write in JSON format."""
192190
pass
193191

@@ -196,7 +194,7 @@ class SeriesWriter(Writer):
196194
_default_orient = "index"
197195

198196
@property
199-
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
197+
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
200198
if not self.index and self.orient == "split":
201199
return {"name": self.obj.name, "data": self.obj.values}
202200
else:
@@ -211,7 +209,7 @@ class FrameWriter(Writer):
211209
_default_orient = "columns"
212210

213211
@property
214-
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
212+
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
215213
if not self.index and self.orient == "split":
216214
obj_to_write = self.obj.to_dict(orient="split")
217215
del obj_to_write["index"]
@@ -243,13 +241,13 @@ class JSONTableWriter(FrameWriter):
243241
def __init__(
244242
self,
245243
obj,
246-
orient: Optional[str],
244+
orient: str | None,
247245
date_format: str,
248246
double_precision: int,
249247
ensure_ascii: bool,
250248
date_unit: str,
251249
index: bool,
252-
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
250+
default_handler: Callable[[Any], JSONSerializable] | None = None,
253251
indent: int = 0,
254252
):
255253
"""
@@ -313,7 +311,7 @@ def __init__(
313311
self.index = index
314312

315313
@property
316-
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
314+
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
317315
return {"schema": self.schema, "data": self.obj}
318316

319317

@@ -326,19 +324,19 @@ def read_json(
326324
path_or_buf=None,
327325
orient=None,
328326
typ="frame",
329-
dtype: Optional[DtypeArg] = None,
327+
dtype: DtypeArg | None = None,
330328
convert_axes=None,
331329
convert_dates=True,
332330
keep_default_dates: bool = True,
333331
numpy: bool = False,
334332
precise_float: bool = False,
335333
date_unit=None,
336334
encoding=None,
337-
encoding_errors: Optional[str] = "strict",
335+
encoding_errors: str | None = "strict",
338336
lines: bool = False,
339-
chunksize: Optional[int] = None,
337+
chunksize: int | None = None,
340338
compression: CompressionOptions = "infer",
341-
nrows: Optional[int] = None,
339+
nrows: int | None = None,
342340
storage_options: StorageOptions = None,
343341
):
344342
"""
@@ -639,11 +637,11 @@ def __init__(
639637
date_unit,
640638
encoding,
641639
lines: bool,
642-
chunksize: Optional[int],
640+
chunksize: int | None,
643641
compression: CompressionOptions,
644-
nrows: Optional[int],
642+
nrows: int | None,
645643
storage_options: StorageOptions = None,
646-
encoding_errors: Optional[str] = "strict",
644+
encoding_errors: str | None = "strict",
647645
):
648646

649647
self.orient = orient
@@ -663,7 +661,7 @@ def __init__(
663661
self.nrows_seen = 0
664662
self.nrows = nrows
665663
self.encoding_errors = encoding_errors
666-
self.handles: Optional[IOHandles] = None
664+
self.handles: IOHandles | None = None
667665

668666
if self.chunksize is not None:
669667
self.chunksize = validate_integer("chunksize", self.chunksize, 1)
@@ -816,7 +814,7 @@ def __exit__(self, exc_type, exc_value, traceback):
816814

817815

818816
class Parser:
819-
_split_keys: Tuple[str, ...]
817+
_split_keys: tuple[str, ...]
820818
_default_orient: str
821819

822820
_STAMP_UNITS = ("s", "ms", "us", "ns")
@@ -831,7 +829,7 @@ def __init__(
831829
self,
832830
json,
833831
orient,
834-
dtype: Optional[DtypeArg] = None,
832+
dtype: DtypeArg | None = None,
835833
convert_axes=True,
836834
convert_dates=True,
837835
keep_default_dates=False,
@@ -865,7 +863,7 @@ def __init__(
865863
self.convert_dates = convert_dates
866864
self.date_unit = date_unit
867865
self.keep_default_dates = keep_default_dates
868-
self.obj: Optional[FrameOrSeriesUnion] = None
866+
self.obj: FrameOrSeriesUnion | None = None
869867

870868
def check_keys_split(self, decoded):
871869
"""

pandas/plotting/_matplotlib/converter.py

+9-13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import contextlib
24
import datetime as pydt
35
from datetime import (
@@ -6,13 +8,7 @@
68
tzinfo,
79
)
810
import functools
9-
from typing import (
10-
Any,
11-
Dict,
12-
List,
13-
Optional,
14-
Tuple,
15-
)
11+
from typing import Any
1612

1713
from dateutil.relativedelta import relativedelta
1814
import matplotlib.dates as dates
@@ -169,7 +165,7 @@ def convert(value, unit, axis):
169165
return value
170166

171167
@staticmethod
172-
def axisinfo(unit, axis) -> Optional[units.AxisInfo]:
168+
def axisinfo(unit, axis) -> units.AxisInfo | None:
173169
if unit != "time":
174170
return None
175171

@@ -319,7 +315,7 @@ def try_parse(values):
319315
return values
320316

321317
@staticmethod
322-
def axisinfo(unit: Optional[tzinfo], axis) -> units.AxisInfo:
318+
def axisinfo(unit: tzinfo | None, axis) -> units.AxisInfo:
323319
"""
324320
Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
325321
@@ -447,7 +443,7 @@ def autoscale(self):
447443
return self.nonsingular(vmin, vmax)
448444

449445

450-
def _from_ordinal(x, tz: Optional[tzinfo] = None) -> datetime:
446+
def _from_ordinal(x, tz: tzinfo | None = None) -> datetime:
451447
ix = int(x)
452448
dt = datetime.fromordinal(ix)
453449
remainder = float(x) - ix
@@ -476,7 +472,7 @@ def _from_ordinal(x, tz: Optional[tzinfo] = None) -> datetime:
476472
# -------------------------------------------------------------------------
477473

478474

479-
def _get_default_annual_spacing(nyears) -> Tuple[int, int]:
475+
def _get_default_annual_spacing(nyears) -> tuple[int, int]:
480476
"""
481477
Returns a default spacing between consecutive ticks for annual data.
482478
"""
@@ -1027,8 +1023,8 @@ def __init__(
10271023
freq = to_offset(freq)
10281024
self.format = None
10291025
self.freq = freq
1030-
self.locs: List[Any] = [] # unused, for matplotlib compat
1031-
self.formatdict: Optional[Dict[Any, Any]] = None
1026+
self.locs: list[Any] = [] # unused, for matplotlib compat
1027+
self.formatdict: dict[Any, Any] | None = None
10321028
self.isminor = minor_locator
10331029
self.isdynamic = dynamic_mode
10341030
self.offset = 0

pandas/tests/extension/base/ops.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
from typing import (
2-
Optional,
3-
Type,
4-
)
1+
from __future__ import annotations
52

63
import pytest
74

@@ -67,10 +64,10 @@ class BaseArithmeticOpsTests(BaseOpsUtil):
6764
* divmod_exc = TypeError
6865
"""
6966

70-
series_scalar_exc: Optional[Type[TypeError]] = TypeError
71-
frame_scalar_exc: Optional[Type[TypeError]] = TypeError
72-
series_array_exc: Optional[Type[TypeError]] = TypeError
73-
divmod_exc: Optional[Type[TypeError]] = TypeError
67+
series_scalar_exc: type[TypeError] | None = TypeError
68+
frame_scalar_exc: type[TypeError] | None = TypeError
69+
series_array_exc: type[TypeError] | None = TypeError
70+
divmod_exc: type[TypeError] | None = TypeError
7471

7572
def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
7673
# series & scalar

pandas/tests/io/parser/conftest.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1+
from __future__ import annotations
2+
13
import os
2-
from typing import (
3-
List,
4-
Optional,
5-
)
64

75
import pytest
86

@@ -13,9 +11,9 @@
1311

1412

1513
class BaseParser:
16-
engine: Optional[str] = None
14+
engine: str | None = None
1715
low_memory = True
18-
float_precision_choices: List[Optional[str]] = []
16+
float_precision_choices: list[str | None] = []
1917

2018
def update_kwargs(self, kwargs):
2119
kwargs = kwargs.copy()

pandas/tests/tseries/offsets/common.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
"""
22
Assertion helpers and base class for offsets tests
33
"""
4+
from __future__ import annotations
5+
46
from datetime import datetime
5-
from typing import (
6-
Optional,
7-
Type,
8-
)
97

108
from dateutil.tz.tz import tzlocal
119
import pytest
@@ -61,7 +59,7 @@ class WeekDay:
6159

6260

6361
class Base:
64-
_offset: Optional[Type[DateOffset]] = None
62+
_offset: type[DateOffset] | None = None
6563
d = Timestamp(datetime(2008, 1, 2))
6664

6765
timezones = [

0 commit comments

Comments
 (0)