fb2c15a79a0783def2a14d8f1a9e39ce1a74644d
[profile/ivi/python.git] / Doc / extending / newtypes.rst
1 .. highlightlang:: c
2
3
4 .. _defining-new-types:
5
6 ******************
7 Defining New Types
8 ******************
9
10 .. sectionauthor:: Michael Hudson <mwh@python.net>
11 .. sectionauthor:: Dave Kuhlman <dkuhlman@rexx.com>
12 .. sectionauthor:: Jim Fulton <jim@zope.com>
13
14
15 As mentioned in the last chapter, Python allows the writer of an extension
16 module to define new types that can be manipulated from Python code, much like
17 strings and lists in core Python.
18
19 This is not hard; the code for all extension types follows a pattern, but there
20 are some details that you need to understand before you can get started.
21
22 .. note::
23
24    The way new types are defined changed dramatically (and for the better) in
25    Python 2.2.  This document documents how to define new types for Python 2.2 and
26    later.  If you need to support older versions of Python, you will need to refer
27    to `older versions of this documentation
28    <http://www.python.org/doc/versions/>`_.
29
30
31 .. _dnt-basics:
32
33 The Basics
34 ==========
35
36 The Python runtime sees all Python objects as variables of type
37 :ctype:`PyObject\*`.  A :ctype:`PyObject` is not a very magnificent object - it
38 just contains the refcount and a pointer to the object's "type object".  This is
39 where the action is; the type object determines which (C) functions get called
40 when, for instance, an attribute gets looked up on an object or it is multiplied
41 by another object.  These C functions are called "type methods" to distinguish
42 them from things like ``[].append`` (which we call "object methods").
43
44 So, if you want to define a new object type, you need to create a new type
45 object.
46
47 This sort of thing can only be explained by example, so here's a minimal, but
48 complete, module that defines a new type:
49
50 .. literalinclude:: ../includes/noddy.c
51
52
53 Now that's quite a bit to take in at once, but hopefully bits will seem familiar
54 from the last chapter.
55
56 The first bit that will be new is::
57
58    typedef struct {
59        PyObject_HEAD
60    } noddy_NoddyObject;
61
62 This is what a Noddy object will contain---in this case, nothing more than every
63 Python object contains, namely a refcount and a pointer to a type object.  These
64 are the fields the ``PyObject_HEAD`` macro brings in.  The reason for the macro
65 is to standardize the layout and to enable special debugging fields in debug
66 builds.  Note that there is no semicolon after the ``PyObject_HEAD`` macro; one
67 is included in the macro definition.  Be wary of adding one by accident; it's
68 easy to do from habit, and your compiler might not complain, but someone else's
69 probably will!  (On Windows, MSVC is known to call this an error and refuse to
70 compile the code.)
71
72 For contrast, let's take a look at the corresponding definition for standard
73 Python integers::
74
75    typedef struct {
76        PyObject_HEAD
77        long ob_ival;
78    } PyIntObject;
79
80 Moving on, we come to the crunch --- the type object. ::
81
82    static PyTypeObject noddy_NoddyType = {
83        PyObject_HEAD_INIT(NULL)
84        0,                         /*ob_size*/
85        "noddy.Noddy",             /*tp_name*/
86        sizeof(noddy_NoddyObject), /*tp_basicsize*/
87        0,                         /*tp_itemsize*/
88        0,                         /*tp_dealloc*/
89        0,                         /*tp_print*/
90        0,                         /*tp_getattr*/
91        0,                         /*tp_setattr*/
92        0,                         /*tp_compare*/
93        0,                         /*tp_repr*/
94        0,                         /*tp_as_number*/
95        0,                         /*tp_as_sequence*/
96        0,                         /*tp_as_mapping*/
97        0,                         /*tp_hash */
98        0,                         /*tp_call*/
99        0,                         /*tp_str*/
100        0,                         /*tp_getattro*/
101        0,                         /*tp_setattro*/
102        0,                         /*tp_as_buffer*/
103        Py_TPFLAGS_DEFAULT,        /*tp_flags*/
104        "Noddy objects",           /* tp_doc */
105    };
106
107 Now if you go and look up the definition of :ctype:`PyTypeObject` in
108 :file:`object.h` you'll see that it has many more fields that the definition
109 above.  The remaining fields will be filled with zeros by the C compiler, and
110 it's common practice to not specify them explicitly unless you need them.
111
112 This is so important that we're going to pick the top of it apart still
113 further::
114
115    PyObject_HEAD_INIT(NULL)
116
117 This line is a bit of a wart; what we'd like to write is::
118
119    PyObject_HEAD_INIT(&PyType_Type)
120
121 as the type of a type object is "type", but this isn't strictly conforming C and
122 some compilers complain.  Fortunately, this member will be filled in for us by
123 :cfunc:`PyType_Ready`. ::
124
125    0,                          /* ob_size */
126
127 The :attr:`ob_size` field of the header is not used; its presence in the type
128 structure is a historical artifact that is maintained for binary compatibility
129 with extension modules compiled for older versions of Python.  Always set this
130 field to zero. ::
131
132    "noddy.Noddy",              /* tp_name */
133
134 The name of our type.  This will appear in the default textual representation of
135 our objects and in some error messages, for example::
136
137    >>> "" + noddy.new_noddy()
138    Traceback (most recent call last):
139      File "<stdin>", line 1, in ?
140    TypeError: cannot add type "noddy.Noddy" to string
141
142 Note that the name is a dotted name that includes both the module name and the
143 name of the type within the module. The module in this case is :mod:`noddy` and
144 the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`. ::
145
146    sizeof(noddy_NoddyObject),  /* tp_basicsize */
147
148 This is so that Python knows how much memory to allocate when you call
149 :cfunc:`PyObject_New`.
150
151 .. note::
152
153    If you want your type to be subclassable from Python, and your type has the same
154    :attr:`tp_basicsize` as its base type, you may have problems with multiple
155    inheritance.  A Python subclass of your type will have to list your type first
156    in its :attr:`__bases__`, or else it will not be able to call your type's
157    :meth:`__new__` method without getting an error.  You can avoid this problem by
158    ensuring that your type has a larger value for :attr:`tp_basicsize` than its
159    base type does.  Most of the time, this will be true anyway, because either your
160    base type will be :class:`object`, or else you will be adding data members to
161    your base type, and therefore increasing its size.
162
163 ::
164
165    0,                          /* tp_itemsize */
166
167 This has to do with variable length objects like lists and strings. Ignore this
168 for now.
169
170 Skipping a number of type methods that we don't provide, we set the class flags
171 to :const:`Py_TPFLAGS_DEFAULT`. ::
172
173    Py_TPFLAGS_DEFAULT,        /*tp_flags*/
174
175 All types should include this constant in their flags.  It enables all of the
176 members defined by the current version of Python.
177
178 We provide a doc string for the type in :attr:`tp_doc`. ::
179
180    "Noddy objects",           /* tp_doc */
181
182 Now we get into the type methods, the things that make your objects different
183 from the others.  We aren't going to implement any of these in this version of
184 the module.  We'll expand this example later to have more interesting behavior.
185
186 For now, all we want to be able to do is to create new :class:`Noddy` objects.
187 To enable object creation, we have to provide a :attr:`tp_new` implementation.
188 In this case, we can just use the default implementation provided by the API
189 function :cfunc:`PyType_GenericNew`.  We'd like to just assign this to the
190 :attr:`tp_new` slot, but we can't, for portability sake, On some platforms or
191 compilers, we can't statically initialize a structure member with a function
192 defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot
193 in the module initialization function just before calling
194 :cfunc:`PyType_Ready`::
195
196    noddy_NoddyType.tp_new = PyType_GenericNew;
197    if (PyType_Ready(&noddy_NoddyType) < 0)
198        return;
199
200 All the other type methods are *NULL*, so we'll go over them later --- that's
201 for a later section!
202
203 Everything else in the file should be familiar, except for some code in
204 :cfunc:`initnoddy`::
205
206    if (PyType_Ready(&noddy_NoddyType) < 0)
207        return;
208
209 This initializes the :class:`Noddy` type, filing in a number of members,
210 including :attr:`ob_type` that we initially set to *NULL*. ::
211
212    PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
213
214 This adds the type to the module dictionary.  This allows us to create
215 :class:`Noddy` instances by calling the :class:`Noddy` class::
216
217    >>> import noddy
218    >>> mynoddy = noddy.Noddy()
219
220 That's it!  All that remains is to build it; put the above code in a file called
221 :file:`noddy.c` and ::
222
223    from distutils.core import setup, Extension
224    setup(name="noddy", version="1.0",
225          ext_modules=[Extension("noddy", ["noddy.c"])])
226
227 in a file called :file:`setup.py`; then typing ::
228
229    $ python setup.py build
230
231 at a shell should produce a file :file:`noddy.so` in a subdirectory; move to
232 that directory and fire up Python --- you should be able to ``import noddy`` and
233 play around with Noddy objects.
234
235 That wasn't so hard, was it?
236
237 Of course, the current Noddy type is pretty uninteresting. It has no data and
238 doesn't do anything. It can't even be subclassed.
239
240
241 Adding data and methods to the Basic example
242 --------------------------------------------
243
244 Let's expend the basic example to add some data and methods.  Let's also make
245 the type usable as a base class. We'll create a new module, :mod:`noddy2` that
246 adds these capabilities:
247
248 .. literalinclude:: ../includes/noddy2.c
249
250
251 This version of the module has a number of changes.
252
253 We've added an extra include::
254
255    #include <structmember.h>
256
257 This include provides declarations that we use to handle attributes, as
258 described a bit later.
259
260 The name of the :class:`Noddy` object structure has been shortened to
261 :class:`Noddy`.  The type object name has been shortened to :class:`NoddyType`.
262
263 The  :class:`Noddy` type now has three data attributes, *first*, *last*, and
264 *number*.  The *first* and *last* variables are Python strings containing first
265 and last names. The *number* attribute is an integer.
266
267 The object structure is updated accordingly::
268
269    typedef struct {
270        PyObject_HEAD
271        PyObject *first;
272        PyObject *last;
273        int number;
274    } Noddy;
275
276 Because we now have data to manage, we have to be more careful about object
277 allocation and deallocation.  At a minimum, we need a deallocation method::
278
279    static void
280    Noddy_dealloc(Noddy* self)
281    {
282        Py_XDECREF(self->first);
283        Py_XDECREF(self->last);
284        self->ob_type->tp_free((PyObject*)self);
285    }
286
287 which is assigned to the :attr:`tp_dealloc` member::
288
289    (destructor)Noddy_dealloc, /*tp_dealloc*/
290
291 This method decrements the reference counts of the two Python attributes. We use
292 :cfunc:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members
293 could be *NULL*.  It then calls the :attr:`tp_free` member of the object's type
294 to free the object's memory.  Note that the object's type might not be
295 :class:`NoddyType`, because the object may be an instance of a subclass.
296
297 We want to make sure that the first and last names are initialized to empty
298 strings, so we provide a new method::
299
300    static PyObject *
301    Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
302    {
303        Noddy *self;
304
305        self = (Noddy *)type->tp_alloc(type, 0);
306        if (self != NULL) {
307            self->first = PyString_FromString("");
308            if (self->first == NULL)
309              {
310                Py_DECREF(self);
311                return NULL;
312              }
313
314            self->last = PyString_FromString("");
315            if (self->last == NULL)
316              {
317                Py_DECREF(self);
318                return NULL;
319              }
320
321            self->number = 0;
322        }
323
324        return (PyObject *)self;
325    }
326
327 and install it in the :attr:`tp_new` member::
328
329    Noddy_new,                 /* tp_new */
330
331 The new member is responsible for creating (as opposed to initializing) objects
332 of the type.  It is exposed in Python as the :meth:`__new__` method.  See the
333 paper titled "Unifying types and classes in Python" for a detailed discussion of
334 the :meth:`__new__` method.  One reason to implement a new method is to assure
335 the initial values of instance variables.  In this case, we use the new method
336 to make sure that the initial values of the members :attr:`first` and
337 :attr:`last` are not *NULL*. If we didn't care whether the initial values were
338 *NULL*, we could have used :cfunc:`PyType_GenericNew` as our new method, as we
339 did before.  :cfunc:`PyType_GenericNew` initializes all of the instance variable
340 members to *NULL*.
341
342 The new method is a static method that is passed the type being instantiated and
343 any arguments passed when the type was called, and that returns the new object
344 created. New methods always accept positional and keyword arguments, but they
345 often ignore the arguments, leaving the argument handling to initializer
346 methods. Note that if the type supports subclassing, the type passed may not be
347 the type being defined.  The new method calls the tp_alloc slot to allocate
348 memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather
349 :cfunc:`PyType_Ready` fills it for us by inheriting it from our base class,
350 which is :class:`object` by default.  Most types use the default allocation.
351
352 .. note::
353
354    If you are creating a co-operative :attr:`tp_new` (one that calls a base type's
355    :attr:`tp_new` or :meth:`__new__`), you must *not* try to determine what method
356    to call using method resolution order at runtime.  Always statically determine
357    what type you are going to call, and call its :attr:`tp_new` directly, or via
358    ``type->tp_base->tp_new``.  If you do not do this, Python subclasses of your
359    type that also inherit from other Python-defined classes may not work correctly.
360    (Specifically, you may not be able to create instances of such subclasses
361    without getting a :exc:`TypeError`.)
362
363 We provide an initialization function::
364
365    static int
366    Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
367    {
368        PyObject *first=NULL, *last=NULL, *tmp;
369
370        static char *kwlist[] = {"first", "last", "number", NULL};
371
372        if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
373                                          &first, &last,
374                                          &self->number))
375            return -1;
376
377        if (first) {
378            tmp = self->first;
379            Py_INCREF(first);
380            self->first = first;
381            Py_XDECREF(tmp);
382        }
383
384        if (last) {
385            tmp = self->last;
386            Py_INCREF(last);
387            self->last = last;
388            Py_XDECREF(tmp);
389        }
390
391        return 0;
392    }
393
394 by filling the :attr:`tp_init` slot. ::
395
396    (initproc)Noddy_init,         /* tp_init */
397
398 The :attr:`tp_init` slot is exposed in Python as the :meth:`__init__` method. It
399 is used to initialize an object after it's created. Unlike the new method, we
400 can't guarantee that the initializer is called.  The initializer isn't called
401 when unpickling objects and it can be overridden.  Our initializer accepts
402 arguments to provide initial values for our instance. Initializers always accept
403 positional and keyword arguments.
404
405 Initializers can be called multiple times.  Anyone can call the :meth:`__init__`
406 method on our objects.  For this reason, we have to be extra careful when
407 assigning the new values.  We might be tempted, for example to assign the
408 :attr:`first` member like this::
409
410    if (first) {
411        Py_XDECREF(self->first);
412        Py_INCREF(first);
413        self->first = first;
414    }
415
416 But this would be risky.  Our type doesn't restrict the type of the
417 :attr:`first` member, so it could be any kind of object.  It could have a
418 destructor that causes code to be executed that tries to access the
419 :attr:`first` member.  To be paranoid and protect ourselves against this
420 possibility, we almost always reassign members before decrementing their
421 reference counts.  When don't we have to do this?
422
423 * when we absolutely know that the reference count is greater than 1
424
425 * when we know that deallocation of the object [#]_ will not cause any calls
426   back into our type's code
427
428 * when decrementing a reference count in a :attr:`tp_dealloc` handler when
429   garbage-collections is not supported [#]_
430
431 We want to expose our instance variables as attributes. There are a
432 number of ways to do that. The simplest way is to define member definitions::
433
434    static PyMemberDef Noddy_members[] = {
435        {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
436         "first name"},
437        {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
438         "last name"},
439        {"number", T_INT, offsetof(Noddy, number), 0,
440         "noddy number"},
441        {NULL}  /* Sentinel */
442    };
443
444 and put the definitions in the :attr:`tp_members` slot::
445
446    Noddy_members,             /* tp_members */
447
448 Each member definition has a member name, type, offset, access flags and
449 documentation string. See the :ref:`Generic-Attribute-Management` section below for
450 details.
451
452 A disadvantage of this approach is that it doesn't provide a way to restrict the
453 types of objects that can be assigned to the Python attributes.  We expect the
454 first and last names to be strings, but any Python objects can be assigned.
455 Further, the attributes can be deleted, setting the C pointers to *NULL*.  Even
456 though we can make sure the members are initialized to non-*NULL* values, the
457 members can be set to *NULL* if the attributes are deleted.
458
459 We define a single method, :meth:`name`, that outputs the objects name as the
460 concatenation of the first and last names. ::
461
462    static PyObject *
463    Noddy_name(Noddy* self)
464    {
465        static PyObject *format = NULL;
466        PyObject *args, *result;
467
468        if (format == NULL) {
469            format = PyString_FromString("%s %s");
470            if (format == NULL)
471                return NULL;
472        }
473
474        if (self->first == NULL) {
475            PyErr_SetString(PyExc_AttributeError, "first");
476            return NULL;
477        }
478
479        if (self->last == NULL) {
480            PyErr_SetString(PyExc_AttributeError, "last");
481            return NULL;
482        }
483
484        args = Py_BuildValue("OO", self->first, self->last);
485        if (args == NULL)
486            return NULL;
487
488        result = PyString_Format(format, args);
489        Py_DECREF(args);
490
491        return result;
492    }
493
494 The method is implemented as a C function that takes a :class:`Noddy` (or
495 :class:`Noddy` subclass) instance as the first argument.  Methods always take an
496 instance as the first argument. Methods often take positional and keyword
497 arguments as well, but in this cased we don't take any and don't need to accept
498 a positional argument tuple or keyword argument dictionary. This method is
499 equivalent to the Python method::
500
501    def name(self):
502       return "%s %s" % (self.first, self.last)
503
504 Note that we have to check for the possibility that our :attr:`first` and
505 :attr:`last` members are *NULL*.  This is because they can be deleted, in which
506 case they are set to *NULL*.  It would be better to prevent deletion of these
507 attributes and to restrict the attribute values to be strings.  We'll see how to
508 do that in the next section.
509
510 Now that we've defined the method, we need to create an array of method
511 definitions::
512
513    static PyMethodDef Noddy_methods[] = {
514        {"name", (PyCFunction)Noddy_name, METH_NOARGS,
515         "Return the name, combining the first and last name"
516        },
517        {NULL}  /* Sentinel */
518    };
519
520 and assign them to the :attr:`tp_methods` slot::
521
522    Noddy_methods,             /* tp_methods */
523
524 Note that we used the :const:`METH_NOARGS` flag to indicate that the method is
525 passed no arguments.
526
527 Finally, we'll make our type usable as a base class.  We've written our methods
528 carefully so far so that they don't make any assumptions about the type of the
529 object being created or used, so all we need to do is to add the
530 :const:`Py_TPFLAGS_BASETYPE` to our class flag definition::
531
532    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
533
534 We rename :cfunc:`initnoddy` to :cfunc:`initnoddy2` and update the module name
535 passed to :cfunc:`Py_InitModule3`.
536
537 Finally, we update our :file:`setup.py` file to build the new module::
538
539    from distutils.core import setup, Extension
540    setup(name="noddy", version="1.0",
541          ext_modules=[
542             Extension("noddy", ["noddy.c"]),
543             Extension("noddy2", ["noddy2.c"]),
544             ])
545
546
547 Providing finer control over data attributes
548 --------------------------------------------
549
550 In this section, we'll provide finer control over how the :attr:`first` and
551 :attr:`last` attributes are set in the :class:`Noddy` example. In the previous
552 version of our module, the instance variables :attr:`first` and :attr:`last`
553 could be set to non-string values or even deleted. We want to make sure that
554 these attributes always contain strings.
555
556 .. literalinclude:: ../includes/noddy3.c
557
558
559 To provide greater control, over the :attr:`first` and :attr:`last` attributes,
560 we'll use custom getter and setter functions.  Here are the functions for
561 getting and setting the :attr:`first` attribute::
562
563    Noddy_getfirst(Noddy *self, void *closure)
564    {
565        Py_INCREF(self->first);
566        return self->first;
567    }
568
569    static int
570    Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
571    {
572      if (value == NULL) {
573        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
574        return -1;
575      }
576
577      if (! PyString_Check(value)) {
578        PyErr_SetString(PyExc_TypeError,
579                        "The first attribute value must be a string");
580        return -1;
581      }
582
583      Py_DECREF(self->first);
584      Py_INCREF(value);
585      self->first = value;
586
587      return 0;
588    }
589
590 The getter function is passed a :class:`Noddy` object and a "closure", which is
591 void pointer. In this case, the closure is ignored. (The closure supports an
592 advanced usage in which definition data is passed to the getter and setter. This
593 could, for example, be used to allow a single set of getter and setter functions
594 that decide the attribute to get or set based on data in the closure.)
595
596 The setter function is passed the :class:`Noddy` object, the new value, and the
597 closure. The new value may be *NULL*, in which case the attribute is being
598 deleted.  In our setter, we raise an error if the attribute is deleted or if the
599 attribute value is not a string.
600
601 We create an array of :ctype:`PyGetSetDef` structures::
602
603    static PyGetSetDef Noddy_getseters[] = {
604        {"first",
605         (getter)Noddy_getfirst, (setter)Noddy_setfirst,
606         "first name",
607         NULL},
608        {"last",
609         (getter)Noddy_getlast, (setter)Noddy_setlast,
610         "last name",
611         NULL},
612        {NULL}  /* Sentinel */
613    };
614
615 and register it in the :attr:`tp_getset` slot::
616
617    Noddy_getseters,           /* tp_getset */
618
619 to register our attribute getters and setters.
620
621 The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned
622 above. In this case, we aren't using the closure, so we just pass *NULL*.
623
624 We also remove the member definitions for these attributes::
625
626    static PyMemberDef Noddy_members[] = {
627        {"number", T_INT, offsetof(Noddy, number), 0,
628         "noddy number"},
629        {NULL}  /* Sentinel */
630    };
631
632 We also need to update the :attr:`tp_init` handler to only allow strings [#]_ to
633 be passed::
634
635    static int
636    Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
637    {
638        PyObject *first=NULL, *last=NULL, *tmp;
639
640        static char *kwlist[] = {"first", "last", "number", NULL};
641
642        if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SSi", kwlist,
643                                          &first, &last,
644                                          &self->number))
645            return -1;
646
647        if (first) {
648            tmp = self->first;
649            Py_INCREF(first);
650            self->first = first;
651            Py_DECREF(tmp);
652        }
653
654        if (last) {
655            tmp = self->last;
656            Py_INCREF(last);
657            self->last = last;
658            Py_DECREF(tmp);
659        }
660
661        return 0;
662    }
663
664 With these changes, we can assure that the :attr:`first` and :attr:`last`
665 members are never *NULL* so we can remove checks for *NULL* values in almost all
666 cases. This means that most of the :cfunc:`Py_XDECREF` calls can be converted to
667 :cfunc:`Py_DECREF` calls. The only place we can't change these calls is in the
668 deallocator, where there is the possibility that the initialization of these
669 members failed in the constructor.
670
671 We also rename the module initialization function and module name in the
672 initialization function, as we did before, and we add an extra definition to the
673 :file:`setup.py` file.
674
675
676 Supporting cyclic garbage collection
677 ------------------------------------
678
679 Python has a cyclic-garbage collector that can identify unneeded objects even
680 when their reference counts are not zero. This can happen when objects are
681 involved in cycles.  For example, consider::
682
683    >>> l = []
684    >>> l.append(l)
685    >>> del l
686
687 In this example, we create a list that contains itself. When we delete it, it
688 still has a reference from itself. Its reference count doesn't drop to zero.
689 Fortunately, Python's cyclic-garbage collector will eventually figure out that
690 the list is garbage and free it.
691
692 In the second version of the :class:`Noddy` example, we allowed any kind of
693 object to be stored in the :attr:`first` or :attr:`last` attributes. [#]_ This
694 means that :class:`Noddy` objects can participate in cycles::
695
696    >>> import noddy2
697    >>> n = noddy2.Noddy()
698    >>> l = [n]
699    >>> n.first = l
700
701 This is pretty silly, but it gives us an excuse to add support for the
702 cyclic-garbage collector to the :class:`Noddy` example.  To support cyclic
703 garbage collection, types need to fill two slots and set a class flag that
704 enables these slots:
705
706 .. literalinclude:: ../includes/noddy4.c
707
708
709 The traversal method provides access to subobjects that could participate in
710 cycles::
711
712    static int
713    Noddy_traverse(Noddy *self, visitproc visit, void *arg)
714    {
715        int vret;
716
717        if (self->first) {
718            vret = visit(self->first, arg);
719            if (vret != 0)
720                return vret;
721        }
722        if (self->last) {
723            vret = visit(self->last, arg);
724            if (vret != 0)
725                return vret;
726        }
727
728        return 0;
729    }
730
731 For each subobject that can participate in cycles, we need to call the
732 :cfunc:`visit` function, which is passed to the traversal method. The
733 :cfunc:`visit` function takes as arguments the subobject and the extra argument
734 *arg* passed to the traversal method.  It returns an integer value that must be
735 returned if it is non-zero.
736
737 Python 2.4 and higher provide a :cfunc:`Py_VISIT` macro that automates calling
738 visit functions.  With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be
739 simplified::
740
741    static int
742    Noddy_traverse(Noddy *self, visitproc visit, void *arg)
743    {
744        Py_VISIT(self->first);
745        Py_VISIT(self->last);
746        return 0;
747    }
748
749 .. note::
750
751    Note that the :attr:`tp_traverse` implementation must name its arguments exactly
752    *visit* and *arg* in order to use :cfunc:`Py_VISIT`.  This is to encourage
753    uniformity across these boring implementations.
754
755 We also need to provide a method for clearing any subobjects that can
756 participate in cycles.  We implement the method and reimplement the deallocator
757 to use it::
758
759    static int
760    Noddy_clear(Noddy *self)
761    {
762        PyObject *tmp;
763
764        tmp = self->first;
765        self->first = NULL;
766        Py_XDECREF(tmp);
767
768        tmp = self->last;
769        self->last = NULL;
770        Py_XDECREF(tmp);
771
772        return 0;
773    }
774
775    static void
776    Noddy_dealloc(Noddy* self)
777    {
778        Noddy_clear(self);
779        self->ob_type->tp_free((PyObject*)self);
780    }
781
782 Notice the use of a temporary variable in :cfunc:`Noddy_clear`. We use the
783 temporary variable so that we can set each member to *NULL* before decrementing
784 its reference count.  We do this because, as was discussed earlier, if the
785 reference count drops to zero, we might cause code to run that calls back into
786 the object.  In addition, because we now support garbage collection, we also
787 have to worry about code being run that triggers garbage collection.  If garbage
788 collection is run, our :attr:`tp_traverse` handler could get called. We can't
789 take a chance of having :cfunc:`Noddy_traverse` called when a member's reference
790 count has dropped to zero and its value hasn't been set to *NULL*.
791
792 Python 2.4 and higher provide a :cfunc:`Py_CLEAR` that automates the careful
793 decrementing of reference counts.  With :cfunc:`Py_CLEAR`, the
794 :cfunc:`Noddy_clear` function can be simplified::
795
796    static int
797    Noddy_clear(Noddy *self)
798    {
799        Py_CLEAR(self->first);
800        Py_CLEAR(self->last);
801        return 0;
802    }
803
804 Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags::
805
806    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
807
808 That's pretty much it.  If we had written custom :attr:`tp_alloc` or
809 :attr:`tp_free` slots, we'd need to modify them for cyclic-garbage collection.
810 Most extensions will use the versions automatically provided.
811
812
813 Subclassing other types
814 -----------------------
815
816 It is possible to create new extension types that are derived from existing
817 types. It is easiest to inherit from the built in types, since an extension can
818 easily use the :class:`PyTypeObject` it needs. It can be difficult to share
819 these :class:`PyTypeObject` structures between extension modules.
820
821 In this example we will create a :class:`Shoddy` type that inherits from the
822 built-in :class:`list` type. The new type will be completely compatible with
823 regular lists, but will have an additional :meth:`increment` method that
824 increases an internal counter. ::
825
826    >>> import shoddy
827    >>> s = shoddy.Shoddy(range(3))
828    >>> s.extend(s)
829    >>> print len(s)
830    6
831    >>> print s.increment()
832    1
833    >>> print s.increment()
834    2
835
836 .. literalinclude:: ../includes/shoddy.c
837
838
839 As you can see, the source code closely resembles the :class:`Noddy` examples in
840 previous sections. We will break down the main differences between them. ::
841
842    typedef struct {
843        PyListObject list;
844        int state;
845    } Shoddy;
846
847 The primary difference for derived type objects is that the base type's object
848 structure must be the first value. The base type will already include the
849 :cfunc:`PyObject_HEAD` at the beginning of its structure.
850
851 When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can
852 be safely cast to both *PyListObject\** and *Shoddy\**. ::
853
854    static int
855    Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
856    {
857        if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
858           return -1;
859        self->state = 0;
860        return 0;
861    }
862
863 In the :attr:`__init__` method for our type, we can see how to call through to
864 the :attr:`__init__` method of the base type.
865
866 This pattern is important when writing a type with custom :attr:`new` and
867 :attr:`dealloc` methods. The :attr:`new` method should not actually create the
868 memory for the object with :attr:`tp_alloc`, that will be handled by the base
869 class when calling its :attr:`tp_new`.
870
871 When filling out the :cfunc:`PyTypeObject` for the :class:`Shoddy` type, you see
872 a slot for :cfunc:`tp_base`. Due to cross platform compiler issues, you can't
873 fill that field directly with the :cfunc:`PyList_Type`; it can be done later in
874 the module's :cfunc:`init` function. ::
875
876    PyMODINIT_FUNC
877    initshoddy(void)
878    {
879        PyObject *m;
880
881        ShoddyType.tp_base = &PyList_Type;
882        if (PyType_Ready(&ShoddyType) < 0)
883            return;
884
885        m = Py_InitModule3("shoddy", NULL, "Shoddy module");
886        if (m == NULL)
887            return;
888
889        Py_INCREF(&ShoddyType);
890        PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
891    }
892
893 Before calling :cfunc:`PyType_Ready`, the type structure must have the
894 :attr:`tp_base` slot filled in. When we are deriving a new type, it is not
895 necessary to fill out the :attr:`tp_alloc` slot with :cfunc:`PyType_GenericNew`
896 -- the allocate function from the base type will be inherited.
897
898 After that, calling :cfunc:`PyType_Ready` and adding the type object to the
899 module is the same as with the basic :class:`Noddy` examples.
900
901
902 .. _dnt-type-methods:
903
904 Type Methods
905 ============
906
907 This section aims to give a quick fly-by on the various type methods you can
908 implement and what they do.
909
910 Here is the definition of :ctype:`PyTypeObject`, with some fields only used in
911 debug builds omitted:
912
913 .. literalinclude:: ../includes/typestruct.h
914
915
916 Now that's a *lot* of methods.  Don't worry too much though - if you have a type
917 you want to define, the chances are very good that you will only implement a
918 handful of these.
919
920 As you probably expect by now, we're going to go over this and give more
921 information about the various handlers.  We won't go in the order they are
922 defined in the structure, because there is a lot of historical baggage that
923 impacts the ordering of the fields; be sure your type initialization keeps the
924 fields in the right order!  It's often easiest to find an example that includes
925 all the fields you need (even if they're initialized to ``0``) and then change
926 the values to suit your new type. ::
927
928    char *tp_name; /* For printing */
929
930 The name of the type - as mentioned in the last section, this will appear in
931 various places, almost entirely for diagnostic purposes. Try to choose something
932 that will be helpful in such a situation! ::
933
934    int tp_basicsize, tp_itemsize; /* For allocation */
935
936 These fields tell the runtime how much memory to allocate when new objects of
937 this type are created.  Python has some built-in support for variable length
938 structures (think: strings, lists) which is where the :attr:`tp_itemsize` field
939 comes in.  This will be dealt with later. ::
940
941    char *tp_doc;
942
943 Here you can put a string (or its address) that you want returned when the
944 Python script references ``obj.__doc__`` to retrieve the doc string.
945
946 Now we come to the basic type methods---the ones most extension types will
947 implement.
948
949
950 Finalization and De-allocation
951 ------------------------------
952
953 .. index::
954    single: object; deallocation
955    single: deallocation, object
956    single: object; finalization
957    single: finalization, of objects
958
959 ::
960
961    destructor tp_dealloc;
962
963 This function is called when the reference count of the instance of your type is
964 reduced to zero and the Python interpreter wants to reclaim it.  If your type
965 has memory to free or other clean-up to perform, put it here.  The object itself
966 needs to be freed here as well.  Here is an example of this function::
967
968    static void
969    newdatatype_dealloc(newdatatypeobject * obj)
970    {
971        free(obj->obj_UnderlyingDatatypePtr);
972        obj->ob_type->tp_free(obj);
973    }
974
975 .. index::
976    single: PyErr_Fetch()
977    single: PyErr_Restore()
978
979 One important requirement of the deallocator function is that it leaves any
980 pending exceptions alone.  This is important since deallocators are frequently
981 called as the interpreter unwinds the Python stack; when the stack is unwound
982 due to an exception (rather than normal returns), nothing is done to protect the
983 deallocators from seeing that an exception has already been set.  Any actions
984 which a deallocator performs which may cause additional Python code to be
985 executed may detect that an exception has been set.  This can lead to misleading
986 errors from the interpreter.  The proper way to protect against this is to save
987 a pending exception before performing the unsafe action, and restoring it when
988 done.  This can be done using the :cfunc:`PyErr_Fetch` and
989 :cfunc:`PyErr_Restore` functions::
990
991    static void
992    my_dealloc(PyObject *obj)
993    {
994        MyObject *self = (MyObject *) obj;
995        PyObject *cbresult;
996
997        if (self->my_callback != NULL) {
998            PyObject *err_type, *err_value, *err_traceback;
999            int have_error = PyErr_Occurred() ? 1 : 0;
1000
1001            if (have_error)
1002                PyErr_Fetch(&err_type, &err_value, &err_traceback);
1003
1004            cbresult = PyObject_CallObject(self->my_callback, NULL);
1005            if (cbresult == NULL)
1006                PyErr_WriteUnraisable(self->my_callback);
1007            else
1008                Py_DECREF(cbresult);
1009
1010            if (have_error)
1011                PyErr_Restore(err_type, err_value, err_traceback);
1012
1013            Py_DECREF(self->my_callback);
1014        }
1015        obj->ob_type->tp_free((PyObject*)self);
1016    }
1017
1018
1019 Object Presentation
1020 -------------------
1021
1022 .. index::
1023    builtin: repr
1024    builtin: str
1025
1026 In Python, there are three ways to generate a textual representation of an
1027 object: the :func:`repr` function (or equivalent back-tick syntax), the
1028 :func:`str` function, and the :keyword:`print` statement.  For most objects, the
1029 :keyword:`print` statement is equivalent to the :func:`str` function, but it is
1030 possible to special-case printing to a :ctype:`FILE\*` if necessary; this should
1031 only be done if efficiency is identified as a problem and profiling suggests
1032 that creating a temporary string object to be written to a file is too
1033 expensive.
1034
1035 These handlers are all optional, and most types at most need to implement the
1036 :attr:`tp_str` and :attr:`tp_repr` handlers. ::
1037
1038    reprfunc tp_repr;
1039    reprfunc tp_str;
1040    printfunc tp_print;
1041
1042 The :attr:`tp_repr` handler should return a string object containing a
1043 representation of the instance for which it is called.  Here is a simple
1044 example::
1045
1046    static PyObject *
1047    newdatatype_repr(newdatatypeobject * obj)
1048    {
1049        return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
1050                                   obj->obj_UnderlyingDatatypePtr->size);
1051    }
1052
1053 If no :attr:`tp_repr` handler is specified, the interpreter will supply a
1054 representation that uses the type's :attr:`tp_name` and a uniquely-identifying
1055 value for the object.
1056
1057 The :attr:`tp_str` handler is to :func:`str` what the :attr:`tp_repr` handler
1058 described above is to :func:`repr`; that is, it is called when Python code calls
1059 :func:`str` on an instance of your object.  Its implementation is very similar
1060 to the :attr:`tp_repr` function, but the resulting string is intended for human
1061 consumption.  If :attr:`tp_str` is not specified, the :attr:`tp_repr` handler is
1062 used instead.
1063
1064 Here is a simple example::
1065
1066    static PyObject *
1067    newdatatype_str(newdatatypeobject * obj)
1068    {
1069        return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
1070                                   obj->obj_UnderlyingDatatypePtr->size);
1071    }
1072
1073 The print function will be called whenever Python needs to "print" an instance
1074 of the type.  For example, if 'node' is an instance of type TreeNode, then the
1075 print function is called when Python code calls::
1076
1077    print node
1078
1079 There is a flags argument and one flag, :const:`Py_PRINT_RAW`, and it suggests
1080 that you print without string quotes and possibly without interpreting escape
1081 sequences.
1082
1083 The print function receives a file object as an argument. You will likely want
1084 to write to that file object.
1085
1086 Here is a sample print function::
1087
1088    static int
1089    newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
1090    {
1091        if (flags & Py_PRINT_RAW) {
1092            fprintf(fp, "<{newdatatype object--size: %d}>",
1093                    obj->obj_UnderlyingDatatypePtr->size);
1094        }
1095        else {
1096            fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
1097                    obj->obj_UnderlyingDatatypePtr->size);
1098        }
1099        return 0;
1100    }
1101
1102
1103 Attribute Management
1104 --------------------
1105
1106 For every object which can support attributes, the corresponding type must
1107 provide the functions that control how the attributes are resolved.  There needs
1108 to be a function which can retrieve attributes (if any are defined), and another
1109 to set attributes (if setting attributes is allowed).  Removing an attribute is
1110 a special case, for which the new value passed to the handler is *NULL*.
1111
1112 Python supports two pairs of attribute handlers; a type that supports attributes
1113 only needs to implement the functions for one pair.  The difference is that one
1114 pair takes the name of the attribute as a :ctype:`char\*`, while the other
1115 accepts a :ctype:`PyObject\*`.  Each type can use whichever pair makes more
1116 sense for the implementation's convenience. ::
1117
1118    getattrfunc  tp_getattr;        /* char * version */
1119    setattrfunc  tp_setattr;
1120    /* ... */
1121    getattrofunc tp_getattrofunc;   /* PyObject * version */
1122    setattrofunc tp_setattrofunc;
1123
1124 If accessing attributes of an object is always a simple operation (this will be
1125 explained shortly), there are generic implementations which can be used to
1126 provide the :ctype:`PyObject\*` version of the attribute management functions.
1127 The actual need for type-specific attribute handlers almost completely
1128 disappeared starting with Python 2.2, though there are many examples which have
1129 not been updated to use some of the new generic mechanism that is available.
1130
1131
1132 .. _generic-attribute-management:
1133
1134 Generic Attribute Management
1135 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1136
1137 .. versionadded:: 2.2
1138
1139 Most extension types only use *simple* attributes.  So, what makes the
1140 attributes simple?  There are only a couple of conditions that must be met:
1141
1142 #. The name of the attributes must be known when :cfunc:`PyType_Ready` is
1143    called.
1144
1145 #. No special processing is needed to record that an attribute was looked up or
1146    set, nor do actions need to be taken based on the value.
1147
1148 Note that this list does not place any restrictions on the values of the
1149 attributes, when the values are computed, or how relevant data is stored.
1150
1151 When :cfunc:`PyType_Ready` is called, it uses three tables referenced by the
1152 type object to create :term:`descriptor`\s which are placed in the dictionary of the
1153 type object.  Each descriptor controls access to one attribute of the instance
1154 object.  Each of the tables is optional; if all three are *NULL*, instances of
1155 the type will only have attributes that are inherited from their base type, and
1156 should leave the :attr:`tp_getattro` and :attr:`tp_setattro` fields *NULL* as
1157 well, allowing the base type to handle attributes.
1158
1159 The tables are declared as three fields of the type object::
1160
1161    struct PyMethodDef *tp_methods;
1162    struct PyMemberDef *tp_members;
1163    struct PyGetSetDef *tp_getset;
1164
1165 If :attr:`tp_methods` is not *NULL*, it must refer to an array of
1166 :ctype:`PyMethodDef` structures.  Each entry in the table is an instance of this
1167 structure::
1168
1169    typedef struct PyMethodDef {
1170        char        *ml_name;       /* method name */
1171        PyCFunction  ml_meth;       /* implementation function */
1172        int          ml_flags;      /* flags */
1173        char        *ml_doc;        /* docstring */
1174    } PyMethodDef;
1175
1176 One entry should be defined for each method provided by the type; no entries are
1177 needed for methods inherited from a base type.  One additional entry is needed
1178 at the end; it is a sentinel that marks the end of the array.  The
1179 :attr:`ml_name` field of the sentinel must be *NULL*.
1180
1181 XXX Need to refer to some unified discussion of the structure fields, shared
1182 with the next section.
1183
1184 The second table is used to define attributes which map directly to data stored
1185 in the instance.  A variety of primitive C types are supported, and access may
1186 be read-only or read-write.  The structures in the table are defined as::
1187
1188    typedef struct PyMemberDef {
1189        char *name;
1190        int   type;
1191        int   offset;
1192        int   flags;
1193        char *doc;
1194    } PyMemberDef;
1195
1196 For each entry in the table, a :term:`descriptor` will be constructed and added to the
1197 type which will be able to extract a value from the instance structure.  The
1198 :attr:`type` field should contain one of the type codes defined in the
1199 :file:`structmember.h` header; the value will be used to determine how to
1200 convert Python values to and from C values.  The :attr:`flags` field is used to
1201 store flags which control how the attribute can be accessed.
1202
1203 XXX Need to move some of this to a shared section!
1204
1205 The following flag constants are defined in :file:`structmember.h`; they may be
1206 combined using bitwise-OR.
1207
1208 +---------------------------+----------------------------------------------+
1209 | Constant                  | Meaning                                      |
1210 +===========================+==============================================+
1211 | :const:`READONLY`         | Never writable.                              |
1212 +---------------------------+----------------------------------------------+
1213 | :const:`RO`               | Shorthand for :const:`READONLY`.             |
1214 +---------------------------+----------------------------------------------+
1215 | :const:`READ_RESTRICTED`  | Not readable in restricted mode.             |
1216 +---------------------------+----------------------------------------------+
1217 | :const:`WRITE_RESTRICTED` | Not writable in restricted mode.             |
1218 +---------------------------+----------------------------------------------+
1219 | :const:`RESTRICTED`       | Not readable or writable in restricted mode. |
1220 +---------------------------+----------------------------------------------+
1221
1222 .. index::
1223    single: READONLY
1224    single: RO
1225    single: READ_RESTRICTED
1226    single: WRITE_RESTRICTED
1227    single: RESTRICTED
1228
1229 An interesting advantage of using the :attr:`tp_members` table to build
1230 descriptors that are used at runtime is that any attribute defined this way can
1231 have an associated doc string simply by providing the text in the table.  An
1232 application can use the introspection API to retrieve the descriptor from the
1233 class object, and get the doc string using its :attr:`__doc__` attribute.
1234
1235 As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value
1236 of *NULL* is required.
1237
1238 .. XXX Descriptors need to be explained in more detail somewhere, but not here.
1239
1240    Descriptor objects have two handler functions which correspond to the
1241    \member{tp_getattro} and \member{tp_setattro} handlers.  The
1242    \method{__get__()} handler is a function which is passed the descriptor,
1243    instance, and type objects, and returns the value of the attribute, or it
1244    returns \NULL{} and sets an exception.  The \method{__set__()} handler is
1245    passed the descriptor, instance, type, and new value;
1246
1247
1248 Type-specific Attribute Management
1249 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1250
1251 For simplicity, only the :ctype:`char\*` version will be demonstrated here; the
1252 type of the name parameter is the only difference between the :ctype:`char\*`
1253 and :ctype:`PyObject\*` flavors of the interface. This example effectively does
1254 the same thing as the generic example above, but does not use the generic
1255 support added in Python 2.2.  The value in showing this is two-fold: it
1256 demonstrates how basic attribute management can be done in a way that is
1257 portable to older versions of Python, and explains how the handler functions are
1258 called, so that if you do need to extend their functionality, you'll understand
1259 what needs to be done.
1260
1261 The :attr:`tp_getattr` handler is called when the object requires an attribute
1262 look-up.  It is called in the same situations where the :meth:`__getattr__`
1263 method of a class would be called.
1264
1265 A likely way to handle this is (1) to implement a set of functions (such as
1266 :cfunc:`newdatatype_getSize` and :cfunc:`newdatatype_setSize` in the example
1267 below), (2) provide a method table listing these functions, and (3) provide a
1268 getattr function that returns the result of a lookup in that table.  The method
1269 table uses the same structure as the :attr:`tp_methods` field of the type
1270 object.
1271
1272 Here is an example::
1273
1274    static PyMethodDef newdatatype_methods[] = {
1275        {"getSize", (PyCFunction)newdatatype_getSize, METH_VARARGS,
1276         "Return the current size."},
1277        {"setSize", (PyCFunction)newdatatype_setSize, METH_VARARGS,
1278         "Set the size."},
1279        {NULL, NULL, 0, NULL}           /* sentinel */
1280    };
1281
1282    static PyObject *
1283    newdatatype_getattr(newdatatypeobject *obj, char *name)
1284    {
1285        return Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);
1286    }
1287
1288 The :attr:`tp_setattr` handler is called when the :meth:`__setattr__` or
1289 :meth:`__delattr__` method of a class instance would be called.  When an
1290 attribute should be deleted, the third parameter will be *NULL*.  Here is an
1291 example that simply raises an exception; if this were really all you wanted, the
1292 :attr:`tp_setattr` handler should be set to *NULL*. ::
1293
1294    static int
1295    newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
1296    {
1297        (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
1298        return -1;
1299    }
1300
1301
1302 Object Comparison
1303 -----------------
1304
1305 ::
1306
1307    cmpfunc tp_compare;
1308
1309 The :attr:`tp_compare` handler is called when comparisons are needed and the
1310 object does not implement the specific rich comparison method which matches the
1311 requested comparison.  (It is always used if defined and the
1312 :cfunc:`PyObject_Compare` or :cfunc:`PyObject_Cmp` functions are used, or if
1313 :func:`cmp` is used from Python.) It is analogous to the :meth:`__cmp__` method.
1314 This function should return ``-1`` if *obj1* is less than *obj2*, ``0`` if they
1315 are equal, and ``1`` if *obj1* is greater than *obj2*. (It was previously
1316 allowed to return arbitrary negative or positive integers for less than and
1317 greater than, respectively; as of Python 2.2, this is no longer allowed.  In the
1318 future, other return values may be assigned a different meaning.)
1319
1320 A :attr:`tp_compare` handler may raise an exception.  In this case it should
1321 return a negative value.  The caller has to test for the exception using
1322 :cfunc:`PyErr_Occurred`.
1323
1324 Here is a sample implementation::
1325
1326    static int
1327    newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)
1328    {
1329        long result;
1330
1331        if (obj1->obj_UnderlyingDatatypePtr->size <
1332            obj2->obj_UnderlyingDatatypePtr->size) {
1333            result = -1;
1334        }
1335        else if (obj1->obj_UnderlyingDatatypePtr->size >
1336                 obj2->obj_UnderlyingDatatypePtr->size) {
1337            result = 1;
1338        }
1339        else {
1340            result = 0;
1341        }
1342        return result;
1343    }
1344
1345
1346 Abstract Protocol Support
1347 -------------------------
1348
1349 Python supports a variety of *abstract* 'protocols;' the specific interfaces
1350 provided to use these interfaces are documented in :ref:`abstract`.
1351
1352
1353 A number of these abstract interfaces were defined early in the development of
1354 the Python implementation.  In particular, the number, mapping, and sequence
1355 protocols have been part of Python since the beginning.  Other protocols have
1356 been added over time.  For protocols which depend on several handler routines
1357 from the type implementation, the older protocols have been defined as optional
1358 blocks of handlers referenced by the type object.  For newer protocols there are
1359 additional slots in the main type object, with a flag bit being set to indicate
1360 that the slots are present and should be checked by the interpreter.  (The flag
1361 bit does not indicate that the slot values are non-*NULL*. The flag may be set
1362 to indicate the presence of a slot, but a slot may still be unfilled.) ::
1363
1364    PyNumberMethods   tp_as_number;
1365    PySequenceMethods tp_as_sequence;
1366    PyMappingMethods  tp_as_mapping;
1367
1368 If you wish your object to be able to act like a number, a sequence, or a
1369 mapping object, then you place the address of a structure that implements the C
1370 type :ctype:`PyNumberMethods`, :ctype:`PySequenceMethods`, or
1371 :ctype:`PyMappingMethods`, respectively. It is up to you to fill in this
1372 structure with appropriate values. You can find examples of the use of each of
1373 these in the :file:`Objects` directory of the Python source distribution. ::
1374
1375    hashfunc tp_hash;
1376
1377 This function, if you choose to provide it, should return a hash number for an
1378 instance of your data type. Here is a moderately pointless example::
1379
1380    static long
1381    newdatatype_hash(newdatatypeobject *obj)
1382    {
1383        long result;
1384        result = obj->obj_UnderlyingDatatypePtr->size;
1385        result = result * 3;
1386        return result;
1387    }
1388
1389 ::
1390
1391    ternaryfunc tp_call;
1392
1393 This function is called when an instance of your data type is "called", for
1394 example, if ``obj1`` is an instance of your data type and the Python script
1395 contains ``obj1('hello')``, the :attr:`tp_call` handler is invoked.
1396
1397 This function takes three arguments:
1398
1399 #. *arg1* is the instance of the data type which is the subject of the call. If
1400    the call is ``obj1('hello')``, then *arg1* is ``obj1``.
1401
1402 #. *arg2* is a tuple containing the arguments to the call.  You can use
1403    :cfunc:`PyArg_ParseTuple` to extract the arguments.
1404
1405 #. *arg3* is a dictionary of keyword arguments that were passed. If this is
1406    non-*NULL* and you support keyword arguments, use
1407    :cfunc:`PyArg_ParseTupleAndKeywords` to extract the arguments.  If you do not
1408    want to support keyword arguments and this is non-*NULL*, raise a
1409    :exc:`TypeError` with a message saying that keyword arguments are not supported.
1410
1411 Here is a desultory example of the implementation of the call function. ::
1412
1413    /* Implement the call function.
1414     *    obj1 is the instance receiving the call.
1415     *    obj2 is a tuple containing the arguments to the call, in this
1416     *         case 3 strings.
1417     */
1418    static PyObject *
1419    newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
1420    {
1421        PyObject *result;
1422        char *arg1;
1423        char *arg2;
1424        char *arg3;
1425
1426        if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
1427            return NULL;
1428        }
1429        result = PyString_FromFormat(
1430            "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",
1431            obj->obj_UnderlyingDatatypePtr->size,
1432            arg1, arg2, arg3);
1433        printf("\%s", PyString_AS_STRING(result));
1434        return result;
1435    }
1436
1437 XXX some fields need to be added here... ::
1438
1439    /* Added in release 2.2 */
1440    /* Iterators */
1441    getiterfunc tp_iter;
1442    iternextfunc tp_iternext;
1443
1444 These functions provide support for the iterator protocol.  Any object which
1445 wishes to support iteration over its contents (which may be generated during
1446 iteration) must implement the ``tp_iter`` handler.  Objects which are returned
1447 by a ``tp_iter`` handler must implement both the ``tp_iter`` and ``tp_iternext``
1448 handlers. Both handlers take exactly one parameter, the instance for which they
1449 are being called, and return a new reference.  In the case of an error, they
1450 should set an exception and return *NULL*.
1451
1452 For an object which represents an iterable collection, the ``tp_iter`` handler
1453 must return an iterator object.  The iterator object is responsible for
1454 maintaining the state of the iteration.  For collections which can support
1455 multiple iterators which do not interfere with each other (as lists and tuples
1456 do), a new iterator should be created and returned.  Objects which can only be
1457 iterated over once (usually due to side effects of iteration) should implement
1458 this handler by returning a new reference to themselves, and should also
1459 implement the ``tp_iternext`` handler.  File objects are an example of such an
1460 iterator.
1461
1462 Iterator objects should implement both handlers.  The ``tp_iter`` handler should
1463 return a new reference to the iterator (this is the same as the ``tp_iter``
1464 handler for objects which can only be iterated over destructively).  The
1465 ``tp_iternext`` handler should return a new reference to the next object in the
1466 iteration if there is one.  If the iteration has reached the end, it may return
1467 *NULL* without setting an exception or it may set :exc:`StopIteration`; avoiding
1468 the exception can yield slightly better performance.  If an actual error occurs,
1469 it should set an exception and return *NULL*.
1470
1471
1472 .. _weakref-support:
1473
1474 Weak Reference Support
1475 ----------------------
1476
1477 One of the goals of Python's weak-reference implementation is to allow any type
1478 to participate in the weak reference mechanism without incurring the overhead on
1479 those objects which do not benefit by weak referencing (such as numbers).
1480
1481 For an object to be weakly referencable, the extension must include a
1482 :ctype:`PyObject\*` field in the instance structure for the use of the weak
1483 reference mechanism; it must be initialized to *NULL* by the object's
1484 constructor.  It must also set the :attr:`tp_weaklistoffset` field of the
1485 corresponding type object to the offset of the field. For example, the instance
1486 type is defined with the following structure::
1487
1488    typedef struct {
1489        PyObject_HEAD
1490        PyClassObject *in_class;       /* The class object */
1491        PyObject      *in_dict;        /* A dictionary */
1492        PyObject      *in_weakreflist; /* List of weak references */
1493    } PyInstanceObject;
1494
1495 The statically-declared type object for instances is defined this way::
1496
1497    PyTypeObject PyInstance_Type = {
1498        PyObject_HEAD_INIT(&PyType_Type)
1499        0,
1500        "module.instance",
1501
1502        /* Lots of stuff omitted for brevity... */
1503
1504        Py_TPFLAGS_DEFAULT,                         /* tp_flags */
1505        0,                                          /* tp_doc */
1506        0,                                          /* tp_traverse */
1507        0,                                          /* tp_clear */
1508        0,                                          /* tp_richcompare */
1509        offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
1510    };
1511
1512 The type constructor is responsible for initializing the weak reference list to
1513 *NULL*::
1514
1515    static PyObject *
1516    instance_new() {
1517        /* Other initialization stuff omitted for brevity */
1518
1519        self->in_weakreflist = NULL;
1520
1521        return (PyObject *) self;
1522    }
1523
1524 The only further addition is that the destructor needs to call the weak
1525 reference manager to clear any weak references.  This should be done before any
1526 other parts of the destruction have occurred, but is only required if the weak
1527 reference list is non-*NULL*::
1528
1529    static void
1530    instance_dealloc(PyInstanceObject *inst)
1531    {
1532        /* Allocate temporaries if needed, but do not begin
1533           destruction just yet.
1534         */
1535
1536        if (inst->in_weakreflist != NULL)
1537            PyObject_ClearWeakRefs((PyObject *) inst);
1538
1539        /* Proceed with object destruction normally. */
1540    }
1541
1542
1543 More Suggestions
1544 ----------------
1545
1546 Remember that you can omit most of these functions, in which case you provide
1547 ``0`` as a value.  There are type definitions for each of the functions you must
1548 provide.  They are in :file:`object.h` in the Python include directory that
1549 comes with the source distribution of Python.
1550
1551 In order to learn how to implement any specific method for your new data type,
1552 do the following: Download and unpack the Python source distribution.  Go the
1553 :file:`Objects` directory, then search the C source files for ``tp_`` plus the
1554 function you want (for example, ``tp_print`` or ``tp_compare``).  You will find
1555 examples of the function you want to implement.
1556
1557 When you need to verify that an object is an instance of the type you are
1558 implementing, use the :cfunc:`PyObject_TypeCheck` function. A sample of its use
1559 might be something like the following::
1560
1561    if (! PyObject_TypeCheck(some_object, &MyType)) {
1562        PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
1563        return NULL;
1564    }
1565
1566 .. rubric:: Footnotes
1567
1568 .. [#] This is true when we know that the object is a basic type, like a string or a
1569    float.
1570
1571 .. [#] We relied on this in the :attr:`tp_dealloc` handler in this example, because our
1572    type doesn't support garbage collection. Even if a type supports garbage
1573    collection, there are calls that can be made to "untrack" the object from
1574    garbage collection, however, these calls are advanced and not covered here.
1575
1576 .. [#] We now know that the first and last members are strings, so perhaps we could be
1577    less careful about decrementing their reference counts, however, we accept
1578    instances of string subclasses. Even though deallocating normal strings won't
1579    call back into our objects, we can't guarantee that deallocating an instance of
1580    a string subclass won't call back into our objects.
1581
1582 .. [#] Even in the third version, we aren't guaranteed to avoid cycles.  Instances of
1583    string subclasses are allowed and string subclasses could allow cycles even if
1584    normal strings don't.
1585