Skip to content

Commit 8595981

Browse files
committed
refactor to validate_all_hashable
1 parent 82466c9 commit 8595981

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

pandas/core/dtypes/common.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1732,6 +1732,29 @@ def _validate_date_like_dtype(dtype) -> None:
17321732
)
17331733

17341734

1735+
def validate_all_hashable(*args) -> None:
1736+
"""
1737+
Return None if all args are hashable, else raise a TypeError.
1738+
1739+
Raises
1740+
------
1741+
TypeError : If an argument is not hashable
1742+
1743+
Returns
1744+
-------
1745+
None
1746+
1747+
Examples
1748+
--------
1749+
>>> validate_all_hashable(1)
1750+
1751+
>>> validate_all_hashable([1])
1752+
ValueError: All elements must be hashable
1753+
"""
1754+
if not all(is_hashable(x) for x in args):
1755+
raise TypeError("All elements must be hashable")
1756+
1757+
17351758
def pandas_dtype(dtype) -> DtypeObj:
17361759
"""
17371760
Convert input into a pandas only dtype object or a numpy dtype object.

pandas/core/indexes/base.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
is_timedelta64_dtype,
5959
is_unsigned_integer_dtype,
6060
pandas_dtype,
61+
validate_all_hashable,
6162
)
6263
from pandas.core.dtypes.concat import concat_compat
6364
from pandas.core.dtypes.generic import (
@@ -1208,10 +1209,9 @@ def _validate_names(self, name=None, names=None, deep: bool = False) -> List[Lab
12081209
raise ValueError(
12091210
f"Length of new names must be {len(self.names)}, got {len(new_names)}"
12101211
)
1212+
12111213
# All items in 'new_names' need to be hashable
1212-
for new_name in new_names:
1213-
if not is_hashable(new_name):
1214-
raise TypeError(f"{type(self).__name__}.name must be a hashable type")
1214+
validate_all_hashable(*new_names)
12151215

12161216
return new_names
12171217

@@ -1241,9 +1241,8 @@ def _set_names(self, values, level=None):
12411241

12421242
# GH 20527
12431243
# All items in 'name' need to be hashable:
1244-
for name in values:
1245-
if not is_hashable(name):
1246-
raise TypeError(f"{type(self).__name__}.name must be a hashable type")
1244+
validate_all_hashable(*values)
1245+
12471246
self._name = values[0]
12481247

12491248
names = property(fset=_set_names, fget=_get_names)

0 commit comments

Comments
 (0)