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