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
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
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
36 So, if you want to define a new object type, you need to create a new
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:
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:
76 Moving on, we come to the crunch --- the type object.
79 static PyTypeObject noddy_NoddyType =
{
80 PyObject_HEAD_INIT(NULL)
82 "noddy.Noddy", /*tp_name*/
83 sizeof(noddy_NoddyObject), /*tp_basicsize*/
100 Py_TPFLAGS_DEFAULT, /*tp_flags*/
101 "Noddy objects", /* tp_doc */
104 0, /* tp_richcompare */
105 0, /* tp_weaklistoffset */
113 0, /* tp_descr_get */
114 0, /* tp_descr_set */
115 0, /* tp_dictoffset */
118 PyType_GenericNew, /* tp_new */
122 Now if you go and look up the definition of
\ctype{PyTypeObject
} in
123 \file{object.h
} you'll see that it has many more fields that the
124 definition above. The remaining fields will be filled with zeros by
125 the C compiler, and it's common practice to not specify them
126 explicitly unless you need them.
128 This is so important that we're going to pick the top of it apart still
132 PyObject_HEAD_INIT(NULL)
135 This line is a bit of a wart; what we'd like to write is:
138 PyObject_HEAD_INIT(&PyType_Type)
141 as the type of a type object is ``type'', but this isn't strictly
142 conforming C and some compilers complain. Fortunately, this member
143 will be filled in for us by
\cfunction{PyType_Ready()
}.
149 The
\member{ob_size
} field of the header is not used; its presence in
150 the type structure is a historical artifact that is maintained for
151 binary compatibility with extension modules compiled for older
152 versions of Python. Always set this field to zero.
155 "noddy.Noddy", /* tp_name */
158 The name of our type. This will appear in the default textual
159 representation of our objects and in some error messages, for example:
162 >>> "" + noddy.new_noddy()
163 Traceback (most recent call last):
164 File "<stdin>", line
1, in ?
165 TypeError: cannot add type "noddy.Noddy" to string
168 Note that the name is a dotted name that includes both the module name
169 and the name of the type within the module. The module in this case is
170 \module{noddy
} and the type is
\class{Noddy
}, so we set the type name
171 to
\class{noddy.Noddy
}.
174 sizeof(noddy_NoddyObject), /* tp_basicsize */
177 This is so that Python knows how much memory to allocate when you call
178 \cfunction{PyObject_New
}.
184 This has to do with variable length objects like lists and strings.
187 Skipping a number of type methods that we don't provide, we set the
188 class flags to
\constant{Py_TPFLAGS_DEFAULT
}.
191 Py_TPFLAGS_DEFAULT, /*tp_flags*/
194 All types should include this constant in their flags. It enables all
195 of the members defined by the current version of Python.
197 We provide a doc string for the type in
\member{tp_doc
}.
200 "Noddy objects", /* tp_doc */
203 Now we get into the type methods, the things that make your objects
204 different from the others. We aren't going to implement any of these
205 in this version of the module. We'll expand this example later to
206 have more interesting behavior.
208 For now, all we want to be able to do is to create new
\class{Noddy
}
209 objects. To enable object creation, we have to provide a
210 \member{tp_new
} implementation. In this case, we can just use the
211 default implementation provided by the API function
212 \cfunction{PyType_GenericNew
}.
215 PyType_GenericNew, /* tp_new */
218 All the other type methods are
\NULL, so we'll go over them later
219 --- that's for a later section!
221 Everything else in the file should be familiar, except for some code
222 in
\cfunction{initnoddy
}:
225 if (PyType_Ready(&noddy_NoddyType) <
0)
229 This initializes the
\class{Noddy
} type, filing in a number of
230 members, including
\member{ob_type
} that we initially set to
\NULL.
233 PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
236 This adds the type to the module dictionary. This allows us to create
237 \class{Noddy
} instances by calling the
\class{Noddy
} class:
241 mynoddy = noddy.Noddy()
244 That's it! All that remains is to build it; put the above code in a
245 file called
\file{noddy.c
} and
248 from distutils.core import setup, Extension
249 setup(name="noddy", version="
1.0",
250 ext_modules=
[Extension("noddy",
["noddy.c"
])
])
253 in a file called
\file{setup.py
}; then typing
256 $ python setup.py build
257 \end{verbatim
} %$ <-- bow to font-lock ;-(
259 at a shell should produce a file
\file{noddy.so
} in a subdirectory;
260 move to that directory and fire up Python --- you should be able to
261 \code{import noddy
} and play around with Noddy objects.
263 That wasn't so hard, was it?
265 Of course, the current Noddy type is pretty uninteresting. It has no
266 data and doesn't do anything. It can't even be subclassed.
268 \subsection{Adding data and methods to the Basic example
}
270 Let's expend the basic example to add some data and methods. Let's
271 also make the type usable as a base class. We'll create
272 a new module,
\module{noddy2
} that adds these capabilities:
274 \verbatiminput{noddy2.c
}
276 This version of the module has a number of changes.
278 We've added an extra include:
281 #include "structmember.h"
284 This include provides declarations that we use to handle attributes,
285 as described a bit later.
287 The name of the
\class{Noddy
} object structure has been shortened to
288 \class{Noddy
}. The type object name has been shortened to
291 The
\class{Noddy
} type now has three data attributes,
\var{first
},
292 \var{last
}, and
\var{number
}. The
\var{first
} and
\var{last
}
293 variables are Python strings containing first and last names. The
294 \var{number
} attribute is an integer.
296 The object structure is updated accordingly:
307 Because we now have data to manage, we have to be more careful about
308 object allocation and deallocation. At a minimum, we need a
313 Noddy_dealloc(Noddy* self)
315 Py_XDECREF(self->first);
316 Py_XDECREF(self->last);
317 self->ob_type->tp_free((PyObject*)self);
321 which is assigned to the
\member{tp_dealloc
} member:
324 (destructor)Noddy_dealloc, /*tp_dealloc*/
327 This method decrements the reference counts of the two Python
328 attributes. We use
\cfunction{Py_XDECREF
} here because the
329 \member{first
} and
\member{last
} members could be
\NULL. It then
330 calls the
\member{tp_free
} member of the object's type to free the
331 object's memory. Note that the object's type might not be
332 \class{NoddyType
}, because the object may be an instance of a
335 We want to make sure that the first and last names are initialized to
336 empty strings, so we provide a new method:
340 Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
344 self = (Noddy *)type->tp_alloc(type,
0);
346 self->first = PyString_FromString("");
347 if (self->first == NULL)
353 self->last = PyString_FromString("");
354 if (self->last == NULL)
363 return (PyObject *)self;
367 and install it in the
\member{tp_new
} member:
370 Noddy_new, /* tp_new */
373 The new member is responsible for creating (as opposed to
374 initializing) objects of the type. It is exposed in Python as the
375 \method{__new__
} method. See the paper titled ``Unifying types and
376 classes in Python'' for a detailed discussion of the
\method{__new__
}
377 method. One reason to implement a new method is to assure the initial
378 values of instance variables. In this case, we use the new method to
379 make sure that the initial values of the members
\member{first
} and
380 \member{last
} are not
\NULL. If we didn't care whether the initial
381 values were
\NULL, we could have used
\cfunction{PyType_GenericNew
} as
382 our new method, as we did before.
\cfunction{PyType_GenericNew
}
383 initializes all of the instance variable members to NULLs.
385 The new method is a static method that is passed the type being
386 instantiated and any arguments passed when the type was called,
387 and that returns the new object created. New methods always accept
388 positional and keyword arguments, but they often ignore the arguments,
389 leaving the argument handling to initializer methods. Note that if the
390 type supports subclassing, the type passed may not be the type being
391 defined. The new method calls the tp_alloc slot to allocate memory.
392 We don't fill the
\member{tp_alloc
} slot ourselves. Rather
393 \cfunction{PyType_Ready()
} fills it for us by inheriting it from our
394 base class, which is
\class{object
} by default. Most types use the
397 We provide an initialization function:
401 Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
403 PyObject *first=NULL, *last=NULL;
405 static char *kwlist
[] =
{"first", "last", "number", NULL
};
407 if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
413 Py_XDECREF(self->first);
419 Py_XDECREF(self->last);
429 by filling the
\member{tp_init
} slot.
432 (initproc)Noddy_init, /* tp_init */
435 The
\member{tp_init
} slot is exposed in Python as the
436 \method{__init__
} method. It is used to initialize an object after
437 it's created. Unlike the new method, we can't guarantee that the
438 initializer is called. The initializer isn't called when unpickling
439 objects and it can be overridden. Our initializer accepts arguments
440 to provide initial values for our instance. Initializers always accept
441 positional and keyword arguments.
443 We want to want to expose our instance variables as attributes. There
444 are a number of ways to do that. The simplest way is to define member
448 static PyMemberDef Noddy_members
[] =
{
449 {"first", T_OBJECT_EX, offsetof(Noddy, first),
0,
451 {"last", T_OBJECT_EX, offsetof(Noddy, last),
0,
453 {"number", T_INT, offsetof(Noddy, number),
0,
455 {NULL
} /* Sentinel */
459 and put the definitions in the
\member{tp_members
} slot:
462 Noddy_members, /* tp_members */
465 Each member definition has a member name, type, offset, access flags
466 and documentation string. See the ``Generic Attribute Management''
467 section below for details.
469 A disadvantage of this approach is that it doesn't provide a way to
470 restrict the types of objects that can be assigned to the Python
471 attributes. We expect the first and last names to be strings, but any
472 Python objects can be assigned. Further, the attributes can be
473 deleted, setting the C pointers to
\NULL. Even though we can make
474 sure the members are initialized to non-
\NULL values, the members can
475 be set to
\NULL if the attributes are deleted.
477 We define a single method,
\method{name
}, that outputs the objects
478 name as the concatenation of the first and last names.
482 Noddy_name(Noddy* self)
484 static PyObject *format = NULL;
485 PyObject *args, *result;
487 if (format == NULL)
{
488 format = PyString_FromString("
%s %s");
493 if (self->first == NULL)
{
494 PyErr_SetString(PyExc_AttributeError, "first");
498 if (self->last == NULL)
{
499 PyErr_SetString(PyExc_AttributeError, "last");
503 args = Py_BuildValue("OO", self->first, self->last);
507 result = PyString_Format(format, args);
514 The method is implemented as a C function that takes a
\class{Noddy
} (or
515 \class{Noddy
} subclass) instance as the first argument. Methods
516 always take an instance as the first argument. Methods often take
517 positional and keyword arguments as well, but in this cased we don't
518 take any and don't need to accept a positional argument tuple or
519 keyword argument dictionary. This method is equivalent to the Python
524 return "
%s %s" % (self.first, self.last)
527 Note that we have to check for the possibility that our
\member{first
}
528 and
\member{last
} members are
\NULL. This is because they can be
529 deleted, in which case they are set to
\NULL. It would be better to
530 prevent deletion of these attributes and to restrict the attribute
531 values to be strings. We'll see how to do that in the next section.
533 Now that we've defined the method, we need to create an array of
537 static PyMethodDef Noddy_methods
[] =
{
538 {"name", (PyCFunction)Noddy_name, METH_NOARGS,
539 "Return the name, combining the first and last name"
541 {NULL
} /* Sentinel */
545 and assign them to the
\member{tp_methods
} slot:
548 Noddy_methods, /* tp_methods */
551 Note that used the
\constant{METH_NOARGS
} flag to indicate that the
552 method is passed no arguments.
554 Finally, we'll make our type usable as a base class. We've written
555 our methods carefully so far so that they don't make any assumptions
556 about the type of the object being created or used, so all we need to
557 do is to add the
\constant{Py_TPFLAGS_BASETYPE
} to our class flag
561 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
564 We rename
\cfunction{initnoddy
} to
\cfunction{initnoddy2
}
565 and update the module name passed to
\cfunction{Py_InitModule3
}.
567 Finally, we update our
\file{setup.py
} file to build the new module:
570 from distutils.core import setup, Extension
571 setup(name="noddy", version="
1.0",
573 Extension("noddy",
["noddy.c"
]),
574 Extension("noddy2",
["noddy2.c"
]),
578 \subsection{Providing finer control over data attributes
}
580 In this section, we'll provide finer control over how the
581 \member{first
} and
\member{last
} attributes are set in the
582 \class{Noddy
} example. In the previous version of our module, the
583 instance variables
\member{first
} and
\member{last
} could be set to
584 non-string values or even deleted. We want to make sure that these
585 attributes always contain strings.
587 \verbatiminput{noddy3.c
}
589 To provide greater control, over the
\member{first
} and
\member{last
}
590 attributes, we'll use custom getter and setter functions. Here are
591 the functions for getting and setting the
\member{first
} attribute:
594 Noddy_getfirst(Noddy *self, void *closure)
596 Py_INCREF(self->first);
601 Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
604 PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
608 if (! PyString_Check(value))
{
609 PyErr_SetString(PyExc_TypeError,
610 "The first attribute value must be a string");
614 Py_DECREF(self->first);
622 The getter function is passed a
\class{Noddy
} object and a
623 ``closure'', which is void pointer. In this case, the closure is
624 ignored. (The closure supports an advanced usage in which definition
625 data is passed to the getter and setter. This could, for example, be
626 used to allow a single set of getter and setter functions that decide
627 the attribute to get or set based on data in the closure.)
629 The setter function is passed the
\class{Noddy
} object, the new value,
630 and the closure. The new value may be
\NULL, in which case the
631 attribute is being deleted. In our setter, we raise an error if the
632 attribute is deleted or if the attribute value is not a string.
634 We create an array of
\ctype{PyGetSetDef
} structures:
637 static PyGetSetDef Noddy_getseters
[] =
{
639 (getter)Noddy_getfirst, (setter)Noddy_setfirst,
643 (getter)Noddy_getlast, (setter)Noddy_setlast,
646 {NULL
} /* Sentinel */
650 and register it in the
\member{tp_getset
} slot:
653 Noddy_getseters, /* tp_getset */
656 to register out attribute getters and setters.
658 The last item in a
\ctype{PyGetSetDef
} structure is the closure
659 mentioned above. In this case, we aren't using the closure, so we just
662 We also remove the member definitions for these attributes:
665 static PyMemberDef Noddy_members
[] =
{
666 {"number", T_INT, offsetof(Noddy, number),
0,
668 {NULL
} /* Sentinel */
672 With these changes, we can assure that the
\member{first
} and
673 \member{last
} members are never NULL so we can remove checks for
\NULL
674 values in almost all cases. This means that most of the
675 \cfunction{Py_XDECREF
} calls can be converted to
\cfunction{Py_DECREF
}
676 calls. The only place we can't change these calls is in the
677 deallocator, where there is the possibility that the initialization of
678 these members failed in the constructor.
680 We also rename the module initialization function and module name in
681 the initialization function, as we did before, and we add an extra
682 definition to the
\file{setup.py
} file.
684 \section{Type Methods
685 \label{dnt-type-methods
}}
687 This section aims to give a quick fly-by on the various type methods
688 you can implement and what they do.
690 Here is the definition of
\ctype{PyTypeObject
}, with some fields only
691 used in debug builds omitted:
693 \verbatiminput{typestruct.h
}
695 Now that's a
\emph{lot
} of methods. Don't worry too much though - if
696 you have a type you want to define, the chances are very good that you
697 will only implement a handful of these.
699 As you probably expect by now, we're going to go over this and give
700 more information about the various handlers. We won't go in the order
701 they are defined in the structure, because there is a lot of
702 historical baggage that impacts the ordering of the fields; be sure
703 your type initializaion keeps the fields in the right order! It's
704 often easiest to find an example that includes all the fields you need
705 (even if they're initialized to
\code{0}) and then change the values
706 to suit your new type.
709 char *tp_name; /* For printing */
712 The name of the type - as mentioned in the last section, this will
713 appear in various places, almost entirely for diagnostic purposes.
714 Try to choose something that will be helpful in such a situation!
717 int tp_basicsize, tp_itemsize; /* For allocation */
720 These fields tell the runtime how much memory to allocate when new
721 objects of this type are created. Python has some builtin support
722 for variable length structures (think: strings, lists) which is where
723 the
\member{tp_itemsize
} field comes in. This will be dealt with
730 Here you can put a string (or its address) that you want returned when
731 the Python script references
\code{obj.__doc__
} to retrieve the
734 Now we come to the basic type methods---the ones most extension types
738 \subsection{Finalization and De-allocation
}
740 \index{object!deallocation
}
741 \index{deallocation, object
}
742 \index{object!finalization
}
743 \index{finalization, of objects
}
746 destructor tp_dealloc;
749 This function is called when the reference count of the instance of
750 your type is reduced to zero and the Python interpreter wants to
751 reclaim it. If your type has memory to free or other clean-up to
752 perform, put it here. The object itself needs to be freed here as
753 well. Here is an example of this function:
757 newdatatype_dealloc(newdatatypeobject * obj)
759 free(obj->obj_UnderlyingDatatypePtr);
760 obj->ob_type->tp_free(obj);
764 One important requirement of the deallocator function is that it
765 leaves any pending exceptions alone. This is important since
766 deallocators are frequently called as the interpreter unwinds the
767 Python stack; when the stack is unwound due to an exception (rather
768 than normal returns), nothing is done to protect the deallocators from
769 seeing that an exception has already been set. Any actions which a
770 deallocator performs which may cause additional Python code to be
771 executed may detect that an exception has been set. This can lead to
772 misleading errors from the interpreter. The proper way to protect
773 against this is to save a pending exception before performing the
774 unsafe action, and restoring it when done. This can be done using the
775 \cfunction{PyErr_Fetch()
}\ttindex{PyErr_Fetch()
} and
776 \cfunction{PyErr_Restore()
}\ttindex{PyErr_Restore()
} functions:
780 my_dealloc(PyObject *obj)
782 MyObject *self = (MyObject *) obj;
785 if (self->my_callback != NULL)
{
786 PyObject *err_type, *err_value, *err_traceback;
787 int have_error = PyErr_Occurred() ?
1 :
0;
790 PyErr_Fetch(&err_type, &err_value, &err_traceback);
792 cbresult = PyObject_CallObject(self->my_callback, NULL);
793 if (cbresult == NULL)
794 PyErr_WriteUnraisable();
799 PyErr_Restore(err_type, err_value, err_traceback);
801 Py_DECREF(self->my_callback);
803 obj->ob_type->tp_free((PyObject*)self);
808 \subsection{Object Presentation
}
810 In Python, there are three ways to generate a textual representation
811 of an object: the
\function{repr()
}\bifuncindex{repr
} function (or
812 equivalent backtick syntax), the
\function{str()
}\bifuncindex{str
}
813 function, and the
\keyword{print
} statement. For most objects, the
814 \keyword{print
} statement is equivalent to the
\function{str()
}
815 function, but it is possible to special-case printing to a
816 \ctype{FILE*
} if necessary; this should only be done if efficiency is
817 identified as a problem and profiling suggests that creating a
818 temporary string object to be written to a file is too expensive.
820 These handlers are all optional, and most types at most need to
821 implement the
\member{tp_str
} and
\member{tp_repr
} handlers.
829 The
\member{tp_repr
} handler should return a string object containing
830 a representation of the instance for which it is called. Here is a
835 newdatatype_repr(newdatatypeobject * obj)
837 return PyString_FromFormat("Repr-ified_newdatatype
{{size:\%d
}}",
838 obj->obj_UnderlyingDatatypePtr->size);
842 If no
\member{tp_repr
} handler is specified, the interpreter will
843 supply a representation that uses the type's
\member{tp_name
} and a
844 uniquely-identifying value for the object.
846 The
\member{tp_str
} handler is to
\function{str()
} what the
847 \member{tp_repr
} handler described above is to
\function{repr()
}; that
848 is, it is called when Python code calls
\function{str()
} on an
849 instance of your object. Its implementation is very similar to the
850 \member{tp_repr
} function, but the resulting string is intended for
851 human consumption. If
\member{tp_str
} is not specified, the
852 \member{tp_repr
} handler is used instead.
854 Here is a simple example:
858 newdatatype_str(newdatatypeobject * obj)
860 return PyString_FromFormat("Stringified_newdatatype
{{size:\%d
}}",
861 obj->obj_UnderlyingDatatypePtr->size);
865 The print function will be called whenever Python needs to "print" an
866 instance of the type. For example, if 'node' is an instance of type
867 TreeNode, then the print function is called when Python code calls:
873 There is a flags argument and one flag,
\constant{Py_PRINT_RAW
}, and
874 it suggests that you print without string quotes and possibly without
875 interpreting escape sequences.
877 The print function receives a file object as an argument. You will
878 likely want to write to that file object.
880 Here is a sampe print function:
884 newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
886 if (flags & Py_PRINT_RAW)
{
887 fprintf(fp, "<
{newdatatype object--size:
%d}>",
888 obj->obj_UnderlyingDatatypePtr->size);
891 fprintf(fp, "\"<
{newdatatype object--size:
%d}>\"",
892 obj->obj_UnderlyingDatatypePtr->size);
899 \subsection{Attribute Management
}
901 For every object which can support attributes, the corresponding type
902 must provide the functions that control how the attributes are
903 resolved. There needs to be a function which can retrieve attributes
904 (if any are defined), and another to set attributes (if setting
905 attributes is allowed). Removing an attribute is a special case, for
906 which the new value passed to the handler is
\NULL.
908 Python supports two pairs of attribute handlers; a type that supports
909 attributes only needs to implement the functions for one pair. The
910 difference is that one pair takes the name of the attribute as a
911 \ctype{char*
}, while the other accepts a
\ctype{PyObject*
}. Each type
912 can use whichever pair makes more sense for the implementation's
916 getattrfunc tp_getattr; /* char * version */
917 setattrfunc tp_setattr;
919 getattrofunc tp_getattrofunc; /* PyObject * version */
920 setattrofunc tp_setattrofunc;
923 If accessing attributes of an object is always a simple operation
924 (this will be explained shortly), there are generic implementations
925 which can be used to provide the
\ctype{PyObject*
} version of the
926 attribute management functions. The actual need for type-specific
927 attribute handlers almost completely disappeared starting with Python
928 2.2, though there are many examples which have not been updated to use
929 some of the new generic mechanism that is available.
932 \subsubsection{Generic Attribute Management
}
936 Most extension types only use
\emph{simple
} attributes. So, what
937 makes the attributes simple? There are only a couple of conditions
941 \item The name of the attributes must be known when
942 \cfunction{PyType_Ready()
} is called.
944 \item No special processing is needed to record that an attribute
945 was looked up or set, nor do actions need to be taken based
949 Note that this list does not place any restrictions on the values of
950 the attributes, when the values are computed, or how relevant data is
953 When
\cfunction{PyType_Ready()
} is called, it uses three tables
954 referenced by the type object to create
\emph{descriptors
} which are
955 placed in the dictionary of the type object. Each descriptor controls
956 access to one attribute of the instance object. Each of the tables is
957 optional; if all three are
\NULL, instances of the type will only have
958 attributes that are inherited from their base type, and should leave
959 the
\member{tp_getattro
} and
\member{tp_setattro
} fields
\NULL{} as
960 well, allowing the base type to handle attributes.
962 The tables are declared as three fields of the type object:
965 struct PyMethodDef *tp_methods;
966 struct PyMemberDef *tp_members;
967 struct PyGetSetDef *tp_getset;
970 If
\member{tp_methods
} is not
\NULL, it must refer to an array of
971 \ctype{PyMethodDef
} structures. Each entry in the table is an
972 instance of this structure:
975 typedef struct PyMethodDef
{
976 char *ml_name; /* method name */
977 PyCFunction ml_meth; /* implementation function */
978 int ml_flags; /* flags */
979 char *ml_doc; /* docstring */
983 One entry should be defined for each method provided by the type; no
984 entries are needed for methods inherited from a base type. One
985 additional entry is needed at the end; it is a sentinel that marks the
986 end of the array. The
\member{ml_name
} field of the sentinel must be
989 XXX Need to refer to some unified discussion of the structure fields,
990 shared with the next section.
992 The second table is used to define attributes which map directly to
993 data stored in the instance. A variety of primitive C types are
994 supported, and access may be read-only or read-write. The structures
995 in the table are defined as:
998 typedef struct PyMemberDef
{
1007 For each entry in the table, a descriptor will be constructed and
1008 added to the type which will be able to extract a value from the
1009 instance structure. The
\member{type
} field should contain one of the
1010 type codes defined in the
\file{structmember.h
} header; the value will
1011 be used to determine how to convert Python values to and from C
1012 values. The
\member{flags
} field is used to store flags which control
1013 how the attribute can be accessed.
1015 XXX Need to move some of this to a shared section!
1017 The following flag constants are defined in
\file{structmember.h
};
1018 they may be combined using bitwise-OR.
1020 \begin{tableii
}{l|l
}{constant
}{Constant
}{Meaning
}
1021 \lineii{READONLY
\ttindex{READONLY
}}
1023 \lineii{RO
\ttindex{RO
}}
1024 {Shorthand for
\constant{READONLY
}.
}
1025 \lineii{READ_RESTRICTED
\ttindex{READ_RESTRICTED
}}
1026 {Not readable in restricted mode.
}
1027 \lineii{WRITE_RESTRICTED
\ttindex{WRITE_RESTRICTED
}}
1028 {Not writable in restricted mode.
}
1029 \lineii{RESTRICTED
\ttindex{RESTRICTED
}}
1030 {Not readable or writable in restricted mode.
}
1033 An interesting advantage of using the
\member{tp_members
} table to
1034 build descriptors that are used at runtime is that any attribute
1035 defined this way can have an associated docstring simply by providing
1036 the text in the table. An application can use the introspection API
1037 to retrieve the descriptor from the class object, and get the
1038 docstring using its
\member{__doc__
} attribute.
1040 As with the
\member{tp_methods
} table, a sentinel entry with a
1041 \member{name
} value of
\NULL{} is required.
1044 % XXX Descriptors need to be explained in more detail somewhere, but
1047 % Descriptor objects have two handler functions which correspond to
1048 % the \member{tp_getattro} and \member{tp_setattro} handlers. The
1049 % \method{__get__()} handler is a function which is passed the
1050 % descriptor, instance, and type objects, and returns the value of the
1051 % attribute, or it returns \NULL{} and sets an exception. The
1052 % \method{__set__()} handler is passed the descriptor, instance, type,
1056 \subsubsection{Type-specific Attribute Management
}
1058 For simplicity, only the
\ctype{char*
} version will be demonstrated
1059 here; the type of the name parameter is the only difference between
1060 the
\ctype{char*
} and
\ctype{PyObject*
} flavors of the interface.
1061 This example effectively does the same thing as the generic example
1062 above, but does not use the generic support added in Python
2.2. The
1063 value in showing this is two-fold: it demonstrates how basic attribute
1064 management can be done in a way that is portable to older versions of
1065 Python, and explains how the handler functions are called, so that if
1066 you do need to extend their functionality, you'll understand what
1069 The
\member{tp_getattr
} handler is called when the object requires an
1070 attribute look-up. It is called in the same situations where the
1071 \method{__getattr__()
} method of a class would be called.
1073 A likely way to handle this is (
1) to implement a set of functions
1074 (such as
\cfunction{newdatatype_getSize()
} and
1075 \cfunction{newdatatype_setSize()
} in the example below), (
2) provide a
1076 method table listing these functions, and (
3) provide a getattr
1077 function that returns the result of a lookup in that table. The
1078 method table uses the same structure as the
\member{tp_methods
} field
1084 static PyMethodDef newdatatype_methods
[] =
{
1085 {"getSize", (PyCFunction)newdatatype_getSize, METH_VARARGS,
1086 "Return the current size."
},
1087 {"setSize", (PyCFunction)newdatatype_setSize, METH_VARARGS,
1089 {NULL, NULL,
0, NULL
} /* sentinel */
1093 newdatatype_getattr(newdatatypeobject *obj, char *name)
1095 return Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);
1099 The
\member{tp_setattr
} handler is called when the
1100 \method{__setattr__()
} or
\method{__delattr__()
} method of a class
1101 instance would be called. When an attribute should be deleted, the
1102 third parameter will be
\NULL. Here is an example that simply raises
1103 an exception; if this were really all you wanted, the
1104 \member{tp_setattr
} handler should be set to
\NULL.
1108 newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
1110 (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
1116 \subsection{Object Comparison
}
1122 The
\member{tp_compare
} handler is called when comparisons are needed
1123 and the object does not implement the specific rich comparison method
1124 which matches the requested comparison. (It is always used if defined
1125 and the
\cfunction{PyObject_Compare()
} or
\cfunction{PyObject_Cmp()
}
1126 functions are used, or if
\function{cmp()
} is used from Python.)
1127 It is analogous to the
\method{__cmp__()
} method. This function
1128 should return
\code{-
1} if
\var{obj1
} is less than
1129 \var{obj2
},
\code{0} if they are equal, and
\code{1} if
1130 \var{obj1
} is greater than
1132 (It was previously allowed to return arbitrary negative or positive
1133 integers for less than and greater than, respectively; as of Python
1134 2.2, this is no longer allowed. In the future, other return values
1135 may be assigned a different meaning.)
1137 A
\member{tp_compare
} handler may raise an exception. In this case it
1138 should return a negative value. The caller has to test for the
1139 exception using
\cfunction{PyErr_Occurred()
}.
1142 Here is a sample implementation:
1146 newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)
1150 if (obj1->obj_UnderlyingDatatypePtr->size <
1151 obj2->obj_UnderlyingDatatypePtr->size)
{
1154 else if (obj1->obj_UnderlyingDatatypePtr->size >
1155 obj2->obj_UnderlyingDatatypePtr->size)
{
1166 \subsection{Abstract Protocol Support
}
1168 Python supports a variety of
\emph{abstract
} `protocols;' the specific
1169 interfaces provided to use these interfaces are documented in the
1170 \citetitle[../api/api.html
]{Python/C API Reference Manual
} in the
1171 chapter ``
\ulink{Abstract Objects Layer
}{../api/abstract.html
}.''
1173 A number of these abstract interfaces were defined early in the
1174 development of the Python implementation. In particular, the number,
1175 mapping, and sequence protocols have been part of Python since the
1176 beginning. Other protocols have been added over time. For protocols
1177 which depend on several handler routines from the type implementation,
1178 the older protocols have been defined as optional blocks of handlers
1179 referenced by the type object. For newer protocols there are
1180 additional slots in the main type object, with a flag bit being set to
1181 indicate that the slots are present and should be checked by the
1182 interpreter. (The flag bit does not indicate that the slot values are
1183 non-
\NULL. The flag may be set to indicate the presense of a slot,
1184 but a slot may still be unfilled.)
1187 PyNumberMethods tp_as_number;
1188 PySequenceMethods tp_as_sequence;
1189 PyMappingMethods tp_as_mapping;
1192 If you wish your object to be able to act like a number, a sequence,
1193 or a mapping object, then you place the address of a structure that
1194 implements the C type
\ctype{PyNumberMethods
},
1195 \ctype{PySequenceMethods
}, or
\ctype{PyMappingMethods
}, respectively.
1196 It is up to you to fill in this structure with appropriate values. You
1197 can find examples of the use of each of these in the
\file{Objects
}
1198 directory of the Python source distribution.
1205 This function, if you choose to provide it, should return a hash
1206 number for an instance of your datatype. Here is a moderately
1211 newdatatype_hash(newdatatypeobject *obj)
1214 result = obj->obj_UnderlyingDatatypePtr->size;
1215 result = result *
3;
1221 ternaryfunc tp_call;
1224 This function is called when an instance of your datatype is "called",
1225 for example, if
\code{obj1
} is an instance of your datatype and the Python
1226 script contains
\code{obj1('hello')
}, the
\member{tp_call
} handler is
1229 This function takes three arguments:
1233 \var{arg1
} is the instance of the datatype which is the subject of
1234 the call. If the call is
\code{obj1('hello')
}, then
\var{arg1
} is
1238 \var{arg2
} is a tuple containing the arguments to the call. You
1239 can use
\cfunction{PyArg_ParseTuple()
} to extract the arguments.
1242 \var{arg3
} is a dictionary of keyword arguments that were passed.
1243 If this is non-
\NULL{} and you support keyword arguments, use
1244 \cfunction{PyArg_ParseTupleAndKeywords()
} to extract the
1245 arguments. If you do not want to support keyword arguments and
1246 this is non-
\NULL, raise a
\exception{TypeError
} with a message
1247 saying that keyword arguments are not supported.
1250 Here is a desultory example of the implementation of the call function.
1253 /* Implement the call function.
1254 * obj1 is the instance receiving the call.
1255 * obj2 is a tuple containing the arguments to the call, in this
1259 newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
1266 if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3))
{
1269 result = PyString_FromFormat(
1270 "Returning -- value:
[\%d
] arg1:
[\%s
] arg2:
[\%s
] arg3:
[\%s
]\n",
1271 obj->obj_UnderlyingDatatypePtr->size,
1273 printf("\%s", PyString_AS_STRING(result));
1278 XXX some fields need to be added here...
1282 /* Added in release
2.2 */
1284 getiterfunc tp_iter;
1285 iternextfunc tp_iternext;
1288 These functions provide support for the iterator protocol. Any object
1289 which wishes to support iteration over its contents (which may be
1290 generated during iteration) must implement the
\code{tp_iter
}
1291 handler. Objects which are returned by a
\code{tp_iter
} handler must
1292 implement both the
\code{tp_iter
} and
\code{tp_iternext
} handlers.
1293 Both handlers take exactly one parameter, the instance for which they
1294 are being called, and return a new reference. In the case of an
1295 error, they should set an exception and return
\NULL.
1297 For an object which represents an iterable collection, the
1298 \code{tp_iter
} handler must return an iterator object. The iterator
1299 object is responsible for maintaining the state of the iteration. For
1300 collections which can support multiple iterators which do not
1301 interfere with each other (as lists and tuples do), a new iterator
1302 should be created and returned. Objects which can only be iterated
1303 over once (usually due to side effects of iteration) should implement
1304 this handler by returning a new reference to themselves, and should
1305 also implement the
\code{tp_iternext
} handler. File objects are an
1306 example of such an iterator.
1308 Iterator objects should implement both handlers. The
\code{tp_iter
}
1309 handler should return a new reference to the iterator (this is the
1310 same as the
\code{tp_iter
} handler for objects which can only be
1311 iterated over destructively). The
\code{tp_iternext
} handler should
1312 return a new reference to the next object in the iteration if there is
1313 one. If the iteration has reached the end, it may return
\NULL{}
1314 without setting an exception or it may set
\exception{StopIteration
};
1315 avoiding the exception can yield slightly better performance. If an
1316 actual error occurs, it should set an exception and return
\NULL.
1319 \subsection{Supporting the Cycle Collector
1320 \label{example-cycle-support
}}
1322 This example shows only enough of the implementation of an extension
1323 type to show how the garbage collector support needs to be added. It
1324 shows the definition of the object structure, the
1325 \member{tp_traverse
},
\member{tp_clear
} and
\member{tp_dealloc
}
1326 implementations, the type structure, and a constructor --- the module
1327 initialization needed to export the constructor to Python is not shown
1328 as there are no special considerations there for the collector. To
1329 make this interesting, assume that the module exposes ways for the
1330 \member{container
} field of the object to be modified. Note that
1331 since no checks are made on the type of the object used to initialize
1332 \member{container
}, we have to assume that it may be a container.
1334 \verbatiminput{cycle-gc.c
}
1336 Full details on the APIs related to the cycle detector are in
1337 \ulink{Supporting Cyclic Garbarge
1338 Collection
}{../api/supporting-cycle-detection.html
} in the
1339 \citetitle[../api/api.html
]{Python/C API Reference Manual
}.
1342 \subsection{More Suggestions
}
1344 Remember that you can omit most of these functions, in which case you
1345 provide
\code{0} as a value. There are type definitions for each of
1346 the functions you must provide. They are in
\file{object.h
} in the
1347 Python include directory that comes with the source distribution of
1350 In order to learn how to implement any specific method for your new
1351 datatype, do the following: Download and unpack the Python source
1352 distribution. Go the the
\file{Objects
} directory, then search the
1353 C source files for
\code{tp_
} plus the function you want (for
1354 example,
\code{tp_print
} or
\code{tp_compare
}). You will find
1355 examples of the function you want to implement.
1357 When you need to verify that an object is an instance of the type
1358 you are implementing, use the
\cfunction{PyObject_TypeCheck
} function.
1359 A sample of its use might be something like the following:
1362 if (! PyObject_TypeCheck(some_object, &MyType))
{
1363 PyErr_SetString(PyExc_TypeError, "arg
#1 not a mything");