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:
Bruce Merry
2017-08-30 14:22:00 +02:00
committed by Dean Moldovan
parent 29b99a11a4
commit 37de2da9dd
7 changed files with 44 additions and 1 deletions

View File

@@ -28,7 +28,7 @@ enum op_id : int {
op_int, op_long, op_float, op_str, op_cmp, op_gt, op_ge, op_lt, op_le,
op_eq, op_ne, op_iadd, op_isub, op_imul, op_idiv, op_imod, op_ilshift,
op_irshift, op_iand, op_ixor, op_ior, op_complex, op_bool, op_nonzero,
op_repr, op_truediv, op_itruediv
op_repr, op_truediv, op_itruediv, op_hash
};
enum op_type : int {
@@ -148,6 +148,7 @@ PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
PYBIND11_UNARY_OPERATOR(int, int_, (int) l)

View File

@@ -390,6 +390,13 @@ inline void setattr(handle obj, handle name, handle value) {
inline void setattr(handle obj, const char *name, handle value) {
if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); }
}
inline ssize_t hash(handle obj) {
auto h = PyObject_Hash(obj.ptr());
if (h == -1) { throw error_already_set(); }
return h;
}
/// @} python_builtins
NAMESPACE_BEGIN(detail)