mirror of
https://github.com/pybind/pybind11.git
synced 2026-03-14 20:27:47 +00:00
Access C++ hash functions from Python and vice versa (#1034)
There are two separate additions: 1. `py::hash(obj)` is equivalent to the Python `hash(obj)`. 2. `.def(hash(py::self))` registers the hash function defined by `std::hash<T>` as the Python hash function.
This commit is contained in:
committed by
Dean Moldovan
parent
29b99a11a4
commit
37de2da9dd
@@ -220,3 +220,19 @@ def test_print(capture):
|
||||
if debug_enabled else
|
||||
"arguments to Python object (compile in debug mode for details)"
|
||||
)
|
||||
|
||||
|
||||
def test_hash():
|
||||
class Hashable(object):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def __hash__(self):
|
||||
return self.value
|
||||
|
||||
class Unhashable(object):
|
||||
__hash__ = None
|
||||
|
||||
assert m.hash_function(Hashable(42)) == 42
|
||||
with pytest.raises(TypeError):
|
||||
m.hash_function(Unhashable())
|
||||
|
||||
Reference in New Issue
Block a user