Skip to content

Commit a0adc2e

Browse files
TYP: use from __future__ import annotations more
1 parent 4d10194 commit a0adc2e

File tree

10 files changed

+106
-133
lines changed

10 files changed

+106
-133
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/io/parsers/readers.py

+24-29
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
11
"""
22
Module contains tools for processing files into DataFrames or other objects
33
"""
4+
from __future__ import annotations
5+
46
from collections import abc
57
import csv
68
import sys
79
from textwrap import fill
8-
from typing import (
9-
Any,
10-
Dict,
11-
List,
12-
Optional,
13-
Set,
14-
Type,
15-
)
10+
from typing import Any
1611
import warnings
1712

1813
import numpy as np
@@ -413,8 +408,8 @@
413408
_c_unsupported = {"skipfooter"}
414409
_python_unsupported = {"low_memory", "float_precision"}
415410

416-
_deprecated_defaults: Dict[str, Any] = {"error_bad_lines": None, "warn_bad_lines": None}
417-
_deprecated_args: Set[str] = {"error_bad_lines", "warn_bad_lines"}
411+
_deprecated_defaults: dict[str, Any] = {"error_bad_lines": None, "warn_bad_lines": None}
412+
_deprecated_args: set[str] = {"error_bad_lines", "warn_bad_lines"}
418413

419414

420415
def validate_integer(name, val, min_val=0):
@@ -518,7 +513,7 @@ def read_csv(
518513
prefix=lib.no_default,
519514
mangle_dupe_cols=True,
520515
# General Parsing Configuration
521-
dtype: Optional[DtypeArg] = None,
516+
dtype: DtypeArg | None = None,
522517
engine=None,
523518
converters=None,
524519
true_values=None,
@@ -554,7 +549,7 @@ def read_csv(
554549
escapechar=None,
555550
comment=None,
556551
encoding=None,
557-
encoding_errors: Optional[str] = "strict",
552+
encoding_errors: str | None = "strict",
558553
dialect=None,
559554
# Error Handling
560555
error_bad_lines=None,
@@ -616,7 +611,7 @@ def read_table(
616611
prefix=lib.no_default,
617612
mangle_dupe_cols=True,
618613
# General Parsing Configuration
619-
dtype: Optional[DtypeArg] = None,
614+
dtype: DtypeArg | None = None,
620615
engine=None,
621616
converters=None,
622617
true_values=None,
@@ -659,7 +654,7 @@ def read_table(
659654
# TODO (2.0): set on_bad_lines to "error".
660655
# See _refine_defaults_read comment for why we do this.
661656
on_bad_lines=None,
662-
encoding_errors: Optional[str] = "strict",
657+
encoding_errors: str | None = "strict",
663658
# Internal
664659
delim_whitespace=False,
665660
low_memory=_c_parser_defaults["low_memory"],
@@ -823,7 +818,7 @@ def _get_options_with_defaults(self, engine):
823818
kwds = self.orig_options
824819

825820
options = {}
826-
default: Optional[object]
821+
default: object | None
827822

828823
for argname, default in parser_defaults.items():
829824
value = kwds.get(argname, default)
@@ -1033,7 +1028,7 @@ def __next__(self):
10331028
raise
10341029

10351030
def _make_engine(self, engine="c"):
1036-
mapping: Dict[str, Type[ParserBase]] = {
1031+
mapping: dict[str, type[ParserBase]] = {
10371032
"c": CParserWrapper,
10381033
"python": PythonParser,
10391034
"python-fwf": FixedWidthFieldParser,
@@ -1147,7 +1142,7 @@ def TextParser(*args, **kwds):
11471142

11481143

11491144
def _clean_na_values(na_values, keep_default_na=True):
1150-
na_fvalues: Union[Set, Dict]
1145+
na_fvalues: Union[set, dict]
11511146
if na_values is None:
11521147
if keep_default_na:
11531148
na_values = STR_NA_VALUES
@@ -1198,7 +1193,7 @@ def _floatify_na_values(na_values):
11981193

11991194
def _stringify_na_values(na_values):
12001195
""" return a stringified and numeric for these values """
1201-
result: List[Union[int, str, float]] = []
1196+
result: list[Union[int, str, float]] = []
12021197
for x in na_values:
12031198
result.append(str(x))
12041199
result.append(x)
@@ -1227,12 +1222,12 @@ def _refine_defaults_read(
12271222
delim_whitespace: bool,
12281223
engine: str,
12291224
sep: Union[str, object],
1230-
error_bad_lines: Optional[bool],
1231-
warn_bad_lines: Optional[bool],
1232-
on_bad_lines: Optional[str],
1233-
names: Union[Optional[ArrayLike], object],
1234-
prefix: Union[Optional[str], object],
1235-
defaults: Dict[str, Any],
1225+
error_bad_lines: bool | None,
1226+
warn_bad_lines: bool | None,
1227+
on_bad_lines: str | None,
1228+
names: Union[ArrayLike | None, object],
1229+
prefix: Union[str | None, object],
1230+
defaults: dict[str, Any],
12361231
):
12371232
"""Validate/refine default values of input parameters of read_csv, read_table.
12381233
@@ -1287,7 +1282,7 @@ def _refine_defaults_read(
12871282
"""
12881283
# fix types for sep, delimiter to Union(str, Any)
12891284
delim_default = defaults["delimiter"]
1290-
kwds: Dict[str, Any] = {}
1285+
kwds: dict[str, Any] = {}
12911286
# gh-23761
12921287
#
12931288
# When a dialect is passed, it overrides any of the overlapping
@@ -1381,7 +1376,7 @@ def _refine_defaults_read(
13811376
return kwds
13821377

13831378

1384-
def _extract_dialect(kwds: Dict[str, Any]) -> Optional[csv.Dialect]:
1379+
def _extract_dialect(kwds: dict[str, Any]) -> csv.Dialect | None:
13851380
"""
13861381
Extract concrete csv dialect instance.
13871382
@@ -1427,8 +1422,8 @@ def _validate_dialect(dialect: csv.Dialect) -> None:
14271422

14281423
def _merge_with_dialect_properties(
14291424
dialect: csv.Dialect,
1430-
defaults: Dict[str, Any],
1431-
) -> Dict[str, Any]:
1425+
defaults: dict[str, Any],
1426+
) -> dict[str, Any]:
14321427
"""
14331428
Merge default kwargs in TextFileReader with dialect parameters.
14341429
@@ -1477,7 +1472,7 @@ def _merge_with_dialect_properties(
14771472
return kwds
14781473

14791474

1480-
def _validate_skipfooter(kwds: Dict[str, Any]) -> None:
1475+
def _validate_skipfooter(kwds: dict[str, Any]) -> None:
14811476
"""
14821477
Check whether skipfooter is compatible with other kwargs in TextFileReader.
14831478

0 commit comments

Comments
 (0)