Updated for hfsplus module, new gusi libs.
[python/dscho.git] / Doc / ext / newtypes.tex
blob17e2b256e5a061c96c16725cb1853cd206ad02e9
1 \chapter{Defining New Types
2 \label{defining-new-types}}
3 \sectionauthor{Michael Hudson}{mwh21@cam.ac.uk}
4 \sectionauthor{Dave Kuhlman}{dkuhlman@rexx.com}
6 As mentioned in the last chapter, Python allows the writer of an
7 extension module to define new types that can be manipulated from
8 Python code, much like strings and lists in core Python.
10 This is not hard; the code for all extension types follows a pattern,
11 but there are some details that you need to understand before you can
12 get started.
14 \section{The Basics
15 \label{dnt-basics}}
17 The Python runtime sees all Python objects as variables of type
18 \ctype{PyObject*}. A \ctype{PyObject} is not a very magnificent
19 object - it just contains the refcount and a pointer to the object's
20 ``type object''. This is where the action is; the type object
21 determines which (C) functions get called when, for instance, an
22 attribute gets looked up on an object or it is multiplied by another
23 object. I call these C functions ``type methods'' to distinguish them
24 from things like \code{[].append} (which I will call ``object
25 methods'' when I get around to them).
27 So, if you want to define a new object type, you need to create a new
28 type object.
30 This sort of thing can only be explained by example, so here's a
31 minimal, but complete, module that defines a new type:
33 \begin{verbatim}
34 #include <Python.h>
36 staticforward PyTypeObject noddy_NoddyType;
38 typedef struct {
39 PyObject_HEAD
40 } noddy_NoddyObject;
42 static PyObject*
43 noddy_new_noddy(PyObject* self, PyObject* args)
45 noddy_NoddyObject* noddy;
47 if (!PyArg_ParseTuple(args,":new_noddy"))
48 return NULL;
50 noddy = PyObject_New(noddy_NoddyObject, &noddy_NoddyType);
52 return (PyObject*)noddy;
55 static void
56 noddy_noddy_dealloc(PyObject* self)
58 PyObject_Del(self);
61 static PyTypeObject noddy_NoddyType = {
62 PyObject_HEAD_INIT(NULL)
64 "Noddy",
65 sizeof(noddy_NoddyObject),
67 noddy_noddy_dealloc, /*tp_dealloc*/
68 0, /*tp_print*/
69 0, /*tp_getattr*/
70 0, /*tp_setattr*/
71 0, /*tp_compare*/
72 0, /*tp_repr*/
73 0, /*tp_as_number*/
74 0, /*tp_as_sequence*/
75 0, /*tp_as_mapping*/
76 0, /*tp_hash */
79 static PyMethodDef noddy_methods[] = {
80 {"new_noddy", noddy_new_noddy, METH_VARARGS,
81 "Create a new Noddy object."},
82 {NULL, NULL, 0, NULL}
85 DL_EXPORT(void)
86 initnoddy(void)
88 noddy_NoddyType.ob_type = &PyType_Type;
90 Py_InitModule("noddy", noddy_methods);
92 \end{verbatim}
94 Now that's quite a bit to take in at once, but hopefully bits will
95 seem familiar from the last chapter.
97 The first bit that will be new is:
99 \begin{verbatim}
100 staticforward PyTypeObject noddy_NoddyType;
101 \end{verbatim}
103 This names the type object that will be defining further down in the
104 file. It can't be defined here because its definition has to refer to
105 functions that have no yet been defined, but we need to be able to
106 refer to it, hence the declaration.
108 The \code{staticforward} is required to placate various brain dead
109 compilers.
111 \begin{verbatim}
112 typedef struct {
113 PyObject_HEAD
114 } noddy_NoddyObject;
115 \end{verbatim}
117 This is what a Noddy object will contain. In this case nothing more
118 than every Python object contains - a refcount and a pointer to a type
119 object. These are the fields the \code{PyObject_HEAD} macro brings
120 in. The reason for the macro is to standardize the layout and to
121 enable special debugging fields to be brought in debug builds.
123 For contrast
125 \begin{verbatim}
126 typedef struct {
127 PyObject_HEAD
128 long ob_ival;
129 } PyIntObject;
130 \end{verbatim}
132 is the corresponding definition for standard Python integers.
134 Next up is:
136 \begin{verbatim}
137 static PyObject*
138 noddy_new_noddy(PyObject* self, PyObject* args)
140 noddy_NoddyObject* noddy;
142 if (!PyArg_ParseTuple(args,":new_noddy"))
143 return NULL;
145 noddy = PyObject_New(noddy_NoddyObject, &noddy_NoddyType);
147 return (PyObject*)noddy;
149 \end{verbatim}
151 This is in fact just a regular module function, as described in the
152 last chapter. The reason it gets special mention is that this is
153 where we create our Noddy object. Defining PyTypeObject structures is
154 all very well, but if there's no way to actually \emph{create} one
155 of the wretched things it is not going to do anyone much good.
157 Almost always, you create objects with a call of the form:
159 \begin{verbatim}
160 PyObject_New(<type>, &<type object>);
161 \end{verbatim}
163 This allocates the memory and then initializes the object (sets
164 the reference count to one, makes the \cdata{ob_type} pointer point at
165 the right place and maybe some other stuff, depending on build options).
166 You \emph{can} do these steps separately if you have some reason to
167 --- but at this level we don't bother.
169 We cast the return value to a \ctype{PyObject*} because that's what
170 the Python runtime expects. This is safe because of guarantees about
171 the layout of structures in the C standard, and is a fairly common C
172 programming trick. One could declare \cfunction{noddy_new_noddy} to
173 return a \ctype{noddy_NoddyObject*} and then put a cast in the
174 definition of \cdata{noddy_methods} further down the file --- it
175 doesn't make much difference.
177 Now a Noddy object doesn't do very much and so doesn't need to
178 implement many type methods. One you can't avoid is handling
179 deallocation, so we find
181 \begin{verbatim}
182 static void
183 noddy_noddy_dealloc(PyObject* self)
185 PyObject_Del(self);
187 \end{verbatim}
189 This is so short as to be self explanatory. This function will be
190 called when the reference count on a Noddy object reaches \code{0} (or
191 it is found as part of an unreachable cycle by the cyclic garbage
192 collector). \cfunction{PyObject_Del()} is what you call when you want
193 an object to go away. If a Noddy object held references to other
194 Python objects, one would decref them here.
196 Moving on, we come to the crunch --- the type object.
198 \begin{verbatim}
199 static PyTypeObject noddy_NoddyType = {
200 PyObject_HEAD_INIT(NULL)
202 "Noddy",
203 sizeof(noddy_NoddyObject),
205 noddy_noddy_dealloc, /*tp_dealloc*/
206 0, /*tp_print*/
207 0, /*tp_getattr*/
208 0, /*tp_setattr*/
209 0, /*tp_compare*/
210 0, /*tp_repr*/
211 0, /*tp_as_number*/
212 0, /*tp_as_sequence*/
213 0, /*tp_as_mapping*/
214 0, /*tp_hash */
216 \end{verbatim}
218 Now if you go and look up the definition of \ctype{PyTypeObject} in
219 \file{object.h} you'll see that it has many, many more fields that the
220 definition above. The remaining fields will be filled with zeros by
221 the C compiler, and it's common practice to not specify them
222 explicitly unless you need them.
224 This is so important that I'm going to pick the top of it apart still
225 further:
227 \begin{verbatim}
228 PyObject_HEAD_INIT(NULL)
229 \end{verbatim}
231 This line is a bit of a wart; what we'd like to write is:
233 \begin{verbatim}
234 PyObject_HEAD_INIT(&PyType_Type)
235 \end{verbatim}
237 as the type of a type object is ``type'', but this isn't strictly
238 conforming C and some compilers complain. So instead we fill in the
239 \cdata{ob_type} field of \cdata{noddy_NoddyType} at the earliest
240 oppourtunity --- in \cfunction{initnoddy()}.
242 \begin{verbatim}
244 \end{verbatim}
246 XXX why does the type info struct start PyObject_*VAR*_HEAD??
248 \begin{verbatim}
249 "Noddy",
250 \end{verbatim}
252 The name of our type. This will appear in the default textual
253 representation of our objects and in some error messages, for example:
255 \begin{verbatim}
256 >>> "" + noddy.new_noddy()
257 Traceback (most recent call last):
258 File "<stdin>", line 1, in ?
259 TypeError: cannot add type "Noddy" to string
260 \end{verbatim}
262 \begin{verbatim}
263 sizeof(noddy_NoddyObject),
264 \end{verbatim}
266 This is so that Python knows how much memory to allocate when you call
267 \cfunction{PyObject_New}.
269 \begin{verbatim}
271 \end{verbatim}
273 This has to do with variable length objects like lists and strings.
274 Ignore for now...
276 Now we get into the type methods, the things that make your objects
277 different from the others. Of course, the Noddy object doesn't
278 implement many of these, but as mentioned above you have to implement
279 the deallocation function.
281 \begin{verbatim}
282 noddy_noddy_dealloc, /*tp_dealloc*/
283 \end{verbatim}
285 From here, all the type methods are nil so I won't go over them yet -
286 that's for the next section!
288 Everything else in the file should be familiar, except for this line
289 in \cfunction{initnoddy}:
291 \begin{verbatim}
292 noddy_NoddyType.ob_type = &PyType_Type;
293 \end{verbatim}
295 This was alluded to above --- the \cdata{noddy_NoddyType} object should
296 have type ``type'', but \code{\&PyType_Type} is not constant and so
297 can't be used in its initializer. To work around this, we patch it up
298 in the module initialization.
300 That's it! All that remains is to build it; put the above code in a
301 file called \file{noddymodule.c} and
303 \begin{verbatim}
304 from distutils.core import setup, Extension
305 setup(name = "noddy", version = "1.0",
306 ext_modules = [Extension("noddy", ["noddymodule.c"])])
307 \end{verbatim}
309 in a file called \file{setup.py}; then typing
311 \begin{verbatim}
312 $ python setup.py build%$
313 \end{verbatim}
315 at a shell should produce a file \file{noddy.so} in a subdirectory;
316 move to that directory and fire up Python --- you should be able to
317 \code{import noddy} and play around with Noddy objects.
319 That wasn't so hard, was it?
322 \section{Type Methods
323 \label{dnt-type-methods}}
325 This section aims to give a quick fly-by on the various type methods
326 you can implement and what they do.
328 Here is the definition of \ctype{PyTypeObject}, with some fields only
329 used in debug builds omitted:
331 \begin{verbatim}
332 typedef struct _typeobject {
333 PyObject_VAR_HEAD
334 char *tp_name; /* For printing */
335 int tp_basicsize, tp_itemsize; /* For allocation */
337 /* Methods to implement standard operations */
339 destructor tp_dealloc;
340 printfunc tp_print;
341 getattrfunc tp_getattr;
342 setattrfunc tp_setattr;
343 cmpfunc tp_compare;
344 reprfunc tp_repr;
346 /* Method suites for standard classes */
348 PyNumberMethods *tp_as_number;
349 PySequenceMethods *tp_as_sequence;
350 PyMappingMethods *tp_as_mapping;
352 /* More standard operations (here for binary compatibility) */
354 hashfunc tp_hash;
355 ternaryfunc tp_call;
356 reprfunc tp_str;
357 getattrofunc tp_getattro;
358 setattrofunc tp_setattro;
360 /* Functions to access object as input/output buffer */
361 PyBufferProcs *tp_as_buffer;
363 /* Flags to define presence of optional/expanded features */
364 long tp_flags;
366 char *tp_doc; /* Documentation string */
368 /* Assigned meaning in release 2.0 */
369 /* call function for all accessible objects */
370 traverseproc tp_traverse;
372 /* delete references to contained objects */
373 inquiry tp_clear;
375 /* Assigned meaning in release 2.1 */
376 /* rich comparisons */
377 richcmpfunc tp_richcompare;
379 /* weak reference enabler */
380 long tp_weaklistoffset;
382 /* Added in release 2.2 */
383 /* Iterators */
384 getiterfunc tp_iter;
385 iternextfunc tp_iternext;
387 /* Attribute descriptor and subclassing stuff */
388 struct PyMethodDef *tp_methods;
389 struct memberlist *tp_members;
390 struct getsetlist *tp_getset;
391 struct _typeobject *tp_base;
392 PyObject *tp_dict;
393 descrgetfunc tp_descr_get;
394 descrsetfunc tp_descr_set;
395 long tp_dictoffset;
396 initproc tp_init;
397 allocfunc tp_alloc;
398 newfunc tp_new;
399 destructor tp_free; /* Low-level free-memory routine */
400 PyObject *tp_bases;
401 PyObject *tp_mro; /* method resolution order */
402 PyObject *tp_defined;
404 } PyTypeObject;
405 \end{verbatim}
407 Now that's a \emph{lot} of methods. Don't worry too much though - if
408 you have a type you want to define, the chances are very good that you
409 will only implement a handful of these.
411 As you probably expect by now, we're going to go over this and give
412 more information about the various handlers. We won't go in the order
413 they are defined in the structure, because there is a lot of
414 historical baggage that impacts the ordering of the fields; be sure
415 your type initializaion keeps the fields in the right order! It's
416 often easiest to find an example that includes all the fields you need
417 (even if they're initialized to \code{0}) and then change the values
418 to suit your new type.
420 \begin{verbatim}
421 char *tp_name; /* For printing */
422 \end{verbatim}
424 The name of the type - as mentioned in the last section, this will
425 appear in various places, almost entirely for diagnostic purposes.
426 Try to choose something that will be helpful in such a situation!
428 \begin{verbatim}
429 int tp_basicsize, tp_itemsize; /* For allocation */
430 \end{verbatim}
432 These fields tell the runtime how much memory to allocate when new
433 objects of this typed are created. Python has some builtin support
434 for variable length structures (think: strings, lists) which is where
435 the \cdata{tp_itemsize} field comes in. This will be dealt with
436 later.
438 \begin{verbatim}
439 char *tp_doc;
440 \end{verbatim}
442 Here you can put a string (or its address) that you want returned when
443 the Python script references \code{obj.__doc__} to retrieve the
444 docstring.
446 Now we come to the basic type methods---the ones most extension types
447 will implement.
450 \subsection{Finalization and De-allocation}
452 \begin{verbatim}
453 destructor tp_dealloc;
454 \end{verbatim}
456 This function is called when the reference count of the instance of
457 your type is reduced to zero and the Python interpreter wants to
458 reclaim it. If your type has memory to free or other clean-up to
459 perform, put it here. The object itself needs to be freed here as
460 well. Here is an example of this function:
462 \begin{verbatim}
463 static void
464 newdatatype_dealloc(newdatatypeobject * obj)
466 free(obj->obj_UnderlyingDatatypePtr);
467 PyObject_DEL(obj);
469 \end{verbatim}
472 \subsection{Object Representation}
474 In Python, there are three ways to generate a textual representation
475 of an object: the \function{repr()}\bifuncindex{repr} function (or
476 equivalent backtick syntax), the \function{str()}\bifuncindex{str}
477 function, and the \keyword{print} statement. For most objects, the
478 \keyword{print} statement is equivalent to the \function{str()}
479 function, but it is possible to special-case printing to a
480 \ctype{FILE*} if necessary; this should only be done if efficiency is
481 identified as a problem and profiling suggests that creating a
482 temporary string object to be written to a file is too expensive.
484 These handlers are all optional, and most types at most need to
485 implement the \member{tp_str} and \member{tp_repr} handlers.
487 \begin{verbatim}
488 reprfunc tp_repr;
489 reprfunc tp_str;
490 printfunc tp_print;
491 \end{verbatim}
493 The \member{tp_repr} handler should return a string object containing
494 a representation of the instance for which it is called. Here is a
495 simple example:
497 \begin{verbatim}
498 static PyObject *
499 newdatatype_repr(newdatatypeobject * obj)
501 return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
502 obj->obj_UnderlyingDatatypePtr->size);
504 \end{verbatim}
506 If no \member{tp_repr} handler is specified, the interpreter will
507 supply a representation that uses the type's \member{tp_name} and a
508 uniquely-identifying value for the object.
510 The \member{tp_str} handler is to \function{str()} what the
511 \member{tp_repr} handler described above is to \function{repr()}; that
512 is, it is called when Python code calls \function{str()} on an
513 instance of your object. It's implementation is very similar to the
514 \member{tp_repr} function, but the resulting string is intended for
515 human consumption. It \member{tp_str} is not specified, the
516 \member{tp_repr} handler is used instead.
518 Here is a simple example:
520 \begin{verbatim}
521 static PyObject *
522 newdatatype_str(newdatatypeobject * obj)
524 return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
525 obj->obj_UnderlyingDatatypePtr->size
528 \end{verbatim}
530 The print function will be called whenever Python needs to "print" an
531 instance of the type. For example, if 'node' is an instance of type
532 TreeNode, then the print function is called when Python code calls:
534 \begin{verbatim}
535 print node
536 \end{verbatim}
538 There is a flags argument and one flag, \constant{Py_PRINT_RAW}, and
539 it suggests that you print without string quotes and possibly without
540 interpreting escape sequences.
542 The print function receives a file object as an argument. You will
543 likely want to write to that file object.
545 Here is a sampe print function:
547 \begin{verbatim}
548 static int
549 newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
551 if (flags & Py_PRINT_RAW) {
552 fprintf(fp, "<{newdatatype object--size: %d}>",
553 obj->obj_UnderlyingDatatypePtr->size);
555 else {
556 fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
557 obj->obj_UnderlyingDatatypePtr->size);
559 return 0;
561 \end{verbatim}
564 \subsection{Attribute Management Functions}
566 \begin{verbatim}
567 getattrfunc tp_getattr;
568 setattrfunc tp_setattr;
569 \end{verbatim}
571 The \member{tp_getattr} handle is called when the object requires an
572 attribute look-up. It is called in the same situations where the
573 \method{__getattr__()} method of a class would be called.
575 A likely way to handle this is (1) to implement a set of functions
576 (such as \cfunction{newdatatype_getSize()} and
577 \cfunction{newdatatype_setSize()} in the example below), (2) provide a
578 method table listing these functions, and (3) provide a getattr
579 function that returns the result of a lookup in that table.
581 Here is an example:
583 \begin{verbatim}
584 static PyMethodDef newdatatype_methods[] = {
585 {"getSize", (PyCFunction)newdatatype_getSize, METH_VARARGS,
586 "Return the current size."},
587 {"setSize", (PyCFunction)newdatatype_setSize, METH_VARARGS,
588 "Set the size."},
589 {NULL, NULL, 0, NULL} /* sentinel */
592 static PyObject *
593 newdatatype_getattr(newdatatypeobject *obj, char *name)
595 return Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);
597 \end{verbatim}
599 The \member{tp_setattr} handler is called when the
600 \method{__setattr__()} or \method{__delattr__()} method of a class
601 instance would be called. When an attribute should be deleted, the
602 third parameter will be \NULL. Here is an example that simply raises
603 an exception; if this were really all you wanted, the
604 \member{tp_setattr} handler should be set to \NULL.
606 \begin{verbatim}
607 static int
608 newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
610 (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
611 return -1;
613 \end{verbatim}
616 \subsection{Object Comparison}
618 \begin{verbatim}
619 cmpfunc tp_compare;
620 \end{verbatim}
622 The \member{tp_compare} handler is called when comparisons are needed
623 are the object does not implement the specific rich comparison method
624 which matches the requested comparison. (It is always used if defined
625 and the \cfunction{PyObject_Compare()} or \cfunction{PyObject_Cmp()}
626 functions are used, or if \function{cmp()} is used from Python.)
627 It is analogous to the \method{__cmp__()} method. This function
628 should return \code{-1} if \var{obj1} is less than
629 \var{obj2}, \code{0} if they are equal, and \code{1} if
630 \var{obj1} is greater than
631 \var{obj2}.
632 (It was previously allowed to return arbitrary negative or positive
633 integers for less than and greater than, respectively; as of Python
634 2.2, this is no longer allowed. In the future, other return values
635 may be assigned a different meaning.)
637 A \member{tp_compare} handler may raise an exception. In this case it
638 should return a negative value. The caller has to test for the
639 exception using \cfunction{PyErr_Occurred()}.
642 Here is a sample implementation:
644 \begin{verbatim}
645 static int
646 newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)
648 long result;
650 if (obj1->obj_UnderlyingDatatypePtr->size <
651 obj2->obj_UnderlyingDatatypePtr->size) {
652 result = -1;
654 else if (obj1->obj_UnderlyingDatatypePtr->size >
655 obj2->obj_UnderlyingDatatypePtr->size) {
656 result = 1;
658 else {
659 result = 0;
661 return result;
663 \end{verbatim}
666 \subsection{Abstract Protocol Support}
668 \begin{verbatim}
669 tp_as_number;
670 tp_as_sequence;
671 tp_as_mapping;
672 \end{verbatim}
674 If you wish your object to be able to act like a number, a sequence,
675 or a mapping object, then you place the address of a structure that
676 implements the C type \ctype{PyNumberMethods},
677 \ctype{PySequenceMethods}, or \ctype{PyMappingMethods}, respectively.
678 It is up to you to fill in this structure with appropriate values. You
679 can find examples of the use of each of these in the \file{Objects}
680 directory of the Python source distribution.
683 \begin{verbatim}
684 hashfunc tp_hash;
685 \end{verbatim}
687 This function, if you choose to provide it, should return a hash
688 number for an instance of your datatype. Here is a moderately
689 pointless example:
691 \begin{verbatim}
692 static long
693 newdatatype_hash(newdatatypeobject *obj)
695 long result;
696 result = obj->obj_UnderlyingDatatypePtr->size;
697 result = result * 3;
698 return result;
700 \end{verbatim}
702 \begin{verbatim}
703 ternaryfunc tp_call;
704 \end{verbatim}
706 This function is called when an instance of your datatype is "called",
707 for example, if \code{obj1} is an instance of your datatype and the Python
708 script contains \code{obj1('hello')}, the \member{tp_call} handler is
709 invoked.
711 This function takes three arguments:
713 \begin{enumerate}
714 \item
715 \var{arg1} is the instance of the datatype which is the subject of
716 the call. If the call is \code{obj1('hello')}, then \var{arg1} is
717 \code{obj1}.
719 \item
720 \var{arg2} is a tuple containing the arguments to the call. You
721 can use \cfunction{PyArg_ParseTuple()} to extract the arguments.
723 \item
724 \var{arg3} is a dictionary of keyword arguments that were passed.
725 If this is non-\NULL{} and you support keyword arguments, use
726 \cfunction{PyArg_ParseTupleAndKeywords()} to extract the
727 arguments. If you do not want to support keyword arguments and
728 this is non-\NULL, raise a \exception{TypeError} with a message
729 saying that keyword arguments are not supported.
730 \end{enumerate}
732 Here is a desultory example of the implementation of call function.
734 \begin{verbatim}
735 /* Implement the call function.
736 * obj1 is the instance receiving the call.
737 * obj2 is a tuple containing the arguments to the call, in this
738 * case 3 strings.
740 static PyObject *
741 newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
743 PyObject *result;
744 char *arg1;
745 char *arg2;
746 char *arg3;
748 if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
749 return NULL;
751 result = PyString_FromFormat(
752 "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",
753 obj->obj_UnderlyingDatatypePtr->size,
754 arg1, arg2, arg3);
755 printf("\%s", PyString_AS_STRING(result));
756 return result;
758 \end{verbatim}
761 \subsection{More Suggestions}
763 Remember that you can omit most of these functions, in which case you
764 provide \code{0} as a value.
766 In the \file{Objects} directory of the Python source distribution,
767 there is a file \file{xxobject.c}, which is intended to be used as a
768 template for the implementation of new types. One useful strategy
769 for implementing a new type is to copy and rename this file, then
770 read the instructions at the top of it.
772 There are type definitions for each of the functions you must
773 provide. They are in \file{object.h} in the Python include
774 directory that comes with the source distribution of Python.
776 In order to learn how to implement any specific method for your new
777 datatype, do the following: Download and unpack the Python source
778 distribution. Go the the \file{Objects} directory, then search the
779 C source files for \code{tp_} plus the function you want (for
780 example, \code{tp_print} or \code{tp_compare}). You will find
781 examples of the function you want to implement.
783 When you need to verify that the type of an object is indeed the
784 object you are implementing and if you use xxobject.c as an starting
785 template for your implementation, then there is a macro defined for
786 this purpose. The macro definition will look something like this:
788 \begin{verbatim}
789 #define is_newdatatypeobject(v) ((v)->ob_type == &Newdatatypetype)
790 \end{verbatim}
792 And, a sample of its use might be something like the following:
794 \begin{verbatim}
795 if (!is_newdatatypeobject(objp1) {
796 PyErr_SetString(PyExc_TypeError, "arg #1 not a newdatatype");
797 return NULL;
799 \end{verbatim}