Skip to content

Instantly share code, notes, and snippets.

@JeffLabonte
Created October 11, 2019 16:02
Show Gist options
  • Save JeffLabonte/eca62cf5b0008a70b10fa5fef69f243e to your computer and use it in GitHub Desktop.
Save JeffLabonte/eca62cf5b0008a70b10fa5fef69f243e to your computer and use it in GitHub Desktop.
/* this code uses only C features */
static PyObject *
foo(PyObject *self, PyObject *args)
{
PyObject *cb;
// Receive a single argument which can be any Python object
// note: the object's reference count is NOT increased (but it's pinned by
// the argument tuple).
if (!PyArg_ParseTuple(args, "O", &cb)) {
return 0;
}
// determine whether the object is in fact callable
if (!PyCallable_Check(cb)) {
PyErr_SetString(PyExc_TypeError, "foo: a callable is required");
return 0;
}
// call it (no arguments supplied)
// there are a whole bunch of other PyObject_Call* functions for when you want
// to supply arguments
PyObject *rv = PyObject_CallObject(cb, 0);
// if calling it returned 0, must return 0 to propagate the exception
if (!rv) return 0;
// otherwise, discard the object returned and return None
Py_CLEAR(rv);
Py_RETURN_NONE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment