Skip to content

BUG: raise on non-hashable in __contains__ #30902

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jan 20, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions pandas/_libs/index.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ cdef class IndexEngine:
self.over_size_threshold = n >= _SIZE_CUTOFF
self.clear_mapping()

def __contains__(self, object val):
def __contains__(self, val: object) -> bool:
# We assume before we get here:
# - val is hashable
self._ensure_mapping_populated()
hash(val)
return val in self.mapping

cpdef get_value(self, ndarray arr, object key, object tz=None):
Expand All @@ -85,7 +86,6 @@ cdef class IndexEngine:
"""
cdef:
object loc
void* data_ptr

loc = self.get_loc(key)
if isinstance(loc, slice) or util.is_array(loc):
Expand All @@ -101,7 +101,6 @@ cdef class IndexEngine:
"""
cdef:
object loc
void* data_ptr

loc = self.get_loc(key)
value = convert_scalar(arr, value)
Expand Down Expand Up @@ -409,7 +408,9 @@ cdef class DatetimeEngine(Int64Engine):
cdef _get_box_dtype(self):
return 'M8[ns]'

def __contains__(self, object val):
def __contains__(self, val: object) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

# We assume before we get here:
# - val is hashable
cdef:
int64_t loc

Expand Down Expand Up @@ -717,7 +718,9 @@ cdef class BaseMultiIndexCodesEngine:

return indexer

def __contains__(self, object val):
def __contains__(self, val: object) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

# We assume before we get here:
# - val is hashable
# Default __contains__ looks in the underlying mapping, which in this
# case only contains integer representations.
try:
Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ def __contains__(self, key) -> bool:
if is_scalar(key) and isna(key):
return self.hasnans

hash(key)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this is to check that key is hashable. can you not type key as Hashable?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's not a run-time check

return contains(self, key, container=self._engine)

def __array__(self, dtype=None) -> np.ndarray:
Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ def equals(self, other) -> bool:

@Appender(_index_shared_docs["contains"] % _index_doc_kwargs)
def __contains__(self, key):
hash(key)
try:
res = self.get_loc(key)
return (
Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ def __contains__(self, key) -> bool:
-------
bool
"""
hash(key)
if not isinstance(key, Interval):
return False

Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ def equals(self, other) -> bool:
return False

def __contains__(self, other) -> bool:
hash(other)
if super().__contains__(other):
return True

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,11 +377,11 @@ def __contains__(self, key) -> bool:
else:
return key.ordinal in self._engine
else:
hash(key)
try:
self.get_loc(key)
return True
except (TypeError, KeyError):
# TypeError can be reached if we pass a tuple that is not hashable
except KeyError:
return False

@cache_readonly
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,3 +883,11 @@ def test_getitem_2d_deprecated(self):
res = idx[:, None]

assert isinstance(res, np.ndarray), type(res)

def test_contains_requires_hashable(self):
idx = self.create_index()
with pytest.raises(TypeError, match="unhashable type"):
[] in idx

with pytest.raises(TypeError):
{} in idx._engine