Instantiating a C Extension Subclass in C

I’m working through an experimental change to the interpreter that involves adding a subclass of dict to the CPython API. I have followed the C extension guide on subclassing PyDictObject and have a new type that behaves as expected in Python.

However, I also need to construct an instance of my type in C/the interpreter itself and I can’t find any documentation on how to do so. In essence, I would like to have a

PyAPI_FUNC(PyObject *)

Using PyObject_New(SubListObject, &SubListType) alone seems insufficient, but invoking my analog to SubList_init afterwards does not suffice either.

Two questions: a) what’s the right approach here? and b) could it be that there are specific caveats to inheriting from PyDictObject that I’m not addressing?


How would you create an instance of a class in Python? You’d call it.

Try PyObject_CallObject or similar, where the callable is the class.


Try PyObject_CallObject or similar, where the callable is the class.

Thanks so much, it worked!

I’m surprised this is the canonical approach, but I’m happy to run with it. Is there a less roundabout way though? I feel like I’m reaching through unnecessary indirection.

In what way is it “roundabout”? It’s a single call! :slight_smile:

PyObject_CallFunction also works, and it bundles in the Py_BuildValue call so that you can pass native arguments directly. And PyObject_CallMethod also includes the getattr, so it’s really handy if you’ve got a module object and need to get a type.

See Call Protocol — Python 3.11.3 documentation for more details.

Well, I did say “or similar”! :slight_smile: