Py_INCREF(&CustomType); if (PyModule_AddObject(m, "Custom", (PyObject*)&CustomType)<0) { Py_DECREF( &CustomType); Py_DECREF(m); return NULL ; } 

This adds the type to the module dictionary. This allows us to create Custom instances by calling the Custom class: 

>>> import custom >>> mycustom=custom.Custom() 

That’s it! All that remains is to build it; put the above code in a file called$_{custom.c}$ and: 

from distutils.core import setup, Extension setup(name ="custom", version="1.0 ", ext_modules =[Extension( "custom", ["custom.c "])]) 

in a file called$_{setup.py}$ ; then typing 

$ python setup.py build 

at a shell should produce a file custom.so in a subdirectory; move to that directory and fire up Python — you should be able to$_{import custom}$and play around with Custom objects. 

That wasn’t so hard, was it? 

Of course, the current Custom type is pretty uninteresting. It has no data and doesn’t do anything. It can’t even be subclassed. 

Note: While this documentation showcases the standard $_{distutils}$module for building C extensions, it is recommended in real-world use cases to use the newer and better-maintained$_{setuptools}$ library. Documentation on how to do this is out of scope for this document and can be found in the Python Packaging User’s Guide. 

## 2.2.2 Adding data and methods to the Basic example 

Let’s extend the basic example to add some data and methods. Let’s also make the type usable as a base class. We’ll create a new module,$_{custom2}$ that adds these capabilities: 

#define PY_SSIZE_T_CLEAN #include<Python.h> #include"structmember.h" typedef struct { PyObject_HEAD PyObject *first; /* first name */ PyObject *last; /* last name */ int number; } CustomObject; static void Custom_dealloc(CustomObject *self) { Py_XDECREF(self ->first); Py_XDECREF(self ->last); Py_TYPE(self) ->tp_free((PyObject *) self); } static PyObject * 

(continues on next page) 

