Skip to content

Commit 46cec9f

Browse files
TYP: replace Label alias from pandas._typing with Hashable (#39107)
1 parent 0f2c5d4 commit 46cec9f

33 files changed

+226
-187
lines changed

pandas/_typing.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,8 @@
8484
FrameOrSeries = TypeVar("FrameOrSeries", bound="NDFrame")
8585

8686
Axis = Union[str, int]
87-
Label = Optional[Hashable]
88-
IndexLabel = Union[Label, Sequence[Label]]
89-
Level = Union[Label, int]
87+
IndexLabel = Union[Hashable, Sequence[Hashable]]
88+
Level = Union[Hashable, int]
9089
Shape = Tuple[int, ...]
9190
Suffixes = Tuple[str, str]
9291
Ordered = Optional[bool]
@@ -99,11 +98,11 @@
9998
"ExtensionDtype", NpDtype, Type[Union[str, float, int, complex, bool, object]]
10099
]
101100
# DtypeArg specifies all allowable dtypes in a functions its dtype argument
102-
DtypeArg = Union[Dtype, Dict[Label, Dtype]]
101+
DtypeArg = Union[Dtype, Dict[Hashable, Dtype]]
103102
DtypeObj = Union[np.dtype, "ExtensionDtype"]
104103

105104
# For functions like rename that convert one label to another
106-
Renamer = Union[Mapping[Label, Any], Callable[[Label], Label]]
105+
Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]]
107106

108107
# to maintain type information across generic functions and parametrization
109108
T = TypeVar("T")
@@ -120,7 +119,7 @@
120119

121120
# types of `func` kwarg for DataFrame.aggregate and Series.aggregate
122121
AggFuncTypeBase = Union[Callable, str]
123-
AggFuncTypeDict = Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
122+
AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
124123
AggFuncType = Union[
125124
AggFuncTypeBase,
126125
List[AggFuncTypeBase],
@@ -155,8 +154,8 @@
155154
FormattersType = Union[
156155
List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
157156
]
158-
ColspaceType = Mapping[Label, Union[str, int]]
157+
ColspaceType = Mapping[Hashable, Union[str, int]]
159158
FloatFormatType = Union[str, Callable, "EngFormatter"]
160159
ColspaceArgType = Union[
161-
str, int, Sequence[Union[str, int]], Mapping[Label, Union[str, int]]
160+
str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]]
162161
]

pandas/core/aggregation.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
Callable,
1212
DefaultDict,
1313
Dict,
14+
Hashable,
1415
Iterable,
1516
List,
1617
Optional,
@@ -28,7 +29,6 @@
2829
Axis,
2930
FrameOrSeries,
3031
FrameOrSeriesUnion,
31-
Label,
3232
)
3333

3434
from pandas.core.dtypes.cast import is_nested_object
@@ -294,9 +294,9 @@ def maybe_mangle_lambdas(agg_spec: Any) -> Any:
294294
def relabel_result(
295295
result: FrameOrSeries,
296296
func: Dict[str, List[Union[Callable, str]]],
297-
columns: Iterable[Label],
297+
columns: Iterable[Hashable],
298298
order: Iterable[int],
299-
) -> Dict[Label, "Series"]:
299+
) -> Dict[Hashable, "Series"]:
300300
"""
301301
Internal function to reorder result if relabelling is True for
302302
dataframe.agg, and return the reordered result in dict.
@@ -323,7 +323,7 @@ def relabel_result(
323323
reordered_indexes = [
324324
pair[0] for pair in sorted(zip(columns, order), key=lambda t: t[1])
325325
]
326-
reordered_result_in_dict: Dict[Label, "Series"] = {}
326+
reordered_result_in_dict: Dict[Hashable, "Series"] = {}
327327
idx = 0
328328

329329
reorder_mask = not isinstance(result, ABCSeries) and len(result.columns) > 1
@@ -493,7 +493,7 @@ def transform_dict_like(
493493
# GH 15931 - deprecation of renaming keys
494494
raise SpecificationError("nested renamer is not supported")
495495

496-
results: Dict[Label, FrameOrSeriesUnion] = {}
496+
results: Dict[Hashable, FrameOrSeriesUnion] = {}
497497
for name, how in func.items():
498498
colg = obj._gotitem(name, ndim=1)
499499
try:

pandas/core/computation/parsing.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@
66
from keyword import iskeyword
77
import token
88
import tokenize
9-
from typing import Iterator, Tuple
10-
11-
from pandas._typing import Label
9+
from typing import Hashable, Iterator, Tuple
1210

1311
# A token value Python's tokenizer probably will never use.
1412
BACKTICK_QUOTED_STRING = 100
@@ -90,7 +88,7 @@ def clean_backtick_quoted_toks(tok: Tuple[int, str]) -> Tuple[int, str]:
9088
return toknum, tokval
9189

9290

93-
def clean_column_name(name: "Label") -> "Label":
91+
def clean_column_name(name: Hashable) -> Hashable:
9492
"""
9593
Function to emulate the cleaning of a backtick quoted name.
9694

