4. Defining New Types

If you've read chapter 2, you should know enough to write any extension module that only exports functions. But there's more to Python than functions; many programming tasks are most naturally expressed using objects, and an important facility is being able to define new types of object.

This is a large topic, and for any given task this chapter will almost certainly tell you both more and less than you need to know. In part due to its relative advancedness and in part due to the large changes in this area in Python 2.2, documentation on this topic is somewhat sparse. Chapter 10 of the Python/C API reference, ``Object Implementation Support'', has some information, but you may need to ``use the source, Luke''. Fortunately, you need look no further than the source of Python itself for several good examples of object implementations. Modules/_randommodule.c is a good first example, being relatively free of the obscurities that can affect the implementation of the most fundamental Python types - Objects/dictobject.c or Objects/typeobject.c are not particularly good files to go looking for example usages in!

When to implement a new type? Sometimes it's obvious: when wrapping an object oriented library like, say, the GTK interface library, it's only natrual to define a Python extension type for each widget defined by the library. On the other hand, if you're wrapping a library that is has a basically procedural interface, then, even if you want to provide an OO interface to this library the simplest course may be to expose the procedural interface in an extension module and do the objecty wrapper in Python. After all, if you didn't writing Python was less tedious than writing C, you probably wouldn't be reading this document.

Although this document is not really concerned with versions of Python prior to Python 2.3, most of the material before this point applies with only minor changes to older versions - probably all the way back to the ``Great Renaming'' of Python 1.2! This now ceases to be the case. The way in which new objects are defined changed drastically (for the better) as part of the work on so-called ``new-style classes'' in Python 2.2. The material in this chapter can probably be made to work with Python 2.2 with a little effort, but certainly not before that.

One of the ways in which 2.2 changed things was that defining new types in C and Python became much more alike. A corollary of this is that having a good understanding of new-style classes in Python helps greatly when it comes to implementing types in C.

THIS DOCUMENT IS A DRAFT! Comments to mwh@python.net please.