Skip to content

Commit

Permalink
added nb::hash wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
wjakob committed May 24, 2024
1 parent 38990ea commit 01fafa5
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/api_core.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2744,6 +2744,12 @@ Miscellaneous

Return the ``globals()`` dictionary.

.. cpp:function:: Py_hash_t hash(handle h)

Hash the given argument like ``hash()`` in pure Python. The type of the
return value (``Py_hash_t``) is an implementation-specific signed integer
type.

.. cpp:function:: template <typename Source, typename Target> void implicitly_convertible()

Indicate that the type `Source` is implicitly convertible into `Target`
Expand Down
7 changes: 7 additions & 0 deletions include/nanobind/nb_misc.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ inline dict globals() {
return borrow<dict>(p);
}

inline Py_hash_t hash(handle h) {
Py_hash_t rv = PyObject_Hash(h.ptr());
if (rv == -1 && PyErr_Occurred())
nanobind::raise_python_error();
return rv;
}

inline bool is_alive() noexcept {
return detail::is_alive();
}
Expand Down
2 changes: 2 additions & 0 deletions tests/test_functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -359,4 +359,6 @@ NB_MODULE(test_functions_ext, m) {

return b;
});

m.def("hash_it", [](nb::handle h) { return nb::hash(h); });
}
4 changes: 4 additions & 0 deletions tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,3 +591,7 @@ def test43_wrappers_dict():

def test43_wrappers_set():
assert t.test_wrappers_set()

def test44_hash():
value = (1, 2, 3)
assert t.hash_it(value) == hash(value);
2 changes: 2 additions & 0 deletions tests/test_functions_ext.pyi.ref
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ from typing import Annotated, Any, overload

def call_guard_value() -> int: ...

def hash_it(arg: object, /) -> int: ...

def identity_i16(arg: int, /) -> int: ...

def identity_i32(arg: int, /) -> int: ...
Expand Down

0 comments on commit 01fafa5

Please sign in to comment.