Skip to content

Modify hash(pd.NA) to avoid integer hash collisions #30150

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 4 commits into from
Dec 24, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion pandas/_libs/missing.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@ from pandas._libs.tslibs.np_datetime cimport (
from pandas._libs.tslibs.nattype cimport (
checknull_with_nat, c_NaT as NaT, is_null_datetimelike)

from pandas.compat import is_platform_32bit


cdef:
float64_t INF = <float64_t>np.inf
float64_t NEGINF = -INF

int64_t NPY_NAT = util.get_nat()

bint is_32bit = is_platform_32bit()


cpdef bint checknull(object val):
"""
Expand Down Expand Up @@ -345,7 +349,9 @@ class NAType(C_NAType):
raise TypeError("boolean value of NA is ambiguous")

def __hash__(self):
return id(self)
# GH 30013: Ensure hash is large enough to avoid hash collisions with integers
exponent = 31 if is_32bit else 61
return 2 ** exponent - 1

# Binary arithmetic and comparison ops -> propagate

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/scalar/test_na_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,20 @@ def test_series_isna():
s = pd.Series([1, NA], dtype=object)
expected = pd.Series([False, True])
tm.assert_series_equal(s.isna(), expected)


def test_integer_hash_collision_dict():
# GH 30013
result = {NA: "foo", hash(NA): "bar"}

assert result[NA] == "foo"
assert result[hash(NA)] == "bar"


def test_integer_hash_collision_set():
# GH 30013
result = {NA, hash(NA)}

assert len(result) == 2
assert NA in result
assert hash(NA) in result