Skip to content

Commit

Permalink
Bool conversion: simplifications and comments
Browse files Browse the repository at this point in the history
  • Loading branch information
aldanor committed Jul 23, 2017
1 parent 15c3000 commit 9b4f569
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
29 changes: 13 additions & 16 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -1054,29 +1054,26 @@ template <> class type_caster<bool> {
else if (src.ptr() == Py_True) { value = true; return true; }
else if (src.ptr() == Py_False) { value = false; return true; }
else if (convert) {
// This is quite similar to PyObject_IsTrue(), but it doesn't default
// to "True" for arbitrary objects.
Py_ssize_t res = -1;
if (src.is_none()) {
res = 0;
res = 0; // None is implicitly converted to False
}
#if !defined(PYPY_VERSION)
#if PY_MAJOR_VERSION >= 3
else if (src.ptr()->ob_type->tp_as_number && src.ptr()->ob_type->tp_as_number->nb_bool) {
res = (*src.ptr()->ob_type->tp_as_number->nb_bool)(src.ptr());
}
#else
else if (src.ptr()->ob_type->tp_as_number && src.ptr()->ob_type->tp_as_number->nb_nonzero) {
res = (*src.ptr()->ob_type->tp_as_number->nb_nonzero)(src.ptr());
#if defined(PYPY_VERSION)
// On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
res = PyObject_IsTrue(src.ptr());
}
#endif
#else
if (hasattr(src, PYBIND11_NONZERO)) {
res = PyObject_IsTrue(src.ptr());
// Alternate approach for CPython: this does the same as the above, but optimized
// using the CPython API so as to avoid an unneeded attribute lookup.
else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) {
if (PYBIND11_NB_BOOL(tp_as_number)) {
res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
}
}
#endif
if (res >= 0) {
value = res != 0;
if (res == 0 || res == 1) {
value = (bool) res;
return true;
}
return false;
Expand Down
6 changes: 4 additions & 2 deletions include/pybind11/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@
#define PYBIND11_SLICE_OBJECT PyObject
#define PYBIND11_FROM_STRING PyUnicode_FromString
#define PYBIND11_STR_TYPE ::pybind11::str
#define PYBIND11_NONZERO "__bool__"
#define PYBIND11_BOOL_ATTR "__bool__"
#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
#define PYBIND11_PLUGIN_IMPL(name) \
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()

Expand All @@ -173,7 +174,8 @@
#define PYBIND11_SLICE_OBJECT PySliceObject
#define PYBIND11_FROM_STRING PyString_FromString
#define PYBIND11_STR_TYPE ::pybind11::bytes
#define PYBIND11_NONZERO "__nonzero__"
#define PYBIND11_BOOL_ATTR "__nonzero__"
#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
#define PYBIND11_PLUGIN_IMPL(name) \
static PyObject *pybind11_init_wrapper(); \
extern "C" PYBIND11_EXPORT void init##name() { \
Expand Down

0 comments on commit 9b4f569

Please sign in to comment.