title: CPython 'overloaded' functions
body: <p>I am trying to overload a python extension function that would take either a object or a string.</p>
  
  <pre class="lang-cpp prettyprint-override"><code>typedef struct
  {
    PyObject_HEAD
  } CustomObject;
  
  PyObject* customFunction(CustomObject* self, PyObject* args);
  
  PyMethodDef methods[] =
  {
   {"customFunction", (PyCFunction) customFunction, METH_VARAGS, "A custom function"},
   {NULL}
  }
  
  PyTypeObject TypeObj =
  {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "customModule.CustomObject",
    .tp_doc = "Custom Object",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_methods = methods,
  }
  
  // Area of problem
  PyObject* customFunction(CustomObject* self, PyObject* args)
  {
    const char* string;
    PyObject* object;
    if (PyArg_ParseTuple(args, "O!", &amp;TypeObj, &amp;object)) // TypeObj is the PyTypeObject fpr CustomObject
    {
      std::cout &lt;&lt; "Object function\n"
      // Do whatever and return PyObject*
    }
    else if (PyArg_ParseTuple(args, "s", &amp;string))
    {
      std::cout &lt;&lt; "String function\n"
      // Do whatever and return PyObject*
    }
    return PyLong_FromLong(0); // In case nothing above works
  }
  </code></pre>
  
  <p>In python I have a try except for the function and I get this error <code>Error: &lt;built-in method customFunction of CustomModule.CustomObject object at 0xmemoryadress&gt; returned a result with an error set</code></p>
  
  <p>Here are the Python docs for this PyArg_ParseTuple:</p>
  
  <blockquote>
    <p>int PyArg_ParseTuple(PyObject *args, const char *format, ...)</p>
    
    <p>Parse the parameters of a function that takes only positional parameters into local variables. Returns true on success; on failure, it returns false and raises the appropriate exception</p>
  </blockquote>
  
  <p>I am guessing that PyArg_ParseTuple is setting an error, which is causing the entire function not to work (I do have customFunction in my method table for the module, I am just omitting that code). If I have the following Python:</p>
  
  <pre class="lang-py prettyprint-override"><code>import CustomModule
  
  try:
    CustomModule.customFunction("foo")
  except Exception as e:
    print("Error:", e)
  </code></pre>
  
  <p><code>String function</code> does get outputted, so the code in the string if statement does work, but I assume the error occurs because PyArg_ParseTuple for the object failed, so it returns an error (not 100% sure if this is correct).</p>
  
  <p>Is there a way I can prevent PyArg_ParseTuple() from raising an error, is there another function, or is there a better way to 'overload' my custom functions?</p>