Skip to content

Commit 2ca2161

Browse files
CLN: replace Dict with Mapping to annotate arguments (pandas-dev#29155)
1 parent a8e510b commit 2ca2161

File tree

10 files changed

+57
-37
lines changed

10 files changed

+57
-37
lines changed

pandas/_typing.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
from pathlib import Path
2-
from typing import IO, TYPE_CHECKING, AnyStr, Iterable, Optional, TypeVar, Union
2+
from typing import (
3+
IO,
4+
TYPE_CHECKING,
5+
AnyStr,
6+
Dict,
7+
Iterable,
8+
List,
9+
Optional,
10+
TypeVar,
11+
Union,
12+
)
313

414
import numpy as np
515

@@ -25,6 +35,7 @@
2535
Scalar = Union[str, int, float, bool]
2636
Axis = Union[str, int]
2737
Ordered = Optional[bool]
38+
JSONSerializable = Union[Scalar, List, Dict]
2839

2940
# use Collection after we drop support for py35
3041
Axes = Iterable

pandas/core/dtypes/dtypes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
""" define extension dtypes """
22
import re
3-
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
3+
from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Type, Union, cast
44
import warnings
55

66
import numpy as np
@@ -351,7 +351,7 @@ def _finalize(self, categories, ordered: Ordered, fastpath: bool = False) -> Non
351351
self._ordered = ordered if ordered is not ordered_sentinel else None
352352
self._ordered_from_sentinel = ordered is ordered_sentinel
353353

354-
def __setstate__(self, state: Dict[str_type, Any]) -> None:
354+
def __setstate__(self, state: MutableMapping[str_type, Any]) -> None:
355355
# for pickle compat. __get_state__ is defined in the
356356
# PandasExtensionDtype superclass and uses the public properties to
357357
# pickle -> need to set the settable private ones here (see GH26067)

pandas/core/generic.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@
6767
from pandas.core.dtypes.missing import isna, notna
6868

6969
import pandas as pd
70-
from pandas._typing import Dtype, FilePathOrBuffer, Scalar
70+
from pandas._typing import Dtype, FilePathOrBuffer, JSONSerializable
7171
from pandas.core import missing, nanops
7272
import pandas.core.algorithms as algos
7373
from pandas.core.base import PandasObject, SelectionMixin
@@ -2299,7 +2299,7 @@ def to_json(
22992299
double_precision: int = 10,
23002300
force_ascii: bool_t = True,
23012301
date_unit: str = "ms",
2302-
default_handler: Optional[Callable[[Any], Union[Scalar, List, Dict]]] = None,
2302+
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
23032303
lines: bool_t = False,
23042304
compression: Optional[str] = "infer",
23052305
index: bool_t = True,
@@ -3155,7 +3155,7 @@ def to_csv(
31553155
index_label: Optional[Union[bool_t, str, Sequence[Hashable]]] = None,
31563156
mode: str = "w",
31573157
encoding: Optional[str] = None,
3158-
compression: Optional[Union[str, Dict[str, str]]] = "infer",
3158+
compression: Optional[Union[str, Mapping[str, str]]] = "infer",
31593159
quoting: Optional[int] = None,
31603160
quotechar: str = '"',
31613161
line_terminator: Optional[str] = None,

pandas/core/ops/array_ops.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
ExtensionArrays.
44
"""
55
import operator
6-
from typing import Any, Dict, Union
6+
from typing import Any, Mapping, Union
77

88
import numpy as np
99

@@ -161,7 +161,7 @@ def arithmetic_op(
161161
right: Any,
162162
op,
163163
str_rep: str,
164-
eval_kwargs: Dict[str, bool],
164+
eval_kwargs: Mapping[str, bool],
165165
):
166166
"""
167167
Evaluate an arithmetic operation `+`, `-`, `*`, `/`, `//`, `%`, `**`, ...

pandas/io/common.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
BinaryIO,
1616
Dict,
1717
List,
18+
Mapping,
1819
Optional,
1920
TextIO,
2021
Tuple,
@@ -276,16 +277,16 @@ def file_path_to_url(path: str) -> str:
276277

277278

278279
def _get_compression_method(
279-
compression: Optional[Union[str, Dict[str, str]]]
280+
compression: Optional[Union[str, Mapping[str, str]]]
280281
) -> Tuple[Optional[str], Dict[str, str]]:
281282
"""
282283
Simplifies a compression argument to a compression method string and
283-
a dict containing additional arguments.
284+
a mapping containing additional arguments.
284285
285286
Parameters
286287
----------
287-
compression : str or dict
288-
If string, specifies the compression method. If dict, value at key
288+
compression : str or mapping
289+
If string, specifies the compression method. If mapping, value at key
289290
'method' specifies compression method.
290291
291292
Returns
@@ -295,15 +296,14 @@ def _get_compression_method(
295296
296297
Raises
297298
------
298-
ValueError on dict missing 'method' key
299+
ValueError on mapping missing 'method' key
299300
"""
300-
# Handle dict
301-
if isinstance(compression, dict):
302-
compression_args = compression.copy()
301+
if isinstance(compression, Mapping):
302+
compression_args = dict(compression)
303303
try:
304304
compression = compression_args.pop("method")
305305
except KeyError:
306-
raise ValueError("If dict, compression must have key 'method'")
306+
raise ValueError("If mapping, compression must have key 'method'")
307307
else:
308308
compression_args = {}
309309
return compression, compression_args
@@ -368,7 +368,7 @@ def _get_handle(
368368
path_or_buf,
369369
mode: str,
370370
encoding=None,
371-
compression: Optional[Union[str, Dict[str, Any]]] = None,
371+
compression: Optional[Union[str, Mapping[str, Any]]] = None,
372372
memory_map: bool = False,
373373
is_text: bool = True,
374374
):

pandas/io/formats/format.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
Dict,
2121
Iterable,
2222
List,
23+
Mapping,
2324
Optional,
2425
Sequence,
2526
Tuple,
@@ -78,7 +79,7 @@
7879
from pandas import Series, DataFrame, Categorical
7980

8081
formatters_type = Union[
81-
List[Callable], Tuple[Callable, ...], Dict[Union[str, int], Callable]
82+
List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
8283
]
8384
float_format_type = Union[str, Callable, "EngFormatter"]
8485

pandas/io/formats/html.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from collections import OrderedDict
66
from textwrap import dedent
7-
from typing import IO, Any, Dict, Iterable, List, Optional, Tuple, Union, cast
7+
from typing import IO, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast
88

99
from pandas._config import get_option
1010

@@ -394,7 +394,7 @@ def _write_body(self, indent: int) -> None:
394394
self.write("</tbody>", indent)
395395

396396
def _write_regular_rows(
397-
self, fmt_values: Dict[int, List[str]], indent: int
397+
self, fmt_values: Mapping[int, List[str]], indent: int
398398
) -> None:
399399
truncate_h = self.fmt.truncate_h
400400
truncate_v = self.fmt.truncate_v
@@ -440,7 +440,7 @@ def _write_regular_rows(
440440
)
441441

442442
def _write_hierarchical_rows(
443-
self, fmt_values: Dict[int, List[str]], indent: int
443+
self, fmt_values: Mapping[int, List[str]], indent: int
444444
) -> None:
445445
template = 'rowspan="{span}" valign="top"'
446446

pandas/io/formats/printing.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,23 @@
33
"""
44

55
import sys
6-
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union
6+
from typing import (
7+
Any,
8+
Callable,
9+
Iterable,
10+
List,
11+
Mapping,
12+
Optional,
13+
Sequence,
14+
Tuple,
15+
Union,
16+
)
717

818
from pandas._config import get_option
919

1020
from pandas.core.dtypes.inference import is_sequence
1121

12-
EscapeChars = Union[Dict[str, str], Iterable[str]]
22+
EscapeChars = Union[Mapping[str, str], Iterable[str]]
1323

1424

1525
def adjoin(space: int, *lists: List[str], **kwargs) -> str:
@@ -119,7 +129,7 @@ def _pprint_seq(
119129

120130

121131
def _pprint_dict(
122-
seq: Dict, _nest_lvl: int = 0, max_seq_items: Optional[int] = None, **kwds
132+
seq: Mapping, _nest_lvl: int = 0, max_seq_items: Optional[int] = None, **kwds
123133
) -> str:
124134
"""
125135
internal. pprinter for iterables. you should probably use pprint_thing()

pandas/io/json/_json.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from io import StringIO
33
from itertools import islice
44
import os
5-
from typing import Any, Callable, Dict, List, Optional, Type, Union
5+
from typing import Any, Callable, Optional, Type
66

77
import numpy as np
88

@@ -13,7 +13,7 @@
1313
from pandas.core.dtypes.common import ensure_str, is_period_dtype
1414

1515
from pandas import DataFrame, MultiIndex, Series, compat, isna, to_datetime
16-
from pandas._typing import Scalar
16+
from pandas._typing import JSONSerializable
1717
from pandas.core.reshape.concat import concat
1818

1919
from pandas.io.common import (
@@ -34,8 +34,6 @@
3434

3535
TABLE_SCHEMA_VERSION = "0.20.0"
3636

37-
Serializable = Union[Scalar, List, Dict]
38-
3937

4038
# interface to/from
4139
def to_json(
@@ -46,7 +44,7 @@ def to_json(
4644
double_precision: int = 10,
4745
force_ascii: bool = True,
4846
date_unit: str = "ms",
49-
default_handler: Optional[Callable[[Any], Serializable]] = None,
47+
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
5048
lines: bool = False,
5149
compression: Optional[str] = "infer",
5250
index: bool = True,
@@ -110,7 +108,7 @@ def __init__(
110108
ensure_ascii: bool,
111109
date_unit: str,
112110
index: bool,
113-
default_handler: Optional[Callable[[Any], Serializable]] = None,
111+
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
114112
indent: int = 0,
115113
):
116114
self.obj = obj
@@ -153,7 +151,7 @@ def _write(
153151
ensure_ascii: bool,
154152
date_unit: str,
155153
iso_dates: bool,
156-
default_handler: Optional[Callable[[Any], Serializable]],
154+
default_handler: Optional[Callable[[Any], JSONSerializable]],
157155
indent: int,
158156
):
159157
return dumps(
@@ -186,7 +184,7 @@ def _write(
186184
ensure_ascii: bool,
187185
date_unit: str,
188186
iso_dates: bool,
189-
default_handler: Optional[Callable[[Any], Serializable]],
187+
default_handler: Optional[Callable[[Any], JSONSerializable]],
190188
indent: int,
191189
):
192190
if not self.index and orient == "split":
@@ -233,7 +231,7 @@ def _write(
233231
ensure_ascii: bool,
234232
date_unit: str,
235233
iso_dates: bool,
236-
default_handler: Optional[Callable[[Any], Serializable]],
234+
default_handler: Optional[Callable[[Any], JSONSerializable]],
237235
indent: int,
238236
):
239237
if not self.index and orient == "split":
@@ -263,7 +261,7 @@ def __init__(
263261
ensure_ascii: bool,
264262
date_unit: str,
265263
index: bool,
266-
default_handler: Optional[Callable[[Any], Serializable]] = None,
264+
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
267265
indent: int = 0,
268266
):
269267
"""

pandas/util/_decorators.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
from typing import (
55
Any,
66
Callable,
7-
Dict,
87
List,
8+
Mapping,
99
Optional,
1010
Tuple,
1111
Type,
@@ -104,7 +104,7 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]:
104104
def deprecate_kwarg(
105105
old_arg_name: str,
106106
new_arg_name: Optional[str],
107-
mapping: Optional[Union[Dict[Any, Any], Callable[[Any], Any]]] = None,
107+
mapping: Optional[Union[Mapping[Any, Any], Callable[[Any], Any]]] = None,
108108
stacklevel: int = 2,
109109
) -> Callable[..., Any]:
110110
"""

0 commit comments

Comments
 (0)