Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if member function exists in a Boost python::object

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?

like image 297
sunmat Avatar asked Mar 11 '23 23:03

sunmat


1 Answers

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();
    // ...
}
like image 154
Barry Avatar answered Apr 07 '23 03:04

Barry