I'm using Boost Python to make C++ and Python operate together and I have a code that looks like this, creating an instance of a python object and calling one of its member functions.
bp::object myInstance;
// ... myInstance is initialized
bp::object fun = myInstance.attr("myfunction");
fun();
I would like to check if the member function exists before calling it. If it does not exist, I don't want to call.
The problem is: the call to myInstance.attr("myfunction") is successful even if the function does not exist. Hence, the only way to test if the function exists in my current code is by trying to call it, and catching an exception.
Is there any way to check if the function exists without involving exception or calling the function?
the call to
myInstance.attr("myfunction")
is successful even if the function does not exist
Pretty sure it throws an AttributeError
.
Is there any way to check if the function exists without involving exception or calling the function?
One of the strange holes in Boost.Python is that it doesn't have a hasattr()
function. It's easy enough to add:
namespace boost { namespace python {
bool hasattr(object o, const char* name) {
return PyObject_HasAttrString(o.ptr(), name);
}
} }
and then you can just use it:
if (hasattr(myInstance, "myfunction")) {
bp::object fun = myInstance.attr("myfunction");
fun();
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With