Python C/API: how to create a normal class
<p>Using the Python C/API, how do I create a normal Python class using the normal Python class-creation mechanism (i.e.: not an extension type)?</p>

<p>In other words, what is the Python C/API equivalent (in the sense that it does <em>exactly</em> the same in all cases) of a statement</p>

<pre><code>class X(bases):
    ...some methods/attributes here...
</code></pre>

<p>In Python you can get programmatically create a class by calling the <code>type</code> built in function. See <a href="http://stackoverflow.com/a/15247202/4657412">this answer</a> for example.</p>

<p>This takes three arguments: a name, a tuple of bases, and a dictionary.</p>

<p>You can get the Python <code>type</code> in the C api as <a href="https://docs.python.org/3/c-api/type.html#c.PyType_Type" rel="nofollow"><code>PyType_Type</code></a>. You then just need to call it using <a href="https://docs.python.org/3/c-api/object.html#c.PyObject_Call" rel="nofollow">one of the standard methods for calling <code>PyObject*</code> callables</a>:</p>

<pre class="lang-c prettyprint-override"><code>// make a tuple of your bases
PyObject* bases = PyTuple_Pack(0); // assume no bases
// make a dictionary of member functions, etc
PyObject* dict = PyDict_New(); // empty for the sake of example 
PyObject* my_new_class = PyObject_CallFunction(&amp;PyType_Type,"sOO",
                                             "X", // class name
                                             bases,
                                             dict);
// check if null

// decref bases and dict
Py_CLEAR(bases);
Py_CLEAR(dict);
</code></pre>

<p>(Note that you have to do <code>&amp;PyType_Type</code> - the documentation implies that it's a <code>PyObject*</code> but it isn't!)</p>

python class python-c-api