Singletons in a Python extension module

If you want a singleton in a C extension module for CPython you basically have to do the same as when doing this in plain Python: the .__new__() method needs to return the same object each time it is called. Implementing this has a few catches though.

static PyObject *
MyType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    static MyObject *self = NULL;

    if (self == NULL)
        self = (MyObject *)type->tp_alloc(type, 0);
    Py_XINCREF(self);
    return (PyObject *)self;
}

Then assign this function to the tp_new slot in the type. There's two things of interest in this function: