Finding if member function exists in a Boost python::object
<p>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.</p>

<pre><code>bp::object myInstance;
// ... myInstance is initialized
bp::object fun = myInstance.attr("myfunction");
fun();
</code></pre>

<p>I would like to check if the member function exists before calling it. If it does not exist, I don't want to call.</p>

<p>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.</p>

<p>Is there any way to check if the function exists without involving exception or calling the function?</p>

<blockquote>
  <p>the call to <code>myInstance.attr("myfunction")</code> is successful even if the function does not exist</p>
</blockquote>

<p>Pretty sure it throws an <code>AttributeError</code>. </p>

<blockquote>
  <p>Is there any way to check if the function exists without involving exception or calling the function?</p>
</blockquote>

<p>One of the strange holes in Boost.Python is that it doesn't have a <code>hasattr()</code> function. It's easy enough to add:</p>

<pre><code>namespace boost { namespace python {
    bool hasattr(object o, const char* name) {
        return PyObject_HasAttrString(o.ptr(), name);
    }
} }
</code></pre>

<p>and then you can just use it:</p>

<pre><code>if (hasattr(myInstance, "myfunction")) {
    bp::object fun = myInstance.attr("myfunction");
    fun();
    // ...
}
</code></pre>

python c++ boost boost-python