Skip to content

Commit

Permalink
Add support for bool (#382)
Browse files Browse the repository at this point in the history
* Add bool_ support

* Directly compare against Py_True
  • Loading branch information
matthewdcong committed Dec 12, 2023
1 parent eb308de commit 26337d4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions include/nanobind/nb_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ NB_CORE PyObject *bytes_from_cstr_and_size(const char *c, size_t n);

// ========================================================================

/// Convert a Python object into a Python boolean object
NB_CORE PyObject *bool_from_obj(PyObject *o);

/// Convert a Python object into a Python integer object
NB_CORE PyObject *int_from_obj(PyObject *o);

Expand Down
14 changes: 14 additions & 0 deletions include/nanobind/nb_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,20 @@ class capsule : public object {
void *data() const { return PyCapsule_GetPointer(m_ptr, name()); }
};

class bool_ : public object {
NB_OBJECT_DEFAULT(bool_, object, "bool", PyBool_Check)

explicit bool_(handle h)
: object(detail::bool_from_obj(h.ptr()), detail::borrow_t{}) { }

explicit bool_(bool value)
: object(value ? Py_True : Py_False, detail::borrow_t{}) { }

explicit operator bool() const {
return m_ptr == Py_True;
}
};

class int_ : public object {
NB_OBJECT_DEFAULT(int_, object, "int", PyLong_Check)

Expand Down
8 changes: 8 additions & 0 deletions src/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,14 @@ PyObject *bytes_from_cstr_and_size(const char *str, size_t size) {

// ========================================================================

PyObject *bool_from_obj(PyObject *o) {
const auto value = PyObject_IsTrue(o);
if (value == -1) {
raise_python_error();
}
return (value != 0 ? Py_True : Py_False);
}

PyObject *int_from_obj(PyObject *o) {
PyObject *result = PyNumber_Long(o);
if (!result)
Expand Down

0 comments on commit 26337d4

Please sign in to comment.