pandas/core/frame.py

+16-17
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@
6161
FrameOrSeriesUnion,
6262
IndexKeyFunc,
6363
IndexLabel,
64-
Label,
6564
Level,
6665
PythonFuncType,
6766
Renamer,
@@ -992,7 +991,7 @@ def style(self) -> Styler:
992991
"""
993992

994993
@Appender(_shared_docs["items"])
995-
def items(self) -> Iterable[Tuple[Label, Series]]:
994+
def items(self) -> Iterable[Tuple[Hashable, Series]]:
996995
if self.columns.is_unique and hasattr(self, "_item_cache"):
997996
for k in self.columns:
998997
yield k, self._get_item_cache(k)
@@ -1001,10 +1000,10 @@ def items(self) -> Iterable[Tuple[Label, Series]]:
10011000
yield k, self._ixs(i, axis=1)
10021001

10031002
@Appender(_shared_docs["items"])
1004-
def iteritems(self) -> Iterable[Tuple[Label, Series]]:
1003+
def iteritems(self) -> Iterable[Tuple[Hashable, Series]]:
10051004
yield from self.items()
10061005

1007-
def iterrows(self) -> Iterable[Tuple[Label, Series]]:
1006+
def iterrows(self) -> Iterable[Tuple[Hashable, Series]]:
10081007
"""
10091008
Iterate over DataFrame rows as (index, Series) pairs.
10101009
@@ -2121,14 +2120,14 @@ def _from_arrays(
21212120
def to_stata(
21222121
self,
21232122
path: FilePathOrBuffer,
2124-
convert_dates: Optional[Dict[Label, str]] = None,
2123+
convert_dates: Optional[Dict[Hashable, str]] = None,
21252124
write_index: bool = True,
21262125
byteorder: Optional[str] = None,
21272126
time_stamp: Optional[datetime.datetime] = None,
21282127
data_label: Optional[str] = None,
2129-
variable_labels: Optional[Dict[Label, str]] = None,
2128+
variable_labels: Optional[Dict[Hashable, str]] = None,
21302129
version: Optional[int] = 114,
2131-
convert_strl: Optional[Sequence[Label]] = None,
2130+
convert_strl: Optional[Sequence[Hashable]] = None,
21322131
compression: CompressionOptions = "infer",
21332132
storage_options: StorageOptions = None,
21342133
) -> None:
@@ -4483,7 +4482,7 @@ def fillna(
44834482
downcast=downcast,
44844483
)
44854484

4486-
def pop(self, item: Label) -> Series:
4485+
def pop(self, item: Hashable) -> Series:
44874486
"""
44884487
Return item and drop from frame. Raise KeyError if not found.
44894488
@@ -4546,7 +4545,7 @@ def replace(
45464545
)
45474546

45484547
def _replace_columnwise(
4549-
self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex
4548+
self, mapping: Dict[Hashable, Tuple[Any, Any]], inplace: bool, regex
45504549
):
45514550
"""
45524551
Dispatch to Series.replace column-wise.
@@ -4724,7 +4723,7 @@ def set_index(
47244723
"one-dimensional arrays."
47254724
)
47264725

4727-
missing: List[Label] = []
4726+
missing: List[Hashable] = []
47284727
for col in keys:
47294728
if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)):
47304729
# arrays are fine as long as they are one-dimensional
@@ -4752,7 +4751,7 @@ def set_index(
47524751
frame = self.copy()
47534752

47544753
arrays = []
4755-
names: List[Label] = []
4754+
names: List[Hashable] = []
47564755
if append:
47574756
names = list(self.index.names)
47584757
if isinstance(self.index, MultiIndex):
@@ -4761,7 +4760,7 @@ def set_index(
47614760
else:
47624761
arrays.append(self.index)
47634762

4764-
to_remove: List[Label] = []
4763+
to_remove: List[Hashable] = []
47654764
for col in keys:
47664765
if isinstance(col, MultiIndex):
47674766
for n in range(col.nlevels):
@@ -4819,7 +4818,7 @@ def reset_index( # type: ignore[misc]
48194818
drop: bool = ...,
48204819
inplace: Literal[False] = ...,
48214820
col_level: Hashable = ...,
4822-
col_fill: Label = ...,
4821+
col_fill: Hashable = ...,
48234822
) -> DataFrame:
48244823
...
48254824

@@ -4830,7 +4829,7 @@ def reset_index(
48304829
drop: bool = ...,
48314830
inplace: Literal[True] = ...,
48324831
col_level: Hashable = ...,
4833-
col_fill: Label = ...,
4832+
col_fill: Hashable = ...,
48344833
) -> None:
48354834
...
48364835

@@ -4840,7 +4839,7 @@ def reset_index(
48404839
drop: bool = False,
48414840
inplace: bool = False,
48424841
col_level: Hashable = 0,
4843-
col_fill: Label = "",
4842+
col_fill: Hashable = "",
48444843
) -> Optional[DataFrame]:
48454844
"""
48464845
Reset the index, or a level of it.
@@ -5630,7 +5629,7 @@ def sort_index(
56305629

56315630
def value_counts(
56325631
self,
5633-
subset: Optional[Sequence[Label]] = None,
5632+
subset: Optional[Sequence[Hashable]] = None,
56345633
normalize: bool = False,
56355634
sort: bool = True,
56365635
ascending: bool = False,
@@ -7511,7 +7510,7 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame:
75117510

75127511
def _gotitem(
75137512
self,
7514-
key: Union[Label, List[Label]],
7513+
key: IndexLabel,
75157514
ndim: int,
75167515
subset: Optional[FrameOrSeriesUnion] = None,
75177516
) -> FrameOrSeriesUnion:

pandas/core/generic.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@
4444
IndexKeyFunc,
4545
IndexLabel,
4646
JSONSerializable,
47-
Label,
4847
Level,
4948
NpDtype,
5049
Renamer,
@@ -526,7 +525,7 @@ def _get_axis_resolvers(self, axis: str) -> Dict[str, Union[Series, MultiIndex]]
526525
return d
527526

528527
@final
529-
def _get_index_resolvers(self) -> Dict[Label, Union[Series, MultiIndex]]:
528+
def _get_index_resolvers(self) -> Dict[Hashable, Union[Series, MultiIndex]]:
530529
from pandas.core.computation.parsing import clean_column_name
531530

532531
d: Dict[str, Union[Series, MultiIndex]] = {}
@@ -536,7 +535,7 @@ def _get_index_resolvers(self) -> Dict[Label, Union[Series, MultiIndex]]:
536535
return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)}
537536

538537
@final
539-
def _get_cleaned_column_resolvers(self) -> Dict[Label, Series]:
538+
def _get_cleaned_column_resolvers(self) -> Dict[Hashable, Series]:
540539
"""
541540
Return the special character free column resolvers of a dataframe.
542541
@@ -776,7 +775,7 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries:
776775
result = self.set_axis(new_labels, axis=axis, inplace=False)
777776
return result
778777

779-
def pop(self, item: Label) -> Union[Series, Any]:
778+
def pop(self, item: Hashable) -> Union[Series, Any]:
780779
result = self[item]
781780
del self[item]
782781
if self.ndim == 2:
@@ -3225,7 +3224,7 @@ def to_csv(
32253224
sep: str = ",",
32263225
na_rep: str = "",
32273226
float_format: Optional[str] = None,
3228-
columns: Optional[Sequence[Label]] = None,
3227+
columns: Optional[Sequence[Hashable]] = None,
32293228
header: Union[bool_t, List[str]] = True,
32303229
index: bool_t = True,
32313230
index_label: Optional[IndexLabel] = None,
@@ -10214,7 +10213,7 @@ def describe_1d(data) -> "Series":
1021410213

1021510214
ldesc = [describe_1d(s) for _, s in data.items()]
1021610215
# set a convenient order for rows
10217-
names: List[Label] = []
10216+
names: List[Hashable] = []
1021810217
ldesc_indexes = sorted((x.index for x in ldesc), key=len)
1021910218
for idxnames in ldesc_indexes:
1022010219
for name in idxnames:

pandas/core/groupby/generic.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
Callable,
1616
Dict,
1717
FrozenSet,
18+
Hashable,
1819
Iterable,
1920
List,
2021
Mapping,
@@ -30,7 +31,7 @@
3031
import numpy as np
3132

3233
from pandas._libs import lib, reduction as libreduction
33-
from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion, Label
34+
from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion
3435
from pandas.util._decorators import Appender, Substitution, doc
3536

3637
from pandas.core.dtypes.cast import (
@@ -1129,7 +1130,7 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame:
11291130
axis = self.axis
11301131
obj = self._obj_with_exclusions
11311132

1132-
result: Dict[Label, Union[NDFrame, np.ndarray]] = {}
1133+
result: Dict[Hashable, Union[NDFrame, np.ndarray]] = {}
11331134
if axis != obj._info_axis_number:
11341135
for name, data in self:
11351136
fres = func(data, *args, **kwargs)

pandas/core/groupby/groupby.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@ class providing the base-class of operations.
4343
FrameOrSeries,
4444
FrameOrSeriesUnion,
4545
IndexLabel,
46-
Label,
4746
Scalar,
4847
final,
4948
)
@@ -522,7 +521,7 @@ def __init__(
522521
axis: int = 0,
523522
level: Optional[IndexLabel] = None,
524523
grouper: Optional["ops.BaseGrouper"] = None,
525-
exclusions: Optional[Set[Label]] = None,
524+
exclusions: Optional[Set[Hashable]] = None,
526525
selection: Optional[IndexLabel] = None,
527526
as_index: bool = True,
528527
sort: bool = True,
@@ -860,7 +859,7 @@ def get_group(self, name, obj=None):
860859

861860
return obj._take_with_is_copy(inds, axis=self.axis)
862861

863-
def __iter__(self) -> Iterator[Tuple[Label, FrameOrSeries]]:
862+
def __iter__(self) -> Iterator[Tuple[Hashable, FrameOrSeries]]:
864863
"""
865864
Groupby iterator.
866865

pandas/core/groupby/grouper.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import numpy as np
99

10-
from pandas._typing import FrameOrSeries, Label, final
10+
from pandas._typing import FrameOrSeries, final
1111
from pandas.errors import InvalidIndexError
1212
from pandas.util._decorators import cache_readonly
1313

@@ -616,7 +616,7 @@ def get_grouper(
616616
mutated: bool = False,
617617
validate: bool = True,
618618
dropna: bool = True,
619-
) -> Tuple["ops.BaseGrouper", Set[Label], FrameOrSeries]:
619+
) -> Tuple["ops.BaseGrouper", Set[Hashable], FrameOrSeries]:
620620
"""
621621
Create and return a BaseGrouper, which is an internal
622622
mapping of how to create the grouper indexers.
@@ -741,7 +741,7 @@ def get_grouper(
741741
levels = [level] * len(keys)
742742

743743
groupings: List[Grouping] = []
744-
exclusions: Set[Label] = set()
744+
exclusions: Set[Hashable] = set()
745745

746746
# if the actual grouper should be obj[key]
747747
def is_in_axis(key) -> bool:

0 commit comments

Comments
 (0)