Debian Codegraph @

cpython27/Doc/extending/newtypes.rst

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