blob: 376d09a7f264b46175d4586c8e7e6a58078458da [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _defining-new-types:
5
6******************
7Defining 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
15As mentioned in the last chapter, Python allows the writer of an extension
16module to define new types that can be manipulated from Python code, much like
17strings and lists in core Python.
18
19This is not hard; the code for all extension types follows a pattern, but there
20are some details that you need to understand before you can get started.
21
Georg Brandl116aa622007-08-15 14:28:22 +000022
23.. _dnt-basics:
24
25The Basics
26==========
27
28The Python runtime sees all Python objects as variables of type
Eli Bendersky49ac6f42012-02-27 19:18:35 +020029:c:type:`PyObject\*`, which serves as a "base type" for all Python objects.
30:c:type:`PyObject` itself only contains the refcount and a pointer to the
31object's "type object". This is where the action is; the type object determines
32which (C) functions get called when, for instance, an attribute gets looked
33up on an object or it is multiplied by another object. These C functions
34are called "type methods".
Georg Brandl116aa622007-08-15 14:28:22 +000035
36So, if you want to define a new object type, you need to create a new type
37object.
38
39This sort of thing can only be explained by example, so here's a minimal, but
40complete, module that defines a new type:
41
42.. literalinclude:: ../includes/noddy.c
43
44
45Now that's quite a bit to take in at once, but hopefully bits will seem familiar
46from the last chapter.
47
48The first bit that will be new is::
49
50 typedef struct {
51 PyObject_HEAD
52 } noddy_NoddyObject;
53
Eli Bendersky49ac6f42012-02-27 19:18:35 +020054This is what a Noddy object will contain---in this case, nothing more than what
55every Python object contains---a refcount and a pointer to a type object.
56These are the fields the ``PyObject_HEAD`` macro brings in. The reason for the
57macro is to standardize the layout and to enable special debugging fields in
58debug builds. Note that there is no semicolon after the ``PyObject_HEAD``
59macro; one is included in the macro definition. Be wary of adding one by
60accident; it's easy to do from habit, and your compiler might not complain,
61but someone else's probably will! (On Windows, MSVC is known to call this an
62error and refuse to compile the code.)
Georg Brandl116aa622007-08-15 14:28:22 +000063
64For contrast, let's take a look at the corresponding definition for standard
Georg Brandlda65f602007-12-08 18:59:56 +000065Python floats::
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 typedef struct {
68 PyObject_HEAD
Georg Brandlda65f602007-12-08 18:59:56 +000069 double ob_fval;
70 } PyFloatObject;
Georg Brandl116aa622007-08-15 14:28:22 +000071
72Moving on, we come to the crunch --- the type object. ::
73
74 static PyTypeObject noddy_NoddyType = {
Georg Brandlec12e822009-02-27 17:11:23 +000075 PyVarObject_HEAD_INIT(NULL, 0)
Georg Brandl913b2a32008-12-05 15:12:15 +000076 "noddy.Noddy", /* tp_name */
77 sizeof(noddy_NoddyObject), /* tp_basicsize */
78 0, /* tp_itemsize */
79 0, /* tp_dealloc */
80 0, /* tp_print */
81 0, /* tp_getattr */
82 0, /* tp_setattr */
Mark Dickinson9f989262009-02-02 21:29:40 +000083 0, /* tp_reserved */
Georg Brandl913b2a32008-12-05 15:12:15 +000084 0, /* tp_repr */
85 0, /* tp_as_number */
86 0, /* tp_as_sequence */
87 0, /* tp_as_mapping */
88 0, /* tp_hash */
89 0, /* tp_call */
90 0, /* tp_str */
91 0, /* tp_getattro */
92 0, /* tp_setattro */
93 0, /* tp_as_buffer */
94 Py_TPFLAGS_DEFAULT, /* tp_flags */
Georg Brandl116aa622007-08-15 14:28:22 +000095 "Noddy objects", /* tp_doc */
96 };
97
Georg Brandl60203b42010-10-06 10:11:56 +000098Now if you go and look up the definition of :c:type:`PyTypeObject` in
Georg Brandl116aa622007-08-15 14:28:22 +000099:file:`object.h` you'll see that it has many more fields that the definition
100above. The remaining fields will be filled with zeros by the C compiler, and
101it's common practice to not specify them explicitly unless you need them.
102
103This is so important that we're going to pick the top of it apart still
104further::
105
Georg Brandlec12e822009-02-27 17:11:23 +0000106 PyVarObject_HEAD_INIT(NULL, 0)
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108This line is a bit of a wart; what we'd like to write is::
109
Georg Brandlec12e822009-02-27 17:11:23 +0000110 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112as the type of a type object is "type", but this isn't strictly conforming C and
113some compilers complain. Fortunately, this member will be filled in for us by
Georg Brandl60203b42010-10-06 10:11:56 +0000114:c:func:`PyType_Ready`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandl116aa622007-08-15 14:28:22 +0000116 "noddy.Noddy", /* tp_name */
117
118The name of our type. This will appear in the default textual representation of
119our objects and in some error messages, for example::
120
121 >>> "" + noddy.new_noddy()
122 Traceback (most recent call last):
123 File "<stdin>", line 1, in ?
124 TypeError: cannot add type "noddy.Noddy" to string
125
126Note that the name is a dotted name that includes both the module name and the
127name of the type within the module. The module in this case is :mod:`noddy` and
128the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`. ::
129
130 sizeof(noddy_NoddyObject), /* tp_basicsize */
131
132This is so that Python knows how much memory to allocate when you call
Georg Brandl60203b42010-10-06 10:11:56 +0000133:c:func:`PyObject_New`.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135.. note::
136
137 If you want your type to be subclassable from Python, and your type has the same
138 :attr:`tp_basicsize` as its base type, you may have problems with multiple
139 inheritance. A Python subclass of your type will have to list your type first
140 in its :attr:`__bases__`, or else it will not be able to call your type's
141 :meth:`__new__` method without getting an error. You can avoid this problem by
142 ensuring that your type has a larger value for :attr:`tp_basicsize` than its
143 base type does. Most of the time, this will be true anyway, because either your
144 base type will be :class:`object`, or else you will be adding data members to
145 your base type, and therefore increasing its size.
146
147::
148
149 0, /* tp_itemsize */
150
151This has to do with variable length objects like lists and strings. Ignore this
152for now.
153
154Skipping a number of type methods that we don't provide, we set the class flags
155to :const:`Py_TPFLAGS_DEFAULT`. ::
156
Georg Brandl913b2a32008-12-05 15:12:15 +0000157 Py_TPFLAGS_DEFAULT, /* tp_flags */
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159All types should include this constant in their flags. It enables all of the
160members defined by the current version of Python.
161
162We provide a doc string for the type in :attr:`tp_doc`. ::
163
164 "Noddy objects", /* tp_doc */
165
166Now we get into the type methods, the things that make your objects different
167from the others. We aren't going to implement any of these in this version of
168the module. We'll expand this example later to have more interesting behavior.
169
170For now, all we want to be able to do is to create new :class:`Noddy` objects.
171To enable object creation, we have to provide a :attr:`tp_new` implementation.
172In this case, we can just use the default implementation provided by the API
Georg Brandl60203b42010-10-06 10:11:56 +0000173function :c:func:`PyType_GenericNew`. We'd like to just assign this to the
Georg Brandl116aa622007-08-15 14:28:22 +0000174:attr:`tp_new` slot, but we can't, for portability sake, On some platforms or
175compilers, we can't statically initialize a structure member with a function
176defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot
177in the module initialization function just before calling
Georg Brandl60203b42010-10-06 10:11:56 +0000178:c:func:`PyType_Ready`::
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 noddy_NoddyType.tp_new = PyType_GenericNew;
181 if (PyType_Ready(&noddy_NoddyType) < 0)
182 return;
183
184All the other type methods are *NULL*, so we'll go over them later --- that's
185for a later section!
186
187Everything else in the file should be familiar, except for some code in
Georg Brandl60203b42010-10-06 10:11:56 +0000188:c:func:`PyInit_noddy`::
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190 if (PyType_Ready(&noddy_NoddyType) < 0)
191 return;
192
193This initializes the :class:`Noddy` type, filing in a number of members,
194including :attr:`ob_type` that we initially set to *NULL*. ::
195
196 PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
197
198This adds the type to the module dictionary. This allows us to create
199:class:`Noddy` instances by calling the :class:`Noddy` class::
200
201 >>> import noddy
202 >>> mynoddy = noddy.Noddy()
203
204That's it! All that remains is to build it; put the above code in a file called
205:file:`noddy.c` and ::
206
207 from distutils.core import setup, Extension
208 setup(name="noddy", version="1.0",
209 ext_modules=[Extension("noddy", ["noddy.c"])])
210
211in a file called :file:`setup.py`; then typing ::
212
213 $ python setup.py build
214
215at a shell should produce a file :file:`noddy.so` in a subdirectory; move to
216that directory and fire up Python --- you should be able to ``import noddy`` and
217play around with Noddy objects.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219That wasn't so hard, was it?
220
221Of course, the current Noddy type is pretty uninteresting. It has no data and
222doesn't do anything. It can't even be subclassed.
223
224
225Adding data and methods to the Basic example
226--------------------------------------------
227
Eli Bendersky49ac6f42012-02-27 19:18:35 +0200228Let's extend the basic example to add some data and methods. Let's also make
Georg Brandl116aa622007-08-15 14:28:22 +0000229the type usable as a base class. We'll create a new module, :mod:`noddy2` that
230adds these capabilities:
231
232.. literalinclude:: ../includes/noddy2.c
233
234
235This version of the module has a number of changes.
236
237We've added an extra include::
238
Georg Brandl7bc6e4f2010-03-21 10:03:36 +0000239 #include <structmember.h>
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241This include provides declarations that we use to handle attributes, as
242described a bit later.
243
244The name of the :class:`Noddy` object structure has been shortened to
245:class:`Noddy`. The type object name has been shortened to :class:`NoddyType`.
246
247The :class:`Noddy` type now has three data attributes, *first*, *last*, and
248*number*. The *first* and *last* variables are Python strings containing first
249and last names. The *number* attribute is an integer.
250
251The object structure is updated accordingly::
252
253 typedef struct {
254 PyObject_HEAD
255 PyObject *first;
256 PyObject *last;
257 int number;
258 } Noddy;
259
260Because we now have data to manage, we have to be more careful about object
261allocation and deallocation. At a minimum, we need a deallocation method::
262
263 static void
264 Noddy_dealloc(Noddy* self)
265 {
266 Py_XDECREF(self->first);
267 Py_XDECREF(self->last);
Georg Brandl2ed237b2008-12-07 14:09:20 +0000268 Py_TYPE(self)->tp_free((PyObject*)self);
Georg Brandl116aa622007-08-15 14:28:22 +0000269 }
270
271which is assigned to the :attr:`tp_dealloc` member::
272
273 (destructor)Noddy_dealloc, /*tp_dealloc*/
274
275This method decrements the reference counts of the two Python attributes. We use
Georg Brandl60203b42010-10-06 10:11:56 +0000276:c:func:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members
Georg Brandl116aa622007-08-15 14:28:22 +0000277could be *NULL*. It then calls the :attr:`tp_free` member of the object's type
278to free the object's memory. Note that the object's type might not be
279:class:`NoddyType`, because the object may be an instance of a subclass.
280
281We want to make sure that the first and last names are initialized to empty
282strings, so we provide a new method::
283
284 static PyObject *
285 Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
286 {
287 Noddy *self;
288
289 self = (Noddy *)type->tp_alloc(type, 0);
290 if (self != NULL) {
291 self->first = PyString_FromString("");
Eli Bendersky47fe5c02011-08-12 11:40:39 +0300292 if (self->first == NULL) {
Georg Brandl116aa622007-08-15 14:28:22 +0000293 Py_DECREF(self);
294 return NULL;
Eli Bendersky47fe5c02011-08-12 11:40:39 +0300295 }
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297 self->last = PyString_FromString("");
Eli Bendersky47fe5c02011-08-12 11:40:39 +0300298 if (self->last == NULL) {
Georg Brandl116aa622007-08-15 14:28:22 +0000299 Py_DECREF(self);
300 return NULL;
Eli Bendersky47fe5c02011-08-12 11:40:39 +0300301 }
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303 self->number = 0;
304 }
305
306 return (PyObject *)self;
307 }
308
309and install it in the :attr:`tp_new` member::
310
311 Noddy_new, /* tp_new */
312
313The new member is responsible for creating (as opposed to initializing) objects
314of the type. It is exposed in Python as the :meth:`__new__` method. See the
315paper titled "Unifying types and classes in Python" for a detailed discussion of
316the :meth:`__new__` method. One reason to implement a new method is to assure
317the initial values of instance variables. In this case, we use the new method
318to make sure that the initial values of the members :attr:`first` and
319:attr:`last` are not *NULL*. If we didn't care whether the initial values were
Georg Brandl60203b42010-10-06 10:11:56 +0000320*NULL*, we could have used :c:func:`PyType_GenericNew` as our new method, as we
321did before. :c:func:`PyType_GenericNew` initializes all of the instance variable
Georg Brandl116aa622007-08-15 14:28:22 +0000322members to *NULL*.
323
324The new method is a static method that is passed the type being instantiated and
325any arguments passed when the type was called, and that returns the new object
326created. New methods always accept positional and keyword arguments, but they
327often ignore the arguments, leaving the argument handling to initializer
328methods. Note that if the type supports subclassing, the type passed may not be
Eli Bendersky49ac6f42012-02-27 19:18:35 +0200329the type being defined. The new method calls the :attr:`tp_alloc` slot to
330allocate memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather
Georg Brandl60203b42010-10-06 10:11:56 +0000331:c:func:`PyType_Ready` fills it for us by inheriting it from our base class,
Georg Brandl116aa622007-08-15 14:28:22 +0000332which is :class:`object` by default. Most types use the default allocation.
333
334.. note::
335
336 If you are creating a co-operative :attr:`tp_new` (one that calls a base type's
337 :attr:`tp_new` or :meth:`__new__`), you must *not* try to determine what method
338 to call using method resolution order at runtime. Always statically determine
339 what type you are going to call, and call its :attr:`tp_new` directly, or via
340 ``type->tp_base->tp_new``. If you do not do this, Python subclasses of your
341 type that also inherit from other Python-defined classes may not work correctly.
342 (Specifically, you may not be able to create instances of such subclasses
343 without getting a :exc:`TypeError`.)
344
345We provide an initialization function::
346
347 static int
348 Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
349 {
350 PyObject *first=NULL, *last=NULL, *tmp;
351
352 static char *kwlist[] = {"first", "last", "number", NULL};
353
354 if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
355 &first, &last,
356 &self->number))
357 return -1;
358
359 if (first) {
360 tmp = self->first;
361 Py_INCREF(first);
362 self->first = first;
363 Py_XDECREF(tmp);
364 }
365
366 if (last) {
367 tmp = self->last;
368 Py_INCREF(last);
369 self->last = last;
370 Py_XDECREF(tmp);
371 }
372
373 return 0;
374 }
375
376by filling the :attr:`tp_init` slot. ::
377
378 (initproc)Noddy_init, /* tp_init */
379
380The :attr:`tp_init` slot is exposed in Python as the :meth:`__init__` method. It
381is used to initialize an object after it's created. Unlike the new method, we
382can't guarantee that the initializer is called. The initializer isn't called
383when unpickling objects and it can be overridden. Our initializer accepts
384arguments to provide initial values for our instance. Initializers always accept
385positional and keyword arguments.
386
387Initializers can be called multiple times. Anyone can call the :meth:`__init__`
388method on our objects. For this reason, we have to be extra careful when
389assigning the new values. We might be tempted, for example to assign the
390:attr:`first` member like this::
391
392 if (first) {
393 Py_XDECREF(self->first);
394 Py_INCREF(first);
395 self->first = first;
396 }
397
398But this would be risky. Our type doesn't restrict the type of the
399:attr:`first` member, so it could be any kind of object. It could have a
400destructor that causes code to be executed that tries to access the
401:attr:`first` member. To be paranoid and protect ourselves against this
402possibility, we almost always reassign members before decrementing their
403reference counts. When don't we have to do this?
404
405* when we absolutely know that the reference count is greater than 1
406
407* when we know that deallocation of the object [#]_ will not cause any calls
408 back into our type's code
409
410* when decrementing a reference count in a :attr:`tp_dealloc` handler when
411 garbage-collections is not supported [#]_
412
Christian Heimesf75b2902008-03-16 17:29:44 +0000413We want to expose our instance variables as attributes. There are a
Georg Brandl116aa622007-08-15 14:28:22 +0000414number of ways to do that. The simplest way is to define member definitions::
415
416 static PyMemberDef Noddy_members[] = {
417 {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
418 "first name"},
419 {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
420 "last name"},
421 {"number", T_INT, offsetof(Noddy, number), 0,
422 "noddy number"},
423 {NULL} /* Sentinel */
424 };
425
426and put the definitions in the :attr:`tp_members` slot::
427
428 Noddy_members, /* tp_members */
429
430Each member definition has a member name, type, offset, access flags and
R. David Murraybcb8d3a2010-06-01 01:11:18 +0000431documentation string. See the :ref:`Generic-Attribute-Management` section below for
Georg Brandl116aa622007-08-15 14:28:22 +0000432details.
433
434A disadvantage of this approach is that it doesn't provide a way to restrict the
435types of objects that can be assigned to the Python attributes. We expect the
436first and last names to be strings, but any Python objects can be assigned.
437Further, the attributes can be deleted, setting the C pointers to *NULL*. Even
438though we can make sure the members are initialized to non-*NULL* values, the
439members can be set to *NULL* if the attributes are deleted.
440
441We define a single method, :meth:`name`, that outputs the objects name as the
442concatenation of the first and last names. ::
443
444 static PyObject *
445 Noddy_name(Noddy* self)
446 {
Georg Brandl116aa622007-08-15 14:28:22 +0000447 if (self->first == NULL) {
448 PyErr_SetString(PyExc_AttributeError, "first");
449 return NULL;
450 }
451
452 if (self->last == NULL) {
453 PyErr_SetString(PyExc_AttributeError, "last");
454 return NULL;
455 }
456
Eli Bendersky49ac6f42012-02-27 19:18:35 +0200457 return PyUnicode_FromFormat("%S %S", self->first, self->last);
Georg Brandl116aa622007-08-15 14:28:22 +0000458 }
459
460The method is implemented as a C function that takes a :class:`Noddy` (or
461:class:`Noddy` subclass) instance as the first argument. Methods always take an
462instance as the first argument. Methods often take positional and keyword
Eli Bendersky49ac6f42012-02-27 19:18:35 +0200463arguments as well, but in this case we don't take any and don't need to accept
Georg Brandl116aa622007-08-15 14:28:22 +0000464a positional argument tuple or keyword argument dictionary. This method is
465equivalent to the Python method::
466
467 def name(self):
468 return "%s %s" % (self.first, self.last)
469
470Note that we have to check for the possibility that our :attr:`first` and
471:attr:`last` members are *NULL*. This is because they can be deleted, in which
472case they are set to *NULL*. It would be better to prevent deletion of these
473attributes and to restrict the attribute values to be strings. We'll see how to
474do that in the next section.
475
476Now that we've defined the method, we need to create an array of method
477definitions::
478
479 static PyMethodDef Noddy_methods[] = {
480 {"name", (PyCFunction)Noddy_name, METH_NOARGS,
481 "Return the name, combining the first and last name"
482 },
483 {NULL} /* Sentinel */
484 };
485
486and assign them to the :attr:`tp_methods` slot::
487
488 Noddy_methods, /* tp_methods */
489
490Note that we used the :const:`METH_NOARGS` flag to indicate that the method is
491passed no arguments.
492
493Finally, we'll make our type usable as a base class. We've written our methods
494carefully so far so that they don't make any assumptions about the type of the
495object being created or used, so all we need to do is to add the
496:const:`Py_TPFLAGS_BASETYPE` to our class flag definition::
497
498 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
499
Georg Brandl60203b42010-10-06 10:11:56 +0000500We rename :c:func:`PyInit_noddy` to :c:func:`PyInit_noddy2` and update the module
501name in the :c:type:`PyModuleDef` struct.
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503Finally, we update our :file:`setup.py` file to build the new module::
504
505 from distutils.core import setup, Extension
506 setup(name="noddy", version="1.0",
507 ext_modules=[
508 Extension("noddy", ["noddy.c"]),
509 Extension("noddy2", ["noddy2.c"]),
510 ])
511
512
513Providing finer control over data attributes
514--------------------------------------------
515
516In this section, we'll provide finer control over how the :attr:`first` and
517:attr:`last` attributes are set in the :class:`Noddy` example. In the previous
518version of our module, the instance variables :attr:`first` and :attr:`last`
519could be set to non-string values or even deleted. We want to make sure that
520these attributes always contain strings.
521
522.. literalinclude:: ../includes/noddy3.c
523
524
525To provide greater control, over the :attr:`first` and :attr:`last` attributes,
526we'll use custom getter and setter functions. Here are the functions for
527getting and setting the :attr:`first` attribute::
528
529 Noddy_getfirst(Noddy *self, void *closure)
530 {
531 Py_INCREF(self->first);
532 return self->first;
533 }
534
535 static int
536 Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
537 {
538 if (value == NULL) {
539 PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
540 return -1;
541 }
542
543 if (! PyString_Check(value)) {
544 PyErr_SetString(PyExc_TypeError,
545 "The first attribute value must be a string");
546 return -1;
547 }
548
549 Py_DECREF(self->first);
550 Py_INCREF(value);
551 self->first = value;
552
553 return 0;
554 }
555
556The getter function is passed a :class:`Noddy` object and a "closure", which is
557void pointer. In this case, the closure is ignored. (The closure supports an
558advanced usage in which definition data is passed to the getter and setter. This
559could, for example, be used to allow a single set of getter and setter functions
560that decide the attribute to get or set based on data in the closure.)
561
562The setter function is passed the :class:`Noddy` object, the new value, and the
563closure. The new value may be *NULL*, in which case the attribute is being
564deleted. In our setter, we raise an error if the attribute is deleted or if the
565attribute value is not a string.
566
Georg Brandl60203b42010-10-06 10:11:56 +0000567We create an array of :c:type:`PyGetSetDef` structures::
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569 static PyGetSetDef Noddy_getseters[] = {
570 {"first",
571 (getter)Noddy_getfirst, (setter)Noddy_setfirst,
572 "first name",
573 NULL},
574 {"last",
575 (getter)Noddy_getlast, (setter)Noddy_setlast,
576 "last name",
577 NULL},
578 {NULL} /* Sentinel */
579 };
580
581and register it in the :attr:`tp_getset` slot::
582
583 Noddy_getseters, /* tp_getset */
584
Christian Heimesf75b2902008-03-16 17:29:44 +0000585to register our attribute getters and setters.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
Georg Brandl60203b42010-10-06 10:11:56 +0000587The last item in a :c:type:`PyGetSetDef` structure is the closure mentioned
Georg Brandl116aa622007-08-15 14:28:22 +0000588above. In this case, we aren't using the closure, so we just pass *NULL*.
589
590We also remove the member definitions for these attributes::
591
592 static PyMemberDef Noddy_members[] = {
593 {"number", T_INT, offsetof(Noddy, number), 0,
594 "noddy number"},
595 {NULL} /* Sentinel */
596 };
597
598We also need to update the :attr:`tp_init` handler to only allow strings [#]_ to
599be passed::
600
601 static int
602 Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
603 {
604 PyObject *first=NULL, *last=NULL, *tmp;
605
606 static char *kwlist[] = {"first", "last", "number", NULL};
607
608 if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SSi", kwlist,
609 &first, &last,
610 &self->number))
611 return -1;
612
613 if (first) {
614 tmp = self->first;
615 Py_INCREF(first);
616 self->first = first;
617 Py_DECREF(tmp);
618 }
619
620 if (last) {
621 tmp = self->last;
622 Py_INCREF(last);
623 self->last = last;
624 Py_DECREF(tmp);
625 }
626
627 return 0;
628 }
629
630With these changes, we can assure that the :attr:`first` and :attr:`last`
631members are never *NULL* so we can remove checks for *NULL* values in almost all
Georg Brandl60203b42010-10-06 10:11:56 +0000632cases. This means that most of the :c:func:`Py_XDECREF` calls can be converted to
633:c:func:`Py_DECREF` calls. The only place we can't change these calls is in the
Georg Brandl116aa622007-08-15 14:28:22 +0000634deallocator, where there is the possibility that the initialization of these
635members failed in the constructor.
636
637We also rename the module initialization function and module name in the
638initialization function, as we did before, and we add an extra definition to the
639:file:`setup.py` file.
640
641
642Supporting cyclic garbage collection
643------------------------------------
644
645Python has a cyclic-garbage collector that can identify unneeded objects even
646when their reference counts are not zero. This can happen when objects are
647involved in cycles. For example, consider::
648
649 >>> l = []
650 >>> l.append(l)
651 >>> del l
652
653In this example, we create a list that contains itself. When we delete it, it
654still has a reference from itself. Its reference count doesn't drop to zero.
655Fortunately, Python's cyclic-garbage collector will eventually figure out that
656the list is garbage and free it.
657
658In the second version of the :class:`Noddy` example, we allowed any kind of
659object to be stored in the :attr:`first` or :attr:`last` attributes. [#]_ This
660means that :class:`Noddy` objects can participate in cycles::
661
662 >>> import noddy2
663 >>> n = noddy2.Noddy()
664 >>> l = [n]
665 >>> n.first = l
666
667This is pretty silly, but it gives us an excuse to add support for the
668cyclic-garbage collector to the :class:`Noddy` example. To support cyclic
669garbage collection, types need to fill two slots and set a class flag that
670enables these slots:
671
672.. literalinclude:: ../includes/noddy4.c
673
674
675The traversal method provides access to subobjects that could participate in
676cycles::
677
678 static int
679 Noddy_traverse(Noddy *self, visitproc visit, void *arg)
680 {
681 int vret;
682
683 if (self->first) {
684 vret = visit(self->first, arg);
685 if (vret != 0)
686 return vret;
687 }
688 if (self->last) {
689 vret = visit(self->last, arg);
690 if (vret != 0)
691 return vret;
692 }
693
694 return 0;
695 }
696
697For each subobject that can participate in cycles, we need to call the
Georg Brandl60203b42010-10-06 10:11:56 +0000698:c:func:`visit` function, which is passed to the traversal method. The
699:c:func:`visit` function takes as arguments the subobject and the extra argument
Georg Brandl116aa622007-08-15 14:28:22 +0000700*arg* passed to the traversal method. It returns an integer value that must be
701returned if it is non-zero.
702
Georg Brandl60203b42010-10-06 10:11:56 +0000703Python provides a :c:func:`Py_VISIT` macro that automates calling visit
704functions. With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be simplified::
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 static int
707 Noddy_traverse(Noddy *self, visitproc visit, void *arg)
708 {
709 Py_VISIT(self->first);
710 Py_VISIT(self->last);
711 return 0;
712 }
713
714.. note::
715
716 Note that the :attr:`tp_traverse` implementation must name its arguments exactly
Georg Brandl60203b42010-10-06 10:11:56 +0000717 *visit* and *arg* in order to use :c:func:`Py_VISIT`. This is to encourage
Georg Brandl116aa622007-08-15 14:28:22 +0000718 uniformity across these boring implementations.
719
720We also need to provide a method for clearing any subobjects that can
721participate in cycles. We implement the method and reimplement the deallocator
722to use it::
723
724 static int
725 Noddy_clear(Noddy *self)
726 {
727 PyObject *tmp;
728
729 tmp = self->first;
730 self->first = NULL;
731 Py_XDECREF(tmp);
732
733 tmp = self->last;
734 self->last = NULL;
735 Py_XDECREF(tmp);
736
737 return 0;
738 }
739
740 static void
741 Noddy_dealloc(Noddy* self)
742 {
743 Noddy_clear(self);
Georg Brandl2ed237b2008-12-07 14:09:20 +0000744 Py_TYPE(self)->tp_free((PyObject*)self);
Georg Brandl116aa622007-08-15 14:28:22 +0000745 }
746
Georg Brandl60203b42010-10-06 10:11:56 +0000747Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the
Georg Brandl116aa622007-08-15 14:28:22 +0000748temporary variable so that we can set each member to *NULL* before decrementing
749its reference count. We do this because, as was discussed earlier, if the
750reference count drops to zero, we might cause code to run that calls back into
751the object. In addition, because we now support garbage collection, we also
752have to worry about code being run that triggers garbage collection. If garbage
753collection is run, our :attr:`tp_traverse` handler could get called. We can't
Georg Brandl60203b42010-10-06 10:11:56 +0000754take a chance of having :c:func:`Noddy_traverse` called when a member's reference
Georg Brandl116aa622007-08-15 14:28:22 +0000755count has dropped to zero and its value hasn't been set to *NULL*.
756
Georg Brandl60203b42010-10-06 10:11:56 +0000757Python provides a :c:func:`Py_CLEAR` that automates the careful decrementing of
758reference counts. With :c:func:`Py_CLEAR`, the :c:func:`Noddy_clear` function can
Georg Brandle6bcc912008-05-12 18:05:20 +0000759be simplified::
Georg Brandl116aa622007-08-15 14:28:22 +0000760
761 static int
762 Noddy_clear(Noddy *self)
763 {
764 Py_CLEAR(self->first);
765 Py_CLEAR(self->last);
766 return 0;
767 }
768
769Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags::
770
Georg Brandl913b2a32008-12-05 15:12:15 +0000771 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Georg Brandl116aa622007-08-15 14:28:22 +0000772
773That's pretty much it. If we had written custom :attr:`tp_alloc` or
774:attr:`tp_free` slots, we'd need to modify them for cyclic-garbage collection.
775Most extensions will use the versions automatically provided.
776
777
778Subclassing other types
779-----------------------
780
781It is possible to create new extension types that are derived from existing
782types. It is easiest to inherit from the built in types, since an extension can
783easily use the :class:`PyTypeObject` it needs. It can be difficult to share
784these :class:`PyTypeObject` structures between extension modules.
785
786In this example we will create a :class:`Shoddy` type that inherits from the
Georg Brandl22b34312009-07-26 14:54:51 +0000787built-in :class:`list` type. The new type will be completely compatible with
Georg Brandl116aa622007-08-15 14:28:22 +0000788regular lists, but will have an additional :meth:`increment` method that
789increases an internal counter. ::
790
791 >>> import shoddy
792 >>> s = shoddy.Shoddy(range(3))
793 >>> s.extend(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000794 >>> print(len(s))
Georg Brandl116aa622007-08-15 14:28:22 +0000795 6
Georg Brandl6911e3c2007-09-04 07:15:32 +0000796 >>> print(s.increment())
Georg Brandl116aa622007-08-15 14:28:22 +0000797 1
Georg Brandl6911e3c2007-09-04 07:15:32 +0000798 >>> print(s.increment())
Georg Brandl116aa622007-08-15 14:28:22 +0000799 2
800
801.. literalinclude:: ../includes/shoddy.c
802
803
804As you can see, the source code closely resembles the :class:`Noddy` examples in
805previous sections. We will break down the main differences between them. ::
806
807 typedef struct {
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000808 PyListObject list;
809 int state;
Georg Brandl116aa622007-08-15 14:28:22 +0000810 } Shoddy;
811
812The primary difference for derived type objects is that the base type's object
813structure must be the first value. The base type will already include the
Georg Brandl60203b42010-10-06 10:11:56 +0000814:c:func:`PyObject_HEAD` at the beginning of its structure.
Georg Brandl116aa622007-08-15 14:28:22 +0000815
816When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can
817be safely cast to both *PyListObject\** and *Shoddy\**. ::
818
819 static int
820 Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
821 {
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000822 if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
823 return -1;
824 self->state = 0;
825 return 0;
Georg Brandl116aa622007-08-15 14:28:22 +0000826 }
827
828In the :attr:`__init__` method for our type, we can see how to call through to
829the :attr:`__init__` method of the base type.
830
831This pattern is important when writing a type with custom :attr:`new` and
832:attr:`dealloc` methods. The :attr:`new` method should not actually create the
833memory for the object with :attr:`tp_alloc`, that will be handled by the base
834class when calling its :attr:`tp_new`.
835
Georg Brandl60203b42010-10-06 10:11:56 +0000836When filling out the :c:func:`PyTypeObject` for the :class:`Shoddy` type, you see
837a slot for :c:func:`tp_base`. Due to cross platform compiler issues, you can't
838fill that field directly with the :c:func:`PyList_Type`; it can be done later in
839the module's :c:func:`init` function. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841 PyMODINIT_FUNC
Georg Brandl913b2a32008-12-05 15:12:15 +0000842 PyInit_shoddy(void)
Georg Brandl116aa622007-08-15 14:28:22 +0000843 {
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000844 PyObject *m;
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000846 ShoddyType.tp_base = &PyList_Type;
847 if (PyType_Ready(&ShoddyType) < 0)
848 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000850 m = PyModule_Create(&shoddymodule);
851 if (m == NULL)
852 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +0000853
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000854 Py_INCREF(&ShoddyType);
855 PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
Georg Brandl21151762009-03-31 15:52:41 +0000856 return m;
Georg Brandl116aa622007-08-15 14:28:22 +0000857 }
858
Georg Brandl60203b42010-10-06 10:11:56 +0000859Before calling :c:func:`PyType_Ready`, the type structure must have the
Georg Brandl116aa622007-08-15 14:28:22 +0000860:attr:`tp_base` slot filled in. When we are deriving a new type, it is not
Georg Brandl60203b42010-10-06 10:11:56 +0000861necessary to fill out the :attr:`tp_alloc` slot with :c:func:`PyType_GenericNew`
Georg Brandl116aa622007-08-15 14:28:22 +0000862-- the allocate function from the base type will be inherited.
863
Georg Brandl60203b42010-10-06 10:11:56 +0000864After that, calling :c:func:`PyType_Ready` and adding the type object to the
Georg Brandl116aa622007-08-15 14:28:22 +0000865module is the same as with the basic :class:`Noddy` examples.
866
867
868.. _dnt-type-methods:
869
870Type Methods
871============
872
873This section aims to give a quick fly-by on the various type methods you can
874implement and what they do.
875
Georg Brandl60203b42010-10-06 10:11:56 +0000876Here is the definition of :c:type:`PyTypeObject`, with some fields only used in
Georg Brandl116aa622007-08-15 14:28:22 +0000877debug builds omitted:
878
879.. literalinclude:: ../includes/typestruct.h
880
881
882Now that's a *lot* of methods. Don't worry too much though - if you have a type
883you want to define, the chances are very good that you will only implement a
884handful of these.
885
886As you probably expect by now, we're going to go over this and give more
887information about the various handlers. We won't go in the order they are
888defined in the structure, because there is a lot of historical baggage that
889impacts the ordering of the fields; be sure your type initialization keeps the
890fields in the right order! It's often easiest to find an example that includes
891all the fields you need (even if they're initialized to ``0``) and then change
892the values to suit your new type. ::
893
894 char *tp_name; /* For printing */
895
896The name of the type - as mentioned in the last section, this will appear in
897various places, almost entirely for diagnostic purposes. Try to choose something
898that will be helpful in such a situation! ::
899
900 int tp_basicsize, tp_itemsize; /* For allocation */
901
902These fields tell the runtime how much memory to allocate when new objects of
903this type are created. Python has some built-in support for variable length
904structures (think: strings, lists) which is where the :attr:`tp_itemsize` field
905comes in. This will be dealt with later. ::
906
907 char *tp_doc;
908
909Here you can put a string (or its address) that you want returned when the
910Python script references ``obj.__doc__`` to retrieve the doc string.
911
912Now we come to the basic type methods---the ones most extension types will
913implement.
914
915
916Finalization and De-allocation
917------------------------------
918
919.. index::
920 single: object; deallocation
921 single: deallocation, object
922 single: object; finalization
923 single: finalization, of objects
924
925::
926
927 destructor tp_dealloc;
928
929This function is called when the reference count of the instance of your type is
930reduced to zero and the Python interpreter wants to reclaim it. If your type
931has memory to free or other clean-up to perform, put it here. The object itself
932needs to be freed here as well. Here is an example of this function::
933
934 static void
935 newdatatype_dealloc(newdatatypeobject * obj)
936 {
937 free(obj->obj_UnderlyingDatatypePtr);
Georg Brandl2ed237b2008-12-07 14:09:20 +0000938 Py_TYPE(obj)->tp_free(obj);
Georg Brandl116aa622007-08-15 14:28:22 +0000939 }
940
941.. index::
942 single: PyErr_Fetch()
943 single: PyErr_Restore()
944
945One important requirement of the deallocator function is that it leaves any
946pending exceptions alone. This is important since deallocators are frequently
947called as the interpreter unwinds the Python stack; when the stack is unwound
948due to an exception (rather than normal returns), nothing is done to protect the
949deallocators from seeing that an exception has already been set. Any actions
950which a deallocator performs which may cause additional Python code to be
951executed may detect that an exception has been set. This can lead to misleading
952errors from the interpreter. The proper way to protect against this is to save
953a pending exception before performing the unsafe action, and restoring it when
Georg Brandl60203b42010-10-06 10:11:56 +0000954done. This can be done using the :c:func:`PyErr_Fetch` and
955:c:func:`PyErr_Restore` functions::
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957 static void
958 my_dealloc(PyObject *obj)
959 {
960 MyObject *self = (MyObject *) obj;
961 PyObject *cbresult;
962
963 if (self->my_callback != NULL) {
964 PyObject *err_type, *err_value, *err_traceback;
965 int have_error = PyErr_Occurred() ? 1 : 0;
966
967 if (have_error)
968 PyErr_Fetch(&err_type, &err_value, &err_traceback);
969
970 cbresult = PyObject_CallObject(self->my_callback, NULL);
971 if (cbresult == NULL)
972 PyErr_WriteUnraisable(self->my_callback);
973 else
974 Py_DECREF(cbresult);
975
976 if (have_error)
977 PyErr_Restore(err_type, err_value, err_traceback);
978
979 Py_DECREF(self->my_callback);
980 }
Georg Brandl2ed237b2008-12-07 14:09:20 +0000981 Py_TYPE(obj)->tp_free((PyObject*)self);
Georg Brandl116aa622007-08-15 14:28:22 +0000982 }
983
984
985Object Presentation
986-------------------
987
988.. index::
989 builtin: repr
990 builtin: str
991
992In Python, there are two ways to generate a textual representation of an object:
993the :func:`repr` function, and the :func:`str` function. (The :func:`print`
994function just calls :func:`str`.) These handlers are both optional.
995
996::
997
998 reprfunc tp_repr;
999 reprfunc tp_str;
1000
1001The :attr:`tp_repr` handler should return a string object containing a
1002representation of the instance for which it is called. Here is a simple
1003example::
1004
1005 static PyObject *
1006 newdatatype_repr(newdatatypeobject * obj)
1007 {
1008 return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
1009 obj->obj_UnderlyingDatatypePtr->size);
1010 }
1011
1012If no :attr:`tp_repr` handler is specified, the interpreter will supply a
1013representation that uses the type's :attr:`tp_name` and a uniquely-identifying
1014value for the object.
1015
1016The :attr:`tp_str` handler is to :func:`str` what the :attr:`tp_repr` handler
1017described above is to :func:`repr`; that is, it is called when Python code calls
1018:func:`str` on an instance of your object. Its implementation is very similar
1019to the :attr:`tp_repr` function, but the resulting string is intended for human
1020consumption. If :attr:`tp_str` is not specified, the :attr:`tp_repr` handler is
1021used instead.
1022
1023Here is a simple example::
1024
1025 static PyObject *
1026 newdatatype_str(newdatatypeobject * obj)
1027 {
1028 return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
1029 obj->obj_UnderlyingDatatypePtr->size);
1030 }
1031
Georg Brandl116aa622007-08-15 14:28:22 +00001032
1033
1034Attribute Management
1035--------------------
1036
1037For every object which can support attributes, the corresponding type must
1038provide the functions that control how the attributes are resolved. There needs
1039to be a function which can retrieve attributes (if any are defined), and another
1040to set attributes (if setting attributes is allowed). Removing an attribute is
1041a special case, for which the new value passed to the handler is *NULL*.
1042
1043Python supports two pairs of attribute handlers; a type that supports attributes
1044only needs to implement the functions for one pair. The difference is that one
Georg Brandl60203b42010-10-06 10:11:56 +00001045pair takes the name of the attribute as a :c:type:`char\*`, while the other
1046accepts a :c:type:`PyObject\*`. Each type can use whichever pair makes more
Georg Brandl116aa622007-08-15 14:28:22 +00001047sense for the implementation's convenience. ::
1048
1049 getattrfunc tp_getattr; /* char * version */
1050 setattrfunc tp_setattr;
1051 /* ... */
Amaury Forgeot d'Arc87ce6d72008-07-02 22:59:48 +00001052 getattrofunc tp_getattro; /* PyObject * version */
1053 setattrofunc tp_setattro;
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055If accessing attributes of an object is always a simple operation (this will be
1056explained shortly), there are generic implementations which can be used to
Georg Brandl60203b42010-10-06 10:11:56 +00001057provide the :c:type:`PyObject\*` version of the attribute management functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001058The actual need for type-specific attribute handlers almost completely
1059disappeared starting with Python 2.2, though there are many examples which have
1060not been updated to use some of the new generic mechanism that is available.
1061
1062
R. David Murraybcb8d3a2010-06-01 01:11:18 +00001063.. _generic-attribute-management:
1064
Georg Brandl116aa622007-08-15 14:28:22 +00001065Generic Attribute Management
1066^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1067
Georg Brandl116aa622007-08-15 14:28:22 +00001068Most extension types only use *simple* attributes. So, what makes the
1069attributes simple? There are only a couple of conditions that must be met:
1070
Georg Brandl60203b42010-10-06 10:11:56 +00001071#. The name of the attributes must be known when :c:func:`PyType_Ready` is
Georg Brandl116aa622007-08-15 14:28:22 +00001072 called.
1073
1074#. No special processing is needed to record that an attribute was looked up or
1075 set, nor do actions need to be taken based on the value.
1076
1077Note that this list does not place any restrictions on the values of the
1078attributes, when the values are computed, or how relevant data is stored.
1079
Georg Brandl60203b42010-10-06 10:11:56 +00001080When :c:func:`PyType_Ready` is called, it uses three tables referenced by the
Georg Brandl9afde1c2007-11-01 20:32:30 +00001081type object to create :term:`descriptor`\s which are placed in the dictionary of the
Georg Brandl116aa622007-08-15 14:28:22 +00001082type object. Each descriptor controls access to one attribute of the instance
1083object. Each of the tables is optional; if all three are *NULL*, instances of
1084the type will only have attributes that are inherited from their base type, and
1085should leave the :attr:`tp_getattro` and :attr:`tp_setattro` fields *NULL* as
1086well, allowing the base type to handle attributes.
1087
1088The tables are declared as three fields of the type object::
1089
1090 struct PyMethodDef *tp_methods;
1091 struct PyMemberDef *tp_members;
1092 struct PyGetSetDef *tp_getset;
1093
1094If :attr:`tp_methods` is not *NULL*, it must refer to an array of
Georg Brandl60203b42010-10-06 10:11:56 +00001095:c:type:`PyMethodDef` structures. Each entry in the table is an instance of this
Georg Brandl116aa622007-08-15 14:28:22 +00001096structure::
1097
1098 typedef struct PyMethodDef {
1099 char *ml_name; /* method name */
1100 PyCFunction ml_meth; /* implementation function */
Georg Brandla1c6a1c2009-01-03 21:26:05 +00001101 int ml_flags; /* flags */
Georg Brandl116aa622007-08-15 14:28:22 +00001102 char *ml_doc; /* docstring */
1103 } PyMethodDef;
1104
1105One entry should be defined for each method provided by the type; no entries are
1106needed for methods inherited from a base type. One additional entry is needed
1107at the end; it is a sentinel that marks the end of the array. The
1108:attr:`ml_name` field of the sentinel must be *NULL*.
1109
Georg Brandl116aa622007-08-15 14:28:22 +00001110The second table is used to define attributes which map directly to data stored
1111in the instance. A variety of primitive C types are supported, and access may
1112be read-only or read-write. The structures in the table are defined as::
1113
1114 typedef struct PyMemberDef {
1115 char *name;
1116 int type;
1117 int offset;
1118 int flags;
1119 char *doc;
1120 } PyMemberDef;
1121
Georg Brandl9afde1c2007-11-01 20:32:30 +00001122For each entry in the table, a :term:`descriptor` will be constructed and added to the
Georg Brandl116aa622007-08-15 14:28:22 +00001123type which will be able to extract a value from the instance structure. The
1124:attr:`type` field should contain one of the type codes defined in the
1125:file:`structmember.h` header; the value will be used to determine how to
1126convert Python values to and from C values. The :attr:`flags` field is used to
1127store flags which control how the attribute can be accessed.
1128
Georg Brandl116aa622007-08-15 14:28:22 +00001129The following flag constants are defined in :file:`structmember.h`; they may be
1130combined using bitwise-OR.
1131
1132+---------------------------+----------------------------------------------+
1133| Constant | Meaning |
1134+===========================+==============================================+
1135| :const:`READONLY` | Never writable. |
1136+---------------------------+----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001137| :const:`READ_RESTRICTED` | Not readable in restricted mode. |
1138+---------------------------+----------------------------------------------+
1139| :const:`WRITE_RESTRICTED` | Not writable in restricted mode. |
1140+---------------------------+----------------------------------------------+
1141| :const:`RESTRICTED` | Not readable or writable in restricted mode. |
1142+---------------------------+----------------------------------------------+
1143
1144.. index::
1145 single: READONLY
Georg Brandl116aa622007-08-15 14:28:22 +00001146 single: READ_RESTRICTED
1147 single: WRITE_RESTRICTED
1148 single: RESTRICTED
1149
1150An interesting advantage of using the :attr:`tp_members` table to build
1151descriptors that are used at runtime is that any attribute defined this way can
1152have an associated doc string simply by providing the text in the table. An
1153application can use the introspection API to retrieve the descriptor from the
1154class object, and get the doc string using its :attr:`__doc__` attribute.
1155
1156As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value
1157of *NULL* is required.
1158
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001159.. XXX Descriptors need to be explained in more detail somewhere, but not here.
Georg Brandl48310cd2009-01-03 21:18:54 +00001160
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001161 Descriptor objects have two handler functions which correspond to the
1162 \member{tp_getattro} and \member{tp_setattro} handlers. The
1163 \method{__get__()} handler is a function which is passed the descriptor,
1164 instance, and type objects, and returns the value of the attribute, or it
1165 returns \NULL{} and sets an exception. The \method{__set__()} handler is
1166 passed the descriptor, instance, type, and new value;
Georg Brandl116aa622007-08-15 14:28:22 +00001167
1168
1169Type-specific Attribute Management
1170^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1171
Georg Brandl60203b42010-10-06 10:11:56 +00001172For simplicity, only the :c:type:`char\*` version will be demonstrated here; the
1173type of the name parameter is the only difference between the :c:type:`char\*`
1174and :c:type:`PyObject\*` flavors of the interface. This example effectively does
Georg Brandl116aa622007-08-15 14:28:22 +00001175the same thing as the generic example above, but does not use the generic
Amaury Forgeot d'Arc87ce6d72008-07-02 22:59:48 +00001176support added in Python 2.2. It explains how the handler functions are
Georg Brandl116aa622007-08-15 14:28:22 +00001177called, so that if you do need to extend their functionality, you'll understand
1178what needs to be done.
1179
1180The :attr:`tp_getattr` handler is called when the object requires an attribute
1181look-up. It is called in the same situations where the :meth:`__getattr__`
1182method of a class would be called.
1183
Georg Brandl116aa622007-08-15 14:28:22 +00001184Here is an example::
1185
Georg Brandl116aa622007-08-15 14:28:22 +00001186 static PyObject *
1187 newdatatype_getattr(newdatatypeobject *obj, char *name)
1188 {
Amaury Forgeot d'Arc87ce6d72008-07-02 22:59:48 +00001189 if (strcmp(name, "data") == 0)
1190 {
1191 return PyInt_FromLong(obj->data);
1192 }
1193
1194 PyErr_Format(PyExc_AttributeError,
1195 "'%.50s' object has no attribute '%.400s'",
Georg Brandl06788c92009-01-03 21:31:47 +00001196 tp->tp_name, name);
Amaury Forgeot d'Arc87ce6d72008-07-02 22:59:48 +00001197 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001198 }
1199
1200The :attr:`tp_setattr` handler is called when the :meth:`__setattr__` or
1201:meth:`__delattr__` method of a class instance would be called. When an
1202attribute should be deleted, the third parameter will be *NULL*. Here is an
1203example that simply raises an exception; if this were really all you wanted, the
1204:attr:`tp_setattr` handler should be set to *NULL*. ::
1205
1206 static int
1207 newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
1208 {
1209 (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
1210 return -1;
1211 }
1212
Georg Brandl890a49a2009-03-31 18:56:38 +00001213Object Comparison
1214-----------------
Georg Brandl116aa622007-08-15 14:28:22 +00001215
Georg Brandl890a49a2009-03-31 18:56:38 +00001216::
Georg Brandl48310cd2009-01-03 21:18:54 +00001217
Georg Brandl890a49a2009-03-31 18:56:38 +00001218 richcmpfunc tp_richcompare;
Georg Brandl48310cd2009-01-03 21:18:54 +00001219
Georg Brandl890a49a2009-03-31 18:56:38 +00001220The :attr:`tp_richcompare` handler is called when comparisons are needed. It is
1221analogous to the :ref:`rich comparison methods <richcmpfuncs>`, like
Georg Brandl60203b42010-10-06 10:11:56 +00001222:meth:`__lt__`, and also called by :c:func:`PyObject_RichCompare` and
1223:c:func:`PyObject_RichCompareBool`.
Georg Brandl48310cd2009-01-03 21:18:54 +00001224
Georg Brandl890a49a2009-03-31 18:56:38 +00001225This function is called with two Python objects and the operator as arguments,
1226where the operator is one of ``Py_EQ``, ``Py_NE``, ``Py_LE``, ``Py_GT``,
1227``Py_LT`` or ``Py_GT``. It should compare the two objects with respect to the
1228specified operator and return ``Py_True`` or ``Py_False`` if the comparison is
Georg Brandl6faee4e2010-09-21 14:48:28 +00001229successful, ``Py_NotImplemented`` to indicate that comparison is not
Georg Brandl890a49a2009-03-31 18:56:38 +00001230implemented and the other object's comparison method should be tried, or *NULL*
1231if an exception was set.
Georg Brandl48310cd2009-01-03 21:18:54 +00001232
Georg Brandl890a49a2009-03-31 18:56:38 +00001233Here is a sample implementation, for a datatype that is considered equal if the
1234size of an internal pointer is equal::
Georg Brandl48310cd2009-01-03 21:18:54 +00001235
Georg Brandl890a49a2009-03-31 18:56:38 +00001236 static int
1237 newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op)
1238 {
1239 PyObject *result;
1240 int c, size1, size2;
Georg Brandl48310cd2009-01-03 21:18:54 +00001241
Georg Brandl890a49a2009-03-31 18:56:38 +00001242 /* code to make sure that both arguments are of type
1243 newdatatype omitted */
Georg Brandl48310cd2009-01-03 21:18:54 +00001244
Georg Brandl890a49a2009-03-31 18:56:38 +00001245 size1 = obj1->obj_UnderlyingDatatypePtr->size;
1246 size2 = obj2->obj_UnderlyingDatatypePtr->size;
1247
1248 switch (op) {
1249 case Py_LT: c = size1 < size2; break;
1250 case Py_LE: c = size1 <= size2; break;
1251 case Py_EQ: c = size1 == size2; break;
1252 case Py_NE: c = size1 != size2; break;
1253 case Py_GT: c = size1 > size2; break;
1254 case Py_GE: c = size1 >= size2; break;
1255 }
1256 result = c ? Py_True : Py_False;
1257 Py_INCREF(result);
1258 return result;
1259 }
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261
1262Abstract Protocol Support
1263-------------------------
1264
1265Python supports a variety of *abstract* 'protocols;' the specific interfaces
1266provided to use these interfaces are documented in :ref:`abstract`.
1267
1268
1269A number of these abstract interfaces were defined early in the development of
1270the Python implementation. In particular, the number, mapping, and sequence
1271protocols have been part of Python since the beginning. Other protocols have
1272been added over time. For protocols which depend on several handler routines
1273from the type implementation, the older protocols have been defined as optional
1274blocks of handlers referenced by the type object. For newer protocols there are
1275additional slots in the main type object, with a flag bit being set to indicate
1276that the slots are present and should be checked by the interpreter. (The flag
1277bit does not indicate that the slot values are non-*NULL*. The flag may be set
1278to indicate the presence of a slot, but a slot may still be unfilled.) ::
1279
Jesus Cea33b57692012-09-28 16:34:45 +02001280 PyNumberMethods *tp_as_number;
1281 PySequenceMethods *tp_as_sequence;
1282 PyMappingMethods *tp_as_mapping;
Georg Brandl116aa622007-08-15 14:28:22 +00001283
1284If you wish your object to be able to act like a number, a sequence, or a
1285mapping object, then you place the address of a structure that implements the C
Georg Brandl60203b42010-10-06 10:11:56 +00001286type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or
1287:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this
Georg Brandl116aa622007-08-15 14:28:22 +00001288structure with appropriate values. You can find examples of the use of each of
1289these in the :file:`Objects` directory of the Python source distribution. ::
1290
1291 hashfunc tp_hash;
1292
1293This function, if you choose to provide it, should return a hash number for an
1294instance of your data type. Here is a moderately pointless example::
1295
1296 static long
1297 newdatatype_hash(newdatatypeobject *obj)
1298 {
1299 long result;
1300 result = obj->obj_UnderlyingDatatypePtr->size;
1301 result = result * 3;
1302 return result;
1303 }
1304
1305::
1306
1307 ternaryfunc tp_call;
1308
1309This function is called when an instance of your data type is "called", for
1310example, if ``obj1`` is an instance of your data type and the Python script
1311contains ``obj1('hello')``, the :attr:`tp_call` handler is invoked.
1312
1313This function takes three arguments:
1314
1315#. *arg1* is the instance of the data type which is the subject of the call. If
1316 the call is ``obj1('hello')``, then *arg1* is ``obj1``.
1317
1318#. *arg2* is a tuple containing the arguments to the call. You can use
Georg Brandl60203b42010-10-06 10:11:56 +00001319 :c:func:`PyArg_ParseTuple` to extract the arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001320
1321#. *arg3* is a dictionary of keyword arguments that were passed. If this is
1322 non-*NULL* and you support keyword arguments, use
Georg Brandl60203b42010-10-06 10:11:56 +00001323 :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not
Georg Brandl116aa622007-08-15 14:28:22 +00001324 want to support keyword arguments and this is non-*NULL*, raise a
1325 :exc:`TypeError` with a message saying that keyword arguments are not supported.
1326
1327Here is a desultory example of the implementation of the call function. ::
1328
1329 /* Implement the call function.
1330 * obj1 is the instance receiving the call.
1331 * obj2 is a tuple containing the arguments to the call, in this
1332 * case 3 strings.
1333 */
1334 static PyObject *
1335 newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
1336 {
1337 PyObject *result;
1338 char *arg1;
1339 char *arg2;
1340 char *arg3;
1341
1342 if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
1343 return NULL;
1344 }
1345 result = PyString_FromFormat(
1346 "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",
1347 obj->obj_UnderlyingDatatypePtr->size,
1348 arg1, arg2, arg3);
1349 printf("\%s", PyString_AS_STRING(result));
1350 return result;
1351 }
1352
Eli Bendersky49ac6f42012-02-27 19:18:35 +02001353::
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Georg Brandl116aa622007-08-15 14:28:22 +00001355 /* Iterators */
1356 getiterfunc tp_iter;
1357 iternextfunc tp_iternext;
1358
1359These functions provide support for the iterator protocol. Any object which
1360wishes to support iteration over its contents (which may be generated during
1361iteration) must implement the ``tp_iter`` handler. Objects which are returned
1362by a ``tp_iter`` handler must implement both the ``tp_iter`` and ``tp_iternext``
1363handlers. Both handlers take exactly one parameter, the instance for which they
1364are being called, and return a new reference. In the case of an error, they
1365should set an exception and return *NULL*.
1366
1367For an object which represents an iterable collection, the ``tp_iter`` handler
1368must return an iterator object. The iterator object is responsible for
1369maintaining the state of the iteration. For collections which can support
1370multiple iterators which do not interfere with each other (as lists and tuples
1371do), a new iterator should be created and returned. Objects which can only be
1372iterated over once (usually due to side effects of iteration) should implement
1373this handler by returning a new reference to themselves, and should also
1374implement the ``tp_iternext`` handler. File objects are an example of such an
1375iterator.
1376
1377Iterator objects should implement both handlers. The ``tp_iter`` handler should
1378return a new reference to the iterator (this is the same as the ``tp_iter``
1379handler for objects which can only be iterated over destructively). The
1380``tp_iternext`` handler should return a new reference to the next object in the
1381iteration if there is one. If the iteration has reached the end, it may return
1382*NULL* without setting an exception or it may set :exc:`StopIteration`; avoiding
1383the exception can yield slightly better performance. If an actual error occurs,
1384it should set an exception and return *NULL*.
1385
1386
1387.. _weakref-support:
1388
1389Weak Reference Support
1390----------------------
1391
1392One of the goals of Python's weak-reference implementation is to allow any type
1393to participate in the weak reference mechanism without incurring the overhead on
1394those objects which do not benefit by weak referencing (such as numbers).
1395
1396For an object to be weakly referencable, the extension must include a
Georg Brandl60203b42010-10-06 10:11:56 +00001397:c:type:`PyObject\*` field in the instance structure for the use of the weak
Georg Brandl116aa622007-08-15 14:28:22 +00001398reference mechanism; it must be initialized to *NULL* by the object's
1399constructor. It must also set the :attr:`tp_weaklistoffset` field of the
1400corresponding type object to the offset of the field. For example, the instance
1401type is defined with the following structure::
1402
1403 typedef struct {
1404 PyObject_HEAD
1405 PyClassObject *in_class; /* The class object */
1406 PyObject *in_dict; /* A dictionary */
1407 PyObject *in_weakreflist; /* List of weak references */
1408 } PyInstanceObject;
1409
1410The statically-declared type object for instances is defined this way::
1411
1412 PyTypeObject PyInstance_Type = {
Georg Brandlec12e822009-02-27 17:11:23 +00001413 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Georg Brandl116aa622007-08-15 14:28:22 +00001414 0,
1415 "module.instance",
1416
1417 /* Lots of stuff omitted for brevity... */
1418
1419 Py_TPFLAGS_DEFAULT, /* tp_flags */
1420 0, /* tp_doc */
1421 0, /* tp_traverse */
1422 0, /* tp_clear */
1423 0, /* tp_richcompare */
1424 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
1425 };
1426
1427The type constructor is responsible for initializing the weak reference list to
1428*NULL*::
1429
1430 static PyObject *
1431 instance_new() {
1432 /* Other initialization stuff omitted for brevity */
1433
1434 self->in_weakreflist = NULL;
1435
1436 return (PyObject *) self;
1437 }
1438
1439The only further addition is that the destructor needs to call the weak
Antoine Pitrou13775222012-06-15 19:11:31 +02001440reference manager to clear any weak references. This is only required if the
1441weak reference list is non-*NULL*::
Georg Brandl116aa622007-08-15 14:28:22 +00001442
1443 static void
1444 instance_dealloc(PyInstanceObject *inst)
1445 {
1446 /* Allocate temporaries if needed, but do not begin
1447 destruction just yet.
1448 */
1449
1450 if (inst->in_weakreflist != NULL)
1451 PyObject_ClearWeakRefs((PyObject *) inst);
1452
1453 /* Proceed with object destruction normally. */
1454 }
1455
1456
1457More Suggestions
1458----------------
1459
1460Remember that you can omit most of these functions, in which case you provide
1461``0`` as a value. There are type definitions for each of the functions you must
1462provide. They are in :file:`object.h` in the Python include directory that
1463comes with the source distribution of Python.
1464
1465In order to learn how to implement any specific method for your new data type,
Mark Dickinson9f989262009-02-02 21:29:40 +00001466do the following: Download and unpack the Python source distribution. Go to
1467the :file:`Objects` directory, then search the C source files for ``tp_`` plus
1468the function you want (for example, ``tp_richcompare``). You will find examples
1469of the function you want to implement.
Georg Brandl116aa622007-08-15 14:28:22 +00001470
1471When you need to verify that an object is an instance of the type you are
Georg Brandl60203b42010-10-06 10:11:56 +00001472implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of its use
Georg Brandl116aa622007-08-15 14:28:22 +00001473might be something like the following::
1474
1475 if (! PyObject_TypeCheck(some_object, &MyType)) {
1476 PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
1477 return NULL;
1478 }
1479
1480.. rubric:: Footnotes
1481
1482.. [#] This is true when we know that the object is a basic type, like a string or a
1483 float.
1484
1485.. [#] We relied on this in the :attr:`tp_dealloc` handler in this example, because our
1486 type doesn't support garbage collection. Even if a type supports garbage
1487 collection, there are calls that can be made to "untrack" the object from
1488 garbage collection, however, these calls are advanced and not covered here.
1489
1490.. [#] We now know that the first and last members are strings, so perhaps we could be
1491 less careful about decrementing their reference counts, however, we accept
1492 instances of string subclasses. Even though deallocating normal strings won't
1493 call back into our objects, we can't guarantee that deallocating an instance of
Christian Heimesf75b2902008-03-16 17:29:44 +00001494 a string subclass won't call back into our objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001495
1496.. [#] Even in the third version, we aren't guaranteed to avoid cycles. Instances of
1497 string subclasses are allowed and string subclasses could allow cycles even if
1498 normal strings don't.
1499