1 \chapter{Object Implementation Support
\label{newTypes
}}
4 This chapter describes the functions, types, and macros used when
5 defining new object types.
8 \section{Allocating Objects on the Heap
9 \label{allocating-objects
}}
11 \begin{cfuncdesc
}{PyObject*
}{_PyObject_New
}{PyTypeObject *type
}
14 \begin{cfuncdesc
}{PyVarObject*
}{_PyObject_NewVar
}{PyTypeObject *type, Py_ssize_t size
}
17 \begin{cfuncdesc
}{void
}{_PyObject_Del
}{PyObject *op
}
20 \begin{cfuncdesc
}{PyObject*
}{PyObject_Init
}{PyObject *op,
22 Initialize a newly-allocated object
\var{op
} with its type and
23 initial reference. Returns the initialized object. If
\var{type
}
24 indicates that the object participates in the cyclic garbage
25 detector, it is added to the detector's set of observed objects.
26 Other fields of the object are not affected.
29 \begin{cfuncdesc
}{PyVarObject*
}{PyObject_InitVar
}{PyVarObject *op,
30 PyTypeObject *type, Py_ssize_t size
}
31 This does everything
\cfunction{PyObject_Init()
} does, and also
32 initializes the length information for a variable-size object.
35 \begin{cfuncdesc
}{\var{TYPE
}*
}{PyObject_New
}{TYPE, PyTypeObject *type
}
36 Allocate a new Python object using the C structure type
\var{TYPE
}
37 and the Python type object
\var{type
}. Fields not defined by the
38 Python object header are not initialized; the object's reference
39 count will be one. The size of the memory
40 allocation is determined from the
\member{tp_basicsize
} field of the
44 \begin{cfuncdesc
}{\var{TYPE
}*
}{PyObject_NewVar
}{TYPE, PyTypeObject *type,
46 Allocate a new Python object using the C structure type
\var{TYPE
}
47 and the Python type object
\var{type
}. Fields not defined by the
48 Python object header are not initialized. The allocated memory
49 allows for the
\var{TYPE
} structure plus
\var{size
} fields of the
50 size given by the
\member{tp_itemsize
} field of
\var{type
}. This is
51 useful for implementing objects like tuples, which are able to
52 determine their size at construction time. Embedding the array of
53 fields into the same allocation decreases the number of allocations,
54 improving the memory management efficiency.
57 \begin{cfuncdesc
}{void
}{PyObject_Del
}{PyObject *op
}
58 Releases memory allocated to an object using
59 \cfunction{PyObject_New()
} or
\cfunction{PyObject_NewVar()
}. This
60 is normally called from the
\member{tp_dealloc
} handler specified in
61 the object's type. The fields of the object should not be accessed
62 after this call as the memory is no longer a valid Python object.
65 \begin{cfuncdesc
}{PyObject*
}{Py_InitModule
}{char *name,
67 Create a new module object based on a name and table of functions,
68 returning the new module object.
70 \versionchanged[Older versions of Python did not support
\NULL{} as
71 the value for the
\var{methods
} argument
]{2.3}
74 \begin{cfuncdesc
}{PyObject*
}{Py_InitModule3
}{char *name,
77 Create a new module object based on a name and table of functions,
78 returning the new module object. If
\var{doc
} is non-
\NULL, it will
79 be used to define the docstring for the module.
81 \versionchanged[Older versions of Python did not support
\NULL{} as
82 the value for the
\var{methods
} argument
]{2.3}
85 \begin{cfuncdesc
}{PyObject*
}{Py_InitModule4
}{char *name,
87 char *doc, PyObject *self,
89 Create a new module object based on a name and table of functions,
90 returning the new module object. If
\var{doc
} is non-
\NULL, it will
91 be used to define the docstring for the module. If
\var{self
} is
92 non-
\NULL, it will passed to the functions of the module as their
93 (otherwise
\NULL) first parameter. (This was added as an
94 experimental feature, and there are no known uses in the current
95 version of Python.) For
\var{apiver
}, the only value which should
96 be passed is defined by the constant
\constant{PYTHON_API_VERSION
}.
98 \note{Most uses of this function should probably be using
99 the
\cfunction{Py_InitModule3()
} instead; only use this if you are
102 \versionchanged[Older versions of Python did not support
\NULL{} as
103 the value for the
\var{methods
} argument
]{2.3}
108 \begin{cvardesc
}{PyObject
}{_Py_NoneStruct
}
109 Object which is visible in Python as
\code{None
}. This should only
110 be accessed using the
\code{Py_None
} macro, which evaluates to a
111 pointer to this object.
115 \section{Common Object Structures
\label{common-structs
}}
117 There are a large number of structures which are used in the
118 definition of object types for Python. This section describes these
119 structures and how they are used.
121 All Python objects ultimately share a small number of fields at the
122 beginning of the object's representation in memory. These are
123 represented by the
\ctype{PyObject
} and
\ctype{PyVarObject
} types,
124 which are defined, in turn, by the expansions of some macros also
125 used, whether directly or indirectly, in the definition of all other
128 \begin{ctypedesc
}{PyObject
}
129 All object types are extensions of this type. This is a type which
130 contains the information Python needs to treat a pointer to an
131 object as an object. In a normal ``release'' build, it contains
132 only the objects reference count and a pointer to the corresponding
133 type object. It corresponds to the fields defined by the
134 expansion of the
\code{PyObject_HEAD
} macro.
137 \begin{ctypedesc
}{PyVarObject
}
138 This is an extension of
\ctype{PyObject
} that adds the
139 \member{ob_size
} field. This is only used for objects that have
140 some notion of
\emph{length
}. This type does not often appear in
141 the Python/C API. It corresponds to the fields defined by the
142 expansion of the
\code{PyObject_VAR_HEAD
} macro.
145 These macros are used in the definition of
\ctype{PyObject
} and
148 \begin{csimplemacrodesc
}{PyObject_HEAD
}
149 This is a macro which expands to the declarations of the fields of
150 the
\ctype{PyObject
} type; it is used when declaring new types which
151 represent objects without a varying length. The specific fields it
152 expands to depend on the definition of
153 \csimplemacro{Py_TRACE_REFS
}. By default, that macro is not
154 defined, and
\csimplemacro{PyObject_HEAD
} expands to:
156 Py_ssize_t ob_refcnt;
157 PyTypeObject *ob_type;
159 When
\csimplemacro{Py_TRACE_REFS
} is defined, it expands to:
161 PyObject *_ob_next, *_ob_prev;
162 Py_ssize_t ob_refcnt;
163 PyTypeObject *ob_type;
165 \end{csimplemacrodesc
}
167 \begin{csimplemacrodesc
}{PyObject_VAR_HEAD
}
168 This is a macro which expands to the declarations of the fields of
169 the
\ctype{PyVarObject
} type; it is used when declaring new types which
170 represent objects with a length that varies from instance to
171 instance. This macro always expands to:
176 Note that
\csimplemacro{PyObject_HEAD
} is part of the expansion, and
177 that its own expansion varies depending on the definition of
178 \csimplemacro{Py_TRACE_REFS
}.
179 \end{csimplemacrodesc
}
183 \begin{ctypedesc
}{PyCFunction
}
184 Type of the functions used to implement most Python callables in C.
185 Functions of this type take two
\ctype{PyObject*
} parameters and
186 return one such value. If the return value is
\NULL, an exception
187 shall have been set. If not
\NULL, the return value is interpreted
188 as the return value of the function as exposed in Python. The
189 function must return a new reference.
192 \begin{ctypedesc
}{PyMethodDef
}
193 Structure used to describe a method of an extension type. This
194 structure has four fields:
196 \begin{tableiii
}{l|l|l
}{member
}{Field
}{C Type
}{Meaning
}
197 \lineiii{ml_name
}{char *
}{name of the method
}
198 \lineiii{ml_meth
}{PyCFunction
}{pointer to the C implementation
}
199 \lineiii{ml_flags
}{int
}{flag bits indicating how the call should be
201 \lineiii{ml_doc
}{char *
}{points to the contents of the docstring
}
205 The
\member{ml_meth
} is a C function pointer. The functions may be of
206 different types, but they always return
\ctype{PyObject*
}. If the
207 function is not of the
\ctype{PyCFunction
}, the compiler will require
208 a cast in the method table. Even though
\ctype{PyCFunction
} defines
209 the first parameter as
\ctype{PyObject*
}, it is common that the method
210 implementation uses a the specific C type of the
\var{self
} object.
212 The
\member{ml_flags
} field is a bitfield which can include the
213 following flags. The individual flags indicate either a calling
214 convention or a binding convention. Of the calling convention flags,
215 only
\constant{METH_VARARGS
} and
\constant{METH_KEYWORDS
} can be
216 combined (but note that
\constant{METH_KEYWORDS
} alone is equivalent
217 to
\code{\constant{METH_VARARGS
} |
\constant{METH_KEYWORDS
}}).
218 Any of the calling convention flags can be combined with a
221 \begin{datadesc
}{METH_VARARGS
}
222 This is the typical calling convention, where the methods have the
223 type
\ctype{PyCFunction
}. The function expects two
224 \ctype{PyObject*
} values. The first one is the
\var{self
} object for
225 methods; for module functions, it has the value given to
226 \cfunction{Py_InitModule4()
} (or
\NULL{} if
227 \cfunction{Py_InitModule()
} was used). The second parameter
228 (often called
\var{args
}) is a tuple object representing all
229 arguments. This parameter is typically processed using
230 \cfunction{PyArg_ParseTuple()
} or
\cfunction{PyArg_UnpackTuple
}.
233 \begin{datadesc
}{METH_KEYWORDS
}
234 Methods with these flags must be of type
235 \ctype{PyCFunctionWithKeywords
}. The function expects three
236 parameters:
\var{self
},
\var{args
}, and a dictionary of all the
237 keyword arguments. The flag is typically combined with
238 \constant{METH_VARARGS
}, and the parameters are typically processed
239 using
\cfunction{PyArg_ParseTupleAndKeywords()
}.
242 \begin{datadesc
}{METH_NOARGS
}
243 Methods without parameters don't need to check whether arguments are
244 given if they are listed with the
\constant{METH_NOARGS
} flag. They
245 need to be of type
\ctype{PyCFunction
}. When used with object
246 methods, the first parameter is typically named
\code{self
} and will
247 hold a reference to the object instance. In all cases the second
248 parameter will be
\NULL.
251 \begin{datadesc
}{METH_O
}
252 Methods with a single object argument can be listed with the
253 \constant{METH_O
} flag, instead of invoking
254 \cfunction{PyArg_ParseTuple()
} with a
\code{"O"
} argument. They have
255 the type
\ctype{PyCFunction
}, with the
\var{self
} parameter, and a
256 \ctype{PyObject*
} parameter representing the single argument.
259 \begin{datadesc
}{METH_OLDARGS
}
260 This calling convention is deprecated. The method must be of type
261 \ctype{PyCFunction
}. The second argument is
\NULL{} if no arguments
262 are given, a single object if exactly one argument is given, and a
263 tuple of objects if more than one argument is given. There is no
264 way for a function using this convention to distinguish between a
265 call with multiple arguments and a call with a tuple as the only
269 These two constants are not used to indicate the calling convention
270 but the binding when use with methods of classes. These may not be
271 used for functions defined for modules. At most one of these flags
272 may be set for any given method.
274 \begin{datadesc
}{METH_CLASS
}
275 The method will be passed the type object as the first parameter
276 rather than an instance of the type. This is used to create
277 \emph{class methods
}, similar to what is created when using the
278 \function{classmethod()
}\bifuncindex{classmethod
} built-in
283 \begin{datadesc
}{METH_STATIC
}
284 The method will be passed
\NULL{} as the first parameter rather than
285 an instance of the type. This is used to create
\emph{static
286 methods
}, similar to what is created when using the
287 \function{staticmethod()
}\bifuncindex{staticmethod
} built-in
292 One other constant controls whether a method is loaded in place of
293 another definition with the same method name.
295 \begin{datadesc
}{METH_COEXIST
}
296 The method will be loaded in place of existing definitions. Without
297 \var{METH_COEXIST
}, the default is to skip repeated definitions. Since
298 slot wrappers are loaded before the method table, the existence of a
299 \var{sq_contains
} slot, for example, would generate a wrapped method
300 named
\method{__contains__()
} and preclude the loading of a
301 corresponding PyCFunction with the same name. With the flag defined,
302 the PyCFunction will be loaded in place of the wrapper object and will
303 co-exist with the slot. This is helpful because calls to PyCFunctions
304 are optimized more than wrapper object calls.
308 \begin{cfuncdesc
}{PyObject*
}{Py_FindMethod
}{PyMethodDef table
[],
309 PyObject *ob, char *name
}
310 Return a bound method object for an extension type implemented in
311 C. This can be useful in the implementation of a
312 \member{tp_getattro
} or
\member{tp_getattr
} handler that does not
313 use the
\cfunction{PyObject_GenericGetAttr()
} function.
317 \section{Type Objects
\label{type-structs
}}
319 Perhaps one of the most important structures of the Python object
320 system is the structure that defines a new type: the
321 \ctype{PyTypeObject
} structure. Type objects can be handled using any
322 of the
\cfunction{PyObject_*()
} or
\cfunction{PyType_*()
} functions,
323 but do not offer much that's interesting to most Python applications.
324 These objects are fundamental to how objects behave, so they are very
325 important to the interpreter itself and to any extension module that
326 implements new types.
328 Type objects are fairly large compared to most of the standard types.
329 The reason for the size is that each type object stores a large number
330 of values, mostly C function pointers, each of which implements a
331 small part of the type's functionality. The fields of the type object
332 are examined in detail in this section. The fields will be described
333 in the order in which they occur in the structure.
336 unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
337 intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
338 destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc,
339 setattrofunc, cmpfunc, reprfunc, hashfunc
341 The structure definition for
\ctype{PyTypeObject
} can be found in
342 \file{Include/object.h
}. For convenience of reference, this repeats
343 the definition found there:
345 \verbatiminput{typestruct.h
}
347 The type object structure extends the
\ctype{PyVarObject
} structure.
348 The
\member{ob_size
} field is used for dynamic types (created
349 by
\function{type_new()
}, usually called from a class statement).
350 Note that
\cdata{PyType_Type
} (the metatype) initializes
351 \member{tp_itemsize
}, which means that its instances (i.e. type
352 objects)
\emph{must
} have the
\member{ob_size
} field.
354 \begin{cmemberdesc
}{PyObject
}{PyObject*
}{_ob_next
}
355 \cmemberline{PyObject
}{PyObject*
}{_ob_prev
}
356 These fields are only present when the macro
\code{Py_TRACE_REFS
} is
357 defined. Their initialization to
\NULL{} is taken care of by the
358 \code{PyObject_HEAD_INIT
} macro. For statically allocated objects,
359 these fields always remain
\NULL. For dynamically allocated
360 objects, these two fields are used to link the object into a
361 doubly-linked list of
\emph{all
} live objects on the heap. This
362 could be used for various debugging purposes; currently the only use
363 is to print the objects that are still alive at the end of a run
364 when the environment variable
\envvar{PYTHONDUMPREFS
} is set.
366 These fields are not inherited by subtypes.
369 \begin{cmemberdesc
}{PyObject
}{Py_ssize_t
}{ob_refcnt
}
370 This is the type object's reference count, initialized to
\code{1}
371 by the
\code{PyObject_HEAD_INIT
} macro. Note that for statically
372 allocated type objects, the type's instances (objects whose
373 \member{ob_type
} points back to the type) do
\emph{not
} count as
374 references. But for dynamically allocated type objects, the
375 instances
\emph{do
} count as references.
377 This field is not inherited by subtypes.
380 \begin{cmemberdesc
}{PyObject
}{PyTypeObject*
}{ob_type
}
381 This is the type's type, in other words its metatype. It is
382 initialized by the argument to the
\code{PyObject_HEAD_INIT
} macro,
383 and its value should normally be
\code{\&PyType_Type
}. However, for
384 dynamically loadable extension modules that must be usable on
385 Windows (at least), the compiler complains that this is not a valid
386 initializer. Therefore, the convention is to pass
\NULL{} to the
387 \code{PyObject_HEAD_INIT
} macro and to initialize this field
388 explicitly at the start of the module's initialization function,
389 before doing anything else. This is typically done like this:
392 Foo_Type.ob_type = &PyType_Type;
395 This should be done before any instances of the type are created.
396 \cfunction{PyType_Ready()
} checks if
\member{ob_type
} is
\NULL, and
397 if so, initializes it: in Python
2.2, it is set to
398 \code{\&PyType_Type
}; in Python
2.2.1 and later it is
399 initialized to the
\member{ob_type
} field of the base class.
400 \cfunction{PyType_Ready()
} will not change this field if it is
403 In Python
2.2, this field is not inherited by subtypes. In
2.2.1,
404 and in
2.3 and beyond, it is inherited by subtypes.
407 \begin{cmemberdesc
}{PyVarObject
}{Py_ssize_t
}{ob_size
}
408 For statically allocated type objects, this should be initialized
409 to zero. For dynamically allocated type objects, this field has a
410 special internal meaning.
412 This field is not inherited by subtypes.
415 \begin{cmemberdesc
}{PyTypeObject
}{char*
}{tp_name
}
416 Pointer to a NUL-terminated string containing the name of the type.
417 For types that are accessible as module globals, the string should
418 be the full module name, followed by a dot, followed by the type
419 name; for built-in types, it should be just the type name. If the
420 module is a submodule of a package, the full package name is part of
421 the full module name. For example, a type named
\class{T
} defined
422 in module
\module{M
} in subpackage
\module{Q
} in package
\module{P
}
423 should have the
\member{tp_name
} initializer
\code{"P.Q.M.T"
}.
425 For dynamically allocated type objects, this should just be the type
426 name, and the module name explicitly stored in the type dict as the
427 value for key
\code{'__module__'
}.
429 For statically allocated type objects, the tp_name field should
430 contain a dot. Everything before the last dot is made accessible as
431 the
\member{__module__
} attribute, and everything after the last dot
432 is made accessible as the
\member{__name__
} attribute.
434 If no dot is present, the entire
\member{tp_name
} field is made
435 accessible as the
\member{__name__
} attribute, and the
436 \member{__module__
} attribute is undefined (unless explicitly set in
437 the dictionary, as explained above). This means your type will be
438 impossible to pickle.
440 This field is not inherited by subtypes.
443 \begin{cmemberdesc
}{PyTypeObject
}{Py_ssize_t
}{tp_basicsize
}
444 \cmemberline{PyTypeObject
}{Py_ssize_t
}{tp_itemsize
}
445 These fields allow calculating the size in bytes of instances of
448 There are two kinds of types: types with fixed-length instances have
449 a zero
\member{tp_itemsize
} field, types with variable-length
450 instances have a non-zero
\member{tp_itemsize
} field. For a type
451 with fixed-length instances, all instances have the same size,
452 given in
\member{tp_basicsize
}.
454 For a type with variable-length instances, the instances must have
455 an
\member{ob_size
} field, and the instance size is
456 \member{tp_basicsize
} plus N times
\member{tp_itemsize
}, where N is
457 the ``length'' of the object. The value of N is typically stored in
458 the instance's
\member{ob_size
} field. There are exceptions: for
459 example, long ints use a negative
\member{ob_size
} to indicate a
460 negative number, and N is
\code{abs(
\member{ob_size
})
} there. Also,
461 the presence of an
\member{ob_size
} field in the instance layout
462 doesn't mean that the instance structure is variable-length (for
463 example, the structure for the list type has fixed-length instances,
464 yet those instances have a meaningful
\member{ob_size
} field).
466 The basic size includes the fields in the instance declared by the
467 macro
\csimplemacro{PyObject_HEAD
} or
468 \csimplemacro{PyObject_VAR_HEAD
} (whichever is used to declare the
469 instance struct) and this in turn includes the
\member{_ob_prev
} and
470 \member{_ob_next
} fields if they are present. This means that the
471 only correct way to get an initializer for the
\member{tp_basicsize
}
472 is to use the
\keyword{sizeof
} operator on the struct used to
473 declare the instance layout. The basic size does not include the GC
474 header size (this is new in Python
2.2; in
2.1 and
2.0, the GC
475 header size was included in
\member{tp_basicsize
}).
477 These fields are inherited separately by subtypes. If the base type
478 has a non-zero
\member{tp_itemsize
}, it is generally not safe to set
479 \member{tp_itemsize
} to a different non-zero value in a subtype
480 (though this depends on the implementation of the base type).
482 A note about alignment: if the variable items require a particular
483 alignment, this should be taken care of by the value of
484 \member{tp_basicsize
}. Example: suppose a type implements an array
485 of
\code{double
}.
\member{tp_itemsize
} is
\code{sizeof(double)
}.
486 It is the programmer's responsibility that
\member{tp_basicsize
} is
487 a multiple of
\code{sizeof(double)
} (assuming this is the alignment
488 requirement for
\code{double
}).
491 \begin{cmemberdesc
}{PyTypeObject
}{destructor
}{tp_dealloc
}
492 A pointer to the instance destructor function. This function must
493 be defined unless the type guarantees that its instances will never
494 be deallocated (as is the case for the singletons
\code{None
} and
497 The destructor function is called by the
\cfunction{Py_DECREF()
} and
498 \cfunction{Py_XDECREF()
} macros when the new reference count is
499 zero. At this point, the instance is still in existence, but there
500 are no references to it. The destructor function should free all
501 references which the instance owns, free all memory buffers owned by
502 the instance (using the freeing function corresponding to the
503 allocation function used to allocate the buffer), and finally (as
504 its last action) call the type's
\member{tp_free
} function. If the
505 type is not subtypable (doesn't have the
506 \constant{Py_TPFLAGS_BASETYPE
} flag bit set), it is permissible to
507 call the object deallocator directly instead of via
508 \member{tp_free
}. The object deallocator should be the one used to
509 allocate the instance; this is normally
\cfunction{PyObject_Del()
}
510 if the instance was allocated using
\cfunction{PyObject_New()
} or
511 \cfunction{PyObject_VarNew()
}, or
\cfunction{PyObject_GC_Del()
} if
512 the instance was allocated using
\cfunction{PyObject_GC_New()
} or
513 \cfunction{PyObject_GC_VarNew()
}.
515 This field is inherited by subtypes.
518 \begin{cmemberdesc
}{PyTypeObject
}{printfunc
}{tp_print
}
519 An optional pointer to the instance print function.
521 The print function is only called when the instance is printed to a
522 \emph{real
} file; when it is printed to a pseudo-file (like a
523 \class{StringIO
} instance), the instance's
\member{tp_repr
} or
524 \member{tp_str
} function is called to convert it to a string. These
525 are also called when the type's
\member{tp_print
} field is
\NULL. A
526 type should never implement
\member{tp_print
} in a way that produces
527 different output than
\member{tp_repr
} or
\member{tp_str
} would.
529 The print function is called with the same signature as
530 \cfunction{PyObject_Print()
}:
\code{int tp_print(PyObject *self, FILE
531 *file, int flags)
}. The
\var{self
} argument is the instance to be
532 printed. The
\var{file
} argument is the stdio file to which it is
533 to be printed. The
\var{flags
} argument is composed of flag bits.
534 The only flag bit currently defined is
\constant{Py_PRINT_RAW
}.
535 When the
\constant{Py_PRINT_RAW
} flag bit is set, the instance
536 should be printed the same way as
\member{tp_str
} would format it;
537 when the
\constant{Py_PRINT_RAW
} flag bit is clear, the instance
538 should be printed the same was as
\member{tp_repr
} would format it.
539 It should return
\code{-
1} and set an exception condition when an
540 error occurred during the comparison.
542 It is possible that the
\member{tp_print
} field will be deprecated.
543 In any case, it is recommended not to define
\member{tp_print
}, but
544 instead to rely on
\member{tp_repr
} and
\member{tp_str
} for
547 This field is inherited by subtypes.
550 \begin{cmemberdesc
}{PyTypeObject
}{getattrfunc
}{tp_getattr
}
551 An optional pointer to the get-attribute-string function.
553 This field is deprecated. When it is defined, it should point to a
554 function that acts the same as the
\member{tp_getattro
} function,
555 but taking a C string instead of a Python string object to give the
556 attribute name. The signature is the same as for
557 \cfunction{PyObject_GetAttrString()
}.
559 This field is inherited by subtypes together with
560 \member{tp_getattro
}: a subtype inherits both
\member{tp_getattr
}
561 and
\member{tp_getattro
} from its base type when the subtype's
562 \member{tp_getattr
} and
\member{tp_getattro
} are both
\NULL.
565 \begin{cmemberdesc
}{PyTypeObject
}{setattrfunc
}{tp_setattr
}
566 An optional pointer to the set-attribute-string function.
568 This field is deprecated. When it is defined, it should point to a
569 function that acts the same as the
\member{tp_setattro
} function,
570 but taking a C string instead of a Python string object to give the
571 attribute name. The signature is the same as for
572 \cfunction{PyObject_SetAttrString()
}.
574 This field is inherited by subtypes together with
575 \member{tp_setattro
}: a subtype inherits both
\member{tp_setattr
}
576 and
\member{tp_setattro
} from its base type when the subtype's
577 \member{tp_setattr
} and
\member{tp_setattro
} are both
\NULL.
580 \begin{cmemberdesc
}{PyTypeObject
}{cmpfunc
}{tp_compare
}
581 An optional pointer to the three-way comparison function.
583 The signature is the same as for
\cfunction{PyObject_Compare()
}.
584 The function should return
\code{1} if
\var{self
} greater than
585 \var{other
},
\code{0} if
\var{self
} is equal to
\var{other
}, and
586 \code{-
1} if
\var{self
} less than
\var{other
}. It should return
587 \code{-
1} and set an exception condition when an error occurred
588 during the comparison.
590 This field is inherited by subtypes together with
591 \member{tp_richcompare
} and
\member{tp_hash
}: a subtypes inherits
592 all three of
\member{tp_compare
},
\member{tp_richcompare
}, and
593 \member{tp_hash
} when the subtype's
\member{tp_compare
},
594 \member{tp_richcompare
}, and
\member{tp_hash
} are all
\NULL.
597 \begin{cmemberdesc
}{PyTypeObject
}{reprfunc
}{tp_repr
}
598 An optional pointer to a function that implements the built-in
599 function
\function{repr()
}.
\bifuncindex{repr
}
601 The signature is the same as for
\cfunction{PyObject_Repr()
}; it
602 must return a string or a Unicode object. Ideally, this function
603 should return a string that, when passed to
\function{eval()
}, given
604 a suitable environment, returns an object with the same value. If
605 this is not feasible, it should return a string starting with
606 \character{\textless} and ending with
\character{\textgreater} from
607 which both the type and the value of the object can be deduced.
609 When this field is not set, a string of the form
\samp{<\%s object
610 at \%p>
} is returned, where
\code{\%s
} is replaced by the type name,
611 and
\code{\%p
} by the object's memory address.
613 This field is inherited by subtypes.
616 PyNumberMethods *tp_as_number;
620 PySequenceMethods *tp_as_sequence;
624 PyMappingMethods *tp_as_mapping;
628 \begin{cmemberdesc
}{PyTypeObject
}{hashfunc
}{tp_hash
}
629 An optional pointer to a function that implements the built-in
630 function
\function{hash()
}.
\bifuncindex{hash
}
632 The signature is the same as for
\cfunction{PyObject_Hash()
}; it
633 must return a C long. The value
\code{-
1} should not be returned as
634 a normal return value; when an error occurs during the computation
635 of the hash value, the function should set an exception and return
638 When this field is not set, two possibilities exist: if the
639 \member{tp_compare
} and
\member{tp_richcompare
} fields are both
640 \NULL, a default hash value based on the object's address is
641 returned; otherwise, a
\exception{TypeError
} is raised.
643 This field is inherited by subtypes together with
644 \member{tp_richcompare
} and
\member{tp_compare
}: a subtypes inherits
645 all three of
\member{tp_compare
},
\member{tp_richcompare
}, and
646 \member{tp_hash
}, when the subtype's
\member{tp_compare
},
647 \member{tp_richcompare
} and
\member{tp_hash
} are all
\NULL.
650 \begin{cmemberdesc
}{PyTypeObject
}{ternaryfunc
}{tp_call
}
651 An optional pointer to a function that implements calling the
652 object. This should be
\NULL{} if the object is not callable. The
653 signature is the same as for
\cfunction{PyObject_Call()
}.
655 This field is inherited by subtypes.
658 \begin{cmemberdesc
}{PyTypeObject
}{reprfunc
}{tp_str
}
659 An optional pointer to a function that implements the built-in
660 operation
\function{str()
}. (Note that
\class{str
} is a type now,
661 and
\function{str()
} calls the constructor for that type. This
662 constructor calls
\cfunction{PyObject_Str()
} to do the actual work,
663 and
\cfunction{PyObject_Str()
} will call this handler.)
665 The signature is the same as for
\cfunction{PyObject_Str()
}; it must
666 return a string or a Unicode object. This function should return a
667 ``friendly'' string representation of the object, as this is the
668 representation that will be used by the print statement.
670 When this field is not set,
\cfunction{PyObject_Repr()
} is called to
671 return a string representation.
673 This field is inherited by subtypes.
676 \begin{cmemberdesc
}{PyTypeObject
}{getattrofunc
}{tp_getattro
}
677 An optional pointer to the get-attribute function.
679 The signature is the same as for
\cfunction{PyObject_GetAttr()
}. It
680 is usually convenient to set this field to
681 \cfunction{PyObject_GenericGetAttr()
}, which implements the normal
682 way of looking for object attributes.
684 This field is inherited by subtypes together with
685 \member{tp_getattr
}: a subtype inherits both
\member{tp_getattr
} and
686 \member{tp_getattro
} from its base type when the subtype's
687 \member{tp_getattr
} and
\member{tp_getattro
} are both
\NULL.
690 \begin{cmemberdesc
}{PyTypeObject
}{setattrofunc
}{tp_setattro
}
691 An optional pointer to the set-attribute function.
693 The signature is the same as for
\cfunction{PyObject_SetAttr()
}. It
694 is usually convenient to set this field to
695 \cfunction{PyObject_GenericSetAttr()
}, which implements the normal
696 way of setting object attributes.
698 This field is inherited by subtypes together with
699 \member{tp_setattr
}: a subtype inherits both
\member{tp_setattr
} and
700 \member{tp_setattro
} from its base type when the subtype's
701 \member{tp_setattr
} and
\member{tp_setattro
} are both
\NULL.
704 \begin{cmemberdesc
}{PyTypeObject
}{PyBufferProcs*
}{tp_as_buffer
}
705 Pointer to an additional structure that contains fields relevant only to
706 objects which implement the buffer interface. These fields are
707 documented in ``Buffer Object Structures'' (section
708 \ref{buffer-structs
}).
710 The
\member{tp_as_buffer
} field is not inherited, but the contained
711 fields are inherited individually.
714 \begin{cmemberdesc
}{PyTypeObject
}{long
}{tp_flags
}
715 This field is a bit mask of various flags. Some flags indicate
716 variant semantics for certain situations; others are used to
717 indicate that certain fields in the type object (or in the extension
718 structures referenced via
\member{tp_as_number
},
719 \member{tp_as_sequence
},
\member{tp_as_mapping
}, and
720 \member{tp_as_buffer
}) that were historically not always present are
721 valid; if such a flag bit is clear, the type fields it guards must
722 not be accessed and must be considered to have a zero or
\NULL{}
725 Inheritance of this field is complicated. Most flag bits are
726 inherited individually, i.e. if the base type has a flag bit set,
727 the subtype inherits this flag bit. The flag bits that pertain to
728 extension structures are strictly inherited if the extension
729 structure is inherited, i.e. the base type's value of the flag bit
730 is copied into the subtype together with a pointer to the extension
731 structure. The
\constant{Py_TPFLAGS_HAVE_GC
} flag bit is inherited
732 together with the
\member{tp_traverse
} and
\member{tp_clear
} fields,
733 i.e. if the
\constant{Py_TPFLAGS_HAVE_GC
} flag bit is clear in the
734 subtype and the
\member{tp_traverse
} and
\member{tp_clear
} fields in
735 the subtype exist (as indicated by the
736 \constant{Py_TPFLAGS_HAVE_RICHCOMPARE
} flag bit) and have
\NULL{}
739 The following bit masks are currently defined; these can be or-ed
740 together using the
\code{|
} operator to form the value of the
741 \member{tp_flags
} field. The macro
\cfunction{PyType_HasFeature()
}
742 takes a type and a flags value,
\var{tp
} and
\var{f
}, and checks
743 whether
\code{\var{tp
}->tp_flags \&
\var{f
}} is non-zero.
745 \begin{datadesc
}{Py_TPFLAGS_HAVE_GETCHARBUFFER
}
746 If this bit is set, the
\ctype{PyBufferProcs
} struct referenced by
747 \member{tp_as_buffer
} has the
\member{bf_getcharbuffer
} field.
750 \begin{datadesc
}{Py_TPFLAGS_HAVE_SEQUENCE_IN
}
751 If this bit is set, the
\ctype{PySequenceMethods
} struct
752 referenced by
\member{tp_as_sequence
} has the
\member{sq_contains
}
756 \begin{datadesc
}{Py_TPFLAGS_GC
}
757 This bit is obsolete. The bit it used to name is no longer in
758 use. The symbol is now defined as zero.
761 \begin{datadesc
}{Py_TPFLAGS_HAVE_INPLACEOPS
}
762 If this bit is set, the
\ctype{PySequenceMethods
} struct
763 referenced by
\member{tp_as_sequence
} and the
764 \ctype{PyNumberMethods
} structure referenced by
765 \member{tp_as_number
} contain the fields for in-place operators.
766 In particular, this means that the
\ctype{PyNumberMethods
}
767 structure has the fields
\member{nb_inplace_add
},
768 \member{nb_inplace_subtract
},
\member{nb_inplace_multiply
},
769 \member{nb_inplace_divide
},
\member{nb_inplace_remainder
},
770 \member{nb_inplace_power
},
\member{nb_inplace_lshift
},
771 \member{nb_inplace_rshift
},
\member{nb_inplace_and
},
772 \member{nb_inplace_xor
}, and
\member{nb_inplace_or
}; and the
773 \ctype{PySequenceMethods
} struct has the fields
774 \member{sq_inplace_concat
} and
\member{sq_inplace_repeat
}.
777 \begin{datadesc
}{Py_TPFLAGS_CHECKTYPES
}
778 If this bit is set, the binary and ternary operations in the
779 \ctype{PyNumberMethods
} structure referenced by
780 \member{tp_as_number
} accept arguments of arbitrary object types,
781 and do their own type conversions if needed. If this bit is
782 clear, those operations require that all arguments have the
783 current type as their type, and the caller is supposed to perform
784 a coercion operation first. This applies to
\member{nb_add
},
785 \member{nb_subtract
},
\member{nb_multiply
},
\member{nb_divide
},
786 \member{nb_remainder
},
\member{nb_divmod
},
\member{nb_power
},
787 \member{nb_lshift
},
\member{nb_rshift
},
\member{nb_and
},
788 \member{nb_xor
}, and
\member{nb_or
}.
791 \begin{datadesc
}{Py_TPFLAGS_HAVE_RICHCOMPARE
}
792 If this bit is set, the type object has the
793 \member{tp_richcompare
} field, as well as the
\member{tp_traverse
}
794 and the
\member{tp_clear
} fields.
797 \begin{datadesc
}{Py_TPFLAGS_HAVE_WEAKREFS
}
798 If this bit is set, the
\member{tp_weaklistoffset
} field is
799 defined. Instances of a type are weakly referenceable if the
800 type's
\member{tp_weaklistoffset
} field has a value greater than
804 \begin{datadesc
}{Py_TPFLAGS_HAVE_ITER
}
805 If this bit is set, the type object has the
\member{tp_iter
} and
806 \member{tp_iternext
} fields.
809 \begin{datadesc
}{Py_TPFLAGS_HAVE_CLASS
}
810 If this bit is set, the type object has several new fields defined
811 starting in Python
2.2:
\member{tp_methods
},
\member{tp_members
},
812 \member{tp_getset
},
\member{tp_base
},
\member{tp_dict
},
813 \member{tp_descr_get
},
\member{tp_descr_set
},
814 \member{tp_dictoffset
},
\member{tp_init
},
\member{tp_alloc
},
815 \member{tp_new
},
\member{tp_free
},
\member{tp_is_gc
},
816 \member{tp_bases
},
\member{tp_mro
},
\member{tp_cache
},
817 \member{tp_subclasses
}, and
\member{tp_weaklist
}.
820 \begin{datadesc
}{Py_TPFLAGS_HEAPTYPE
}
821 This bit is set when the type object itself is allocated on the
822 heap. In this case, the
\member{ob_type
} field of its instances
823 is considered a reference to the type, and the type object is
824 INCREF'ed when a new instance is created, and DECREF'ed when an
825 instance is destroyed (this does not apply to instances of
826 subtypes; only the type referenced by the instance's ob_type gets
827 INCREF'ed or DECREF'ed).
830 \begin{datadesc
}{Py_TPFLAGS_BASETYPE
}
831 This bit is set when the type can be used as the base type of
832 another type. If this bit is clear, the type cannot be subtyped
833 (similar to a "final" class in Java).
836 \begin{datadesc
}{Py_TPFLAGS_READY
}
837 This bit is set when the type object has been fully initialized by
838 \cfunction{PyType_Ready()
}.
841 \begin{datadesc
}{Py_TPFLAGS_READYING
}
842 This bit is set while
\cfunction{PyType_Ready()
} is in the process
843 of initializing the type object.
846 \begin{datadesc
}{Py_TPFLAGS_HAVE_GC
}
847 This bit is set when the object supports garbage collection. If
848 this bit is set, instances must be created using
849 \cfunction{PyObject_GC_New()
} and destroyed using
850 \cfunction{PyObject_GC_Del()
}. More information in section XXX
851 about garbage collection. This bit also implies that the
852 GC-related fields
\member{tp_traverse
} and
\member{tp_clear
} are
853 present in the type object; but those fields also exist when
854 \constant{Py_TPFLAGS_HAVE_GC
} is clear but
855 \constant{Py_TPFLAGS_HAVE_RICHCOMPARE
} is set.
858 \begin{datadesc
}{Py_TPFLAGS_DEFAULT
}
859 This is a bitmask of all the bits that pertain to the existence of
860 certain fields in the type object and its extension structures.
861 Currently, it includes the following bits:
862 \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER
},
863 \constant{Py_TPFLAGS_HAVE_SEQUENCE_IN
},
864 \constant{Py_TPFLAGS_HAVE_INPLACEOPS
},
865 \constant{Py_TPFLAGS_HAVE_RICHCOMPARE
},
866 \constant{Py_TPFLAGS_HAVE_WEAKREFS
},
867 \constant{Py_TPFLAGS_HAVE_ITER
}, and
868 \constant{Py_TPFLAGS_HAVE_CLASS
}.
872 \begin{cmemberdesc
}{PyTypeObject
}{char*
}{tp_doc
}
873 An optional pointer to a NUL-terminated C string giving the
874 docstring for this type object. This is exposed as the
875 \member{__doc__
} attribute on the type and instances of the type.
877 This field is
\emph{not
} inherited by subtypes.
880 The following three fields only exist if the
881 \constant{Py_TPFLAGS_HAVE_RICHCOMPARE
} flag bit is set.
883 \begin{cmemberdesc
}{PyTypeObject
}{traverseproc
}{tp_traverse
}
884 An optional pointer to a traversal function for the garbage
885 collector. This is only used if the
\constant{Py_TPFLAGS_HAVE_GC
}
886 flag bit is set. More information about Python's garbage collection
887 scheme can be found in section
\ref{supporting-cycle-detection
}.
889 The
\member{tp_traverse
} pointer is used by the garbage collector
890 to detect reference cycles. A typical implementation of a
891 \member{tp_traverse
} function simply calls
\cfunction{Py_VISIT()
} on
892 each of the instance's members that are Python objects. For exampe, this
893 is function
\cfunction{local_traverse
} from the
\module{thread
} extension
898 local_traverse(localobject *self, visitproc visit, void *arg)
900 Py_VISIT(self->args);
902 Py_VISIT(self->dict);
907 Note that
\cfunction{Py_VISIT()
} is called only on those members that can
908 participate in reference cycles. Although there is also a
909 \samp{self->key
} member, it can only be
\NULL{} or a Python string and
910 therefore cannot be part of a reference cycle.
912 On the other hand, even if you know a member can never be part of a cycle,
913 as a debugging aid you may want to visit it anyway just so the
914 \module{gc
} module's
\function{get_referents()
} function will include it.
916 Note that
\cfunction{Py_VISIT()
} requires the
\var{visit
} and
\var{arg
}
917 parameters to
\cfunction{local_traverse
} to have these specific names;
918 don't name them just anything.
920 This field is inherited by subtypes together with
\member{tp_clear
}
921 and the
\constant{Py_TPFLAGS_HAVE_GC
} flag bit: the flag bit,
922 \member{tp_traverse
}, and
\member{tp_clear
} are all inherited from
923 the base type if they are all zero in the subtype
\emph{and
} the
924 subtype has the
\constant{Py_TPFLAGS_HAVE_RICHCOMPARE
} flag bit set.
927 \begin{cmemberdesc
}{PyTypeObject
}{inquiry
}{tp_clear
}
928 An optional pointer to a clear function for the garbage collector.
929 This is only used if the
\constant{Py_TPFLAGS_HAVE_GC
} flag bit is
932 The
\member{tp_clear
} member function is used to break reference
933 cycles in cyclic garbage detected by the garbage collector. Taken
934 together, all
\member{tp_clear
} functions in the system must combine to
935 break all reference cycles. This is subtle, and if in any doubt supply a
936 \member{tp_clear
} function. For example, the tuple type does not
937 implement a
\member{tp_clear
} function, because it's possible to prove
938 that no reference cycle can be composed entirely of tuples. Therefore
939 the
\member{tp_clear
} functions of other types must be sufficient to
940 break any cycle containing a tuple. This isn't immediately obvious, and
941 there's rarely a good reason to avoid implementing
\member{tp_clear
}.
943 Implementations of
\member{tp_clear
} should drop the instance's
944 references to those of its members that may be Python objects, and set
945 its pointers to those members to
\NULL{}, as in the following example:
949 local_clear(localobject *self)
952 Py_CLEAR(self->args);
954 Py_CLEAR(self->dict);
959 The
\cfunction{Py_CLEAR()
} macro should be used, because clearing
960 references is delicate: the reference to the contained object must not be
961 decremented until after the pointer to the contained object is set to
962 \NULL{}. This is because decrementing the reference count may cause
963 the contained object to become trash, triggering a chain of reclamation
964 activity that may include invoking arbitrary Python code (due to
965 finalizers, or weakref callbacks, associated with the contained object).
966 If it's possible for such code to reference
\var{self
} again, it's
967 important that the pointer to the contained object be
\NULL{} at that
968 time, so that
\var{self
} knows the contained object can no longer be
969 used. The
\cfunction{Py_CLEAR()
} macro performs the operations in a
972 Because the goal of
\member{tp_clear
} functions is to break reference
973 cycles, it's not necessary to clear contained objects like Python strings
974 or Python integers, which can't participate in reference cycles.
975 On the other hand, it may be convenient to clear all contained Python
976 objects, and write the type's
\member{tp_dealloc
} function to
977 invoke
\member{tp_clear
}.
979 More information about Python's garbage collection
980 scheme can be found in section
\ref{supporting-cycle-detection
}.
982 This field is inherited by subtypes together with
\member{tp_clear
}
983 and the
\constant{Py_TPFLAGS_HAVE_GC
} flag bit: the flag bit,
984 \member{tp_traverse
}, and
\member{tp_clear
} are all inherited from
985 the base type if they are all zero in the subtype
\emph{and
} the
986 subtype has the
\constant{Py_TPFLAGS_HAVE_RICHCOMPARE
} flag bit set.
989 \begin{cmemberdesc
}{PyTypeObject
}{richcmpfunc
}{tp_richcompare
}
990 An optional pointer to the rich comparison function.
992 The signature is the same as for
\cfunction{PyObject_RichCompare()
}.
993 The function should return the result of the comparison (usually
994 \code{Py_True
} or
\code{Py_False
}). If the comparison is undefined,
995 it must return
\code{Py_NotImplemented
}, if another error occurred
996 it must return
\code{NULL
} and set an exception condition.
998 This field is inherited by subtypes together with
999 \member{tp_compare
} and
\member{tp_hash
}: a subtype inherits all
1000 three of
\member{tp_compare
},
\member{tp_richcompare
}, and
1001 \member{tp_hash
}, when the subtype's
\member{tp_compare
},
1002 \member{tp_richcompare
}, and
\member{tp_hash
} are all
\NULL.
1004 The following constants are defined to be used as the third argument
1005 for
\member{tp_richcompare
} and for
\cfunction{PyObject_RichCompare()
}:
1007 \begin{tableii
}{l|c
}{constant
}{Constant
}{Comparison
}
1008 \lineii{Py_LT
}{\code{<
}}
1009 \lineii{Py_LE
}{\code{<=
}}
1010 \lineii{Py_EQ
}{\code{==
}}
1011 \lineii{Py_NE
}{\code{!=
}}
1012 \lineii{Py_GT
}{\code{>
}}
1013 \lineii{Py_GE
}{\code{>=
}}
1017 The next field only exists if the
\constant{Py_TPFLAGS_HAVE_WEAKREFS
}
1020 \begin{cmemberdesc
}{PyTypeObject
}{long
}{tp_weaklistoffset
}
1021 If the instances of this type are weakly referenceable, this field
1022 is greater than zero and contains the offset in the instance
1023 structure of the weak reference list head (ignoring the GC header,
1024 if present); this offset is used by
1025 \cfunction{PyObject_ClearWeakRefs()
} and the
1026 \cfunction{PyWeakref_*()
} functions. The instance structure needs
1027 to include a field of type
\ctype{PyObject*
} which is initialized to
1030 Do not confuse this field with
\member{tp_weaklist
}; that is the
1031 list head for weak references to the type object itself.
1033 This field is inherited by subtypes, but see the rules listed below.
1034 A subtype may override this offset; this means that the subtype uses
1035 a different weak reference list head than the base type. Since the
1036 list head is always found via
\member{tp_weaklistoffset
}, this
1037 should not be a problem.
1039 When a type defined by a class statement has no
\member{__slots__
}
1040 declaration, and none of its base types are weakly referenceable,
1041 the type is made weakly referenceable by adding a weak reference
1042 list head slot to the instance layout and setting the
1043 \member{tp_weaklistoffset
} of that slot's offset.
1045 When a type's
\member{__slots__
} declaration contains a slot named
1046 \member{__weakref__
}, that slot becomes the weak reference list head
1047 for instances of the type, and the slot's offset is stored in the
1048 type's
\member{tp_weaklistoffset
}.
1050 When a type's
\member{__slots__
} declaration does not contain a slot
1051 named
\member{__weakref__
}, the type inherits its
1052 \member{tp_weaklistoffset
} from its base type.
1055 The next two fields only exist if the
1056 \constant{Py_TPFLAGS_HAVE_CLASS
} flag bit is set.
1058 \begin{cmemberdesc
}{PyTypeObject
}{getiterfunc
}{tp_iter
}
1059 An optional pointer to a function that returns an iterator for the
1060 object. Its presence normally signals that the instances of this
1061 type are iterable (although sequences may be iterable without this
1062 function, and classic instances always have this function, even if
1063 they don't define an
\method{__iter__()
} method).
1065 This function has the same signature as
1066 \cfunction{PyObject_GetIter()
}.
1068 This field is inherited by subtypes.
1071 \begin{cmemberdesc
}{PyTypeObject
}{iternextfunc
}{tp_iternext
}
1072 An optional pointer to a function that returns the next item in an
1073 iterator, or raises
\exception{StopIteration
} when the iterator is
1074 exhausted. Its presence normally signals that the instances of this
1075 type are iterators (although classic instances always have this
1076 function, even if they don't define a
\method{next()
} method).
1078 Iterator types should also define the
\member{tp_iter
} function, and
1079 that function should return the iterator instance itself (not a new
1082 This function has the same signature as
\cfunction{PyIter_Next()
}.
1084 This field is inherited by subtypes.
1087 The next fields, up to and including
\member{tp_weaklist
}, only exist
1088 if the
\constant{Py_TPFLAGS_HAVE_CLASS
} flag bit is set.
1090 \begin{cmemberdesc
}{PyTypeObject
}{struct PyMethodDef*
}{tp_methods
}
1091 An optional pointer to a static
\NULL-terminated array of
1092 \ctype{PyMethodDef
} structures, declaring regular methods of this
1095 For each entry in the array, an entry is added to the type's
1096 dictionary (see
\member{tp_dict
} below) containing a method
1099 This field is not inherited by subtypes (methods are
1100 inherited through a different mechanism).
1103 \begin{cmemberdesc
}{PyTypeObject
}{struct PyMemberDef*
}{tp_members
}
1104 An optional pointer to a static
\NULL-terminated array of
1105 \ctype{PyMemberDef
} structures, declaring regular data members
1106 (fields or slots) of instances of this type.
1108 For each entry in the array, an entry is added to the type's
1109 dictionary (see
\member{tp_dict
} below) containing a member
1112 This field is not inherited by subtypes (members are inherited
1113 through a different mechanism).
1116 \begin{cmemberdesc
}{PyTypeObject
}{struct PyGetSetDef*
}{tp_getset
}
1117 An optional pointer to a static
\NULL-terminated array of
1118 \ctype{PyGetSetDef
} structures, declaring computed attributes of
1119 instances of this type.
1121 For each entry in the array, an entry is added to the type's
1122 dictionary (see
\member{tp_dict
} below) containing a getset
1125 This field is not inherited by subtypes (computed attributes are
1126 inherited through a different mechanism).
1128 Docs for PyGetSetDef (XXX belong elsewhere):
1131 typedef PyObject *
(*getter)(PyObject *, void *);
1132 typedef int
(*setter)(PyObject *, PyObject *, void *);
1134 typedef struct PyGetSetDef
{
1135 char *name; /* attribute name */
1136 getter get; /* C function to get the attribute */
1137 setter set; /* C function to set the attribute */
1138 char *doc; /* optional doc string */
1139 void *closure; /* optional additional data for getter and setter */
1144 \begin{cmemberdesc
}{PyTypeObject
}{PyTypeObject*
}{tp_base
}
1145 An optional pointer to a base type from which type properties are
1146 inherited. At this level, only single inheritance is supported;
1147 multiple inheritance require dynamically creating a type object by
1148 calling the metatype.
1150 This field is not inherited by subtypes (obviously), but it defaults
1151 to
\code{\&PyBaseObject_Type
} (which to Python programmers is known
1152 as the type
\class{object
}).
1155 \begin{cmemberdesc
}{PyTypeObject
}{PyObject*
}{tp_dict
}
1156 The type's dictionary is stored here by
\cfunction{PyType_Ready()
}.
1158 This field should normally be initialized to
\NULL{} before
1159 PyType_Ready is called; it may also be initialized to a dictionary
1160 containing initial attributes for the type. Once
1161 \cfunction{PyType_Ready()
} has initialized the type, extra
1162 attributes for the type may be added to this dictionary only if they
1163 don't correspond to overloaded operations (like
\method{__add__()
}).
1165 This field is not inherited by subtypes (though the attributes
1166 defined in here are inherited through a different mechanism).
1169 \begin{cmemberdesc
}{PyTypeObject
}{descrgetfunc
}{tp_descr_get
}
1170 An optional pointer to a "descriptor get" function.
1173 The function signature is
1176 PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
1181 This field is inherited by subtypes.
1184 \begin{cmemberdesc
}{PyTypeObject
}{descrsetfunc
}{tp_descr_set
}
1185 An optional pointer to a "descriptor set" function.
1187 The function signature is
1190 int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
1193 This field is inherited by subtypes.
1199 \begin{cmemberdesc
}{PyTypeObject
}{long
}{tp_dictoffset
}
1200 If the instances of this type have a dictionary containing instance
1201 variables, this field is non-zero and contains the offset in the
1202 instances of the type of the instance variable dictionary; this
1203 offset is used by
\cfunction{PyObject_GenericGetAttr()
}.
1205 Do not confuse this field with
\member{tp_dict
}; that is the
1206 dictionary for attributes of the type object itself.
1208 If the value of this field is greater than zero, it specifies the
1209 offset from the start of the instance structure. If the value is
1210 less than zero, it specifies the offset from the
\emph{end
} of the
1211 instance structure. A negative offset is more expensive to use, and
1212 should only be used when the instance structure contains a
1213 variable-length part. This is used for example to add an instance
1214 variable dictionary to subtypes of
\class{str
} or
\class{tuple
}.
1215 Note that the
\member{tp_basicsize
} field should account for the
1216 dictionary added to the end in that case, even though the dictionary
1217 is not included in the basic object layout. On a system with a
1218 pointer size of
4 bytes,
\member{tp_dictoffset
} should be set to
1219 \code{-
4} to indicate that the dictionary is at the very end of the
1222 The real dictionary offset in an instance can be computed from a
1223 negative
\member{tp_dictoffset
} as follows:
1226 dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
1227 if dictoffset is not aligned on sizeof(void*):
1228 round up to sizeof(void*)
1231 where
\member{tp_basicsize
},
\member{tp_itemsize
} and
1232 \member{tp_dictoffset
} are taken from the type object, and
1233 \member{ob_size
} is taken from the instance. The absolute value is
1234 taken because long ints use the sign of
\member{ob_size
} to store
1235 the sign of the number. (There's never a need to do this
1236 calculation yourself; it is done for you by
1237 \cfunction{_PyObject_GetDictPtr()
}.)
1239 This field is inherited by subtypes, but see the rules listed below.
1240 A subtype may override this offset; this means that the subtype
1241 instances store the dictionary at a difference offset than the base
1242 type. Since the dictionary is always found via
1243 \member{tp_dictoffset
}, this should not be a problem.
1245 When a type defined by a class statement has no
\member{__slots__
}
1246 declaration, and none of its base types has an instance variable
1247 dictionary, a dictionary slot is added to the instance layout and
1248 the
\member{tp_dictoffset
} is set to that slot's offset.
1250 When a type defined by a class statement has a
\member{__slots__
}
1251 declaration, the type inherits its
\member{tp_dictoffset
} from its
1254 (Adding a slot named
\member{__dict__
} to the
\member{__slots__
}
1255 declaration does not have the expected effect, it just causes
1256 confusion. Maybe this should be added as a feature just like
1257 \member{__weakref__
} though.)
1260 \begin{cmemberdesc
}{PyTypeObject
}{initproc
}{tp_init
}
1261 An optional pointer to an instance initialization function.
1263 This function corresponds to the
\method{__init__()
} method of
1264 classes. Like
\method{__init__()
}, it is possible to create an
1265 instance without calling
\method{__init__()
}, and it is possible to
1266 reinitialize an instance by calling its
\method{__init__()
} method
1269 The function signature is
1272 int tp_init(PyObject *self, PyObject *args, PyObject *kwds)
1275 The self argument is the instance to be initialized; the
\var{args
}
1276 and
\var{kwds
} arguments represent positional and keyword arguments
1277 of the call to
\method{__init__()
}.
1279 The
\member{tp_init
} function, if not
\NULL, is called when an
1280 instance is created normally by calling its type, after the type's
1281 \member{tp_new
} function has returned an instance of the type. If
1282 the
\member{tp_new
} function returns an instance of some other type
1283 that is not a subtype of the original type, no
\member{tp_init
}
1284 function is called; if
\member{tp_new
} returns an instance of a
1285 subtype of the original type, the subtype's
\member{tp_init
} is
1286 called. (VERSION NOTE: described here is what is implemented in
1287 Python
2.2.1 and later. In Python
2.2, the
\member{tp_init
} of the
1288 type of the object returned by
\member{tp_new
} was always called, if
1291 This field is inherited by subtypes.
1294 \begin{cmemberdesc
}{PyTypeObject
}{allocfunc
}{tp_alloc
}
1295 An optional pointer to an instance allocation function.
1297 The function signature is
1300 PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems)
1303 The purpose of this function is to separate memory allocation from
1304 memory initialization. It should return a pointer to a block of
1305 memory of adequate length for the instance, suitably aligned, and
1306 initialized to zeros, but with
\member{ob_refcnt
} set to
\code{1}
1307 and
\member{ob_type
} set to the type argument. If the type's
1308 \member{tp_itemsize
} is non-zero, the object's
\member{ob_size
} field
1309 should be initialized to
\var{nitems
} and the length of the
1310 allocated memory block should be
\code{tp_basicsize +
1311 \var{nitems
}*tp_itemsize
}, rounded up to a multiple of
1312 \code{sizeof(void*)
}; otherwise,
\var{nitems
} is not used and the
1313 length of the block should be
\member{tp_basicsize
}.
1315 Do not use this function to do any other instance initialization,
1316 not even to allocate additional memory; that should be done by
1319 This field is inherited by static subtypes, but not by dynamic
1320 subtypes (subtypes created by a class statement); in the latter,
1321 this field is always set to
\cfunction{PyType_GenericAlloc()
}, to
1322 force a standard heap allocation strategy. That is also the
1323 recommended value for statically defined types.
1326 \begin{cmemberdesc
}{PyTypeObject
}{newfunc
}{tp_new
}
1327 An optional pointer to an instance creation function.
1329 If this function is
\NULL{} for a particular type, that type cannot
1330 be called to create new instances; presumably there is some other
1331 way to create instances, like a factory function.
1333 The function signature is
1336 PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
1339 The subtype argument is the type of the object being created; the
1340 \var{args
} and
\var{kwds
} arguments represent positional and keyword
1341 arguments of the call to the type. Note that subtype doesn't have
1342 to equal the type whose
\member{tp_new
} function is called; it may
1343 be a subtype of that type (but not an unrelated type).
1345 The
\member{tp_new
} function should call
1346 \code{\var{subtype
}->tp_alloc(
\var{subtype
},
\var{nitems
})
} to
1347 allocate space for the object, and then do only as much further
1348 initialization as is absolutely necessary. Initialization that can
1349 safely be ignored or repeated should be placed in the
1350 \member{tp_init
} handler. A good rule of thumb is that for
1351 immutable types, all initialization should take place in
1352 \member{tp_new
}, while for mutable types, most initialization should
1353 be deferred to
\member{tp_init
}.
1355 This field is inherited by subtypes, except it is not inherited by
1356 static types whose
\member{tp_base
} is
\NULL{} or
1357 \code{\&PyBaseObject_Type
}. The latter exception is a precaution so
1358 that old extension types don't become callable simply by being
1359 linked with Python
2.2.
1362 \begin{cmemberdesc
}{PyTypeObject
}{destructor
}{tp_free
}
1363 An optional pointer to an instance deallocation function.
1365 The signature of this function has changed slightly: in Python
1366 2.2 and
2.2.1, its signature is
\ctype{destructor
}:
1369 void tp_free(PyObject *)
1372 In Python
2.3 and beyond, its signature is
\ctype{freefunc
}:
1375 void tp_free(void *)
1378 The only initializer that is compatible with both versions is
1379 \code{_PyObject_Del
}, whose definition has suitably adapted in
1382 This field is inherited by static subtypes, but not by dynamic
1383 subtypes (subtypes created by a class statement); in the latter,
1384 this field is set to a deallocator suitable to match
1385 \cfunction{PyType_GenericAlloc()
} and the value of the
1386 \constant{Py_TPFLAGS_HAVE_GC
} flag bit.
1389 \begin{cmemberdesc
}{PyTypeObject
}{inquiry
}{tp_is_gc
}
1390 An optional pointer to a function called by the garbage collector.
1392 The garbage collector needs to know whether a particular object is
1393 collectible or not. Normally, it is sufficient to look at the
1394 object's type's
\member{tp_flags
} field, and check the
1395 \constant{Py_TPFLAGS_HAVE_GC
} flag bit. But some types have a
1396 mixture of statically and dynamically allocated instances, and the
1397 statically allocated instances are not collectible. Such types
1398 should define this function; it should return
\code{1} for a
1399 collectible instance, and
\code{0} for a non-collectible instance.
1403 int tp_is_gc(PyObject *self)
1406 (The only example of this are types themselves. The metatype,
1407 \cdata{PyType_Type
}, defines this function to distinguish between
1408 statically and dynamically allocated types.)
1410 This field is inherited by subtypes. (VERSION NOTE: in Python
1411 2.2, it was not inherited. It is inherited in
2.2.1 and later
1415 \begin{cmemberdesc
}{PyTypeObject
}{PyObject*
}{tp_bases
}
1416 Tuple of base types.
1418 This is set for types created by a class statement. It should be
1419 \NULL{} for statically defined types.
1421 This field is not inherited.
1424 \begin{cmemberdesc
}{PyTypeObject
}{PyObject*
}{tp_mro
}
1425 Tuple containing the expanded set of base types, starting with the
1426 type itself and ending with
\class{object
}, in Method Resolution
1429 This field is not inherited; it is calculated fresh by
1430 \cfunction{PyType_Ready()
}.
1433 \begin{cmemberdesc
}{PyTypeObject
}{PyObject*
}{tp_cache
}
1434 Unused. Not inherited. Internal use only.
1437 \begin{cmemberdesc
}{PyTypeObject
}{PyObject*
}{tp_subclasses
}
1438 List of weak references to subclasses. Not inherited. Internal
1442 \begin{cmemberdesc
}{PyTypeObject
}{PyObject*
}{tp_weaklist
}
1443 Weak reference list head, for weak references to this type
1444 object. Not inherited. Internal use only.
1447 The remaining fields are only defined if the feature test macro
1448 \constant{COUNT_ALLOCS
} is defined, and are for internal use only.
1449 They are documented here for completeness. None of these fields are
1450 inherited by subtypes.
1452 \begin{cmemberdesc
}{PyTypeObject
}{Py_ssize_t
}{tp_allocs
}
1453 Number of allocations.
1456 \begin{cmemberdesc
}{PyTypeObject
}{Py_ssize_t
}{tp_frees
}
1460 \begin{cmemberdesc
}{PyTypeObject
}{Py_ssize_t
}{tp_maxalloc
}
1461 Maximum simultaneously allocated objects.
1464 \begin{cmemberdesc
}{PyTypeObject
}{PyTypeObject*
}{tp_next
}
1465 Pointer to the next type object with a non-zero
\member{tp_allocs
}
1469 Also, note that, in a garbage collected Python, tp_dealloc may be
1470 called from any Python thread, not just the thread which created the
1471 object (if the object becomes part of a refcount cycle, that cycle
1472 might be collected by a garbage collection on any thread). This is
1473 not a problem for Python API calls, since the thread on which
1474 tp_dealloc is called will own the Global Interpreter Lock (GIL).
1475 However, if the object being destroyed in turn destroys objects from
1476 some other C or
\Cpp{} library, care should be taken to ensure that
1477 destroying those objects on the thread which called tp_dealloc will
1478 not violate any assumptions of the library.
1480 \section{Mapping Object Structures
\label{mapping-structs
}}
1482 \begin{ctypedesc
}{PyMappingMethods
}
1483 Structure used to hold pointers to the functions used to implement
1484 the mapping protocol for an extension type.
1488 \section{Number Object Structures
\label{number-structs
}}
1490 \begin{ctypedesc
}{PyNumberMethods
}
1491 Structure used to hold pointers to the functions an extension type
1492 uses to implement the number protocol.
1496 \section{Sequence Object Structures
\label{sequence-structs
}}
1498 \begin{ctypedesc
}{PySequenceMethods
}
1499 Structure used to hold pointers to the functions which an object
1500 uses to implement the sequence protocol.
1504 \section{Buffer Object Structures
\label{buffer-structs
}}
1505 \sectionauthor{Greg J. Stein
}{greg@lyra.org
}
1507 The buffer interface exports a model where an object can expose its
1508 internal data as a set of chunks of data, where each chunk is
1509 specified as a pointer/length pair. These chunks are called
1510 \dfn{segments
} and are presumed to be non-contiguous in memory.
1512 If an object does not export the buffer interface, then its
1513 \member{tp_as_buffer
} member in the
\ctype{PyTypeObject
} structure
1514 should be
\NULL. Otherwise, the
\member{tp_as_buffer
} will point to
1515 a
\ctype{PyBufferProcs
} structure.
1517 \note{It is very important that your
\ctype{PyTypeObject
} structure
1518 uses
\constant{Py_TPFLAGS_DEFAULT
} for the value of the
1519 \member{tp_flags
} member rather than
\code{0}. This tells the Python
1520 runtime that your
\ctype{PyBufferProcs
} structure contains the
1521 \member{bf_getcharbuffer
} slot. Older versions of Python did not have
1522 this member, so a new Python interpreter using an old extension needs
1523 to be able to test for its presence before using it.
}
1525 \begin{ctypedesc
}{PyBufferProcs
}
1526 Structure used to hold the function pointers which define an
1527 implementation of the buffer protocol.
1529 The first slot is
\member{bf_getreadbuffer
}, of type
1530 \ctype{getreadbufferproc
}. If this slot is
\NULL, then the object
1531 does not support reading from the internal data. This is
1532 non-sensical, so implementors should fill this in, but callers
1533 should test that the slot contains a non-
\NULL{} value.
1535 The next slot is
\member{bf_getwritebuffer
} having type
1536 \ctype{getwritebufferproc
}. This slot may be
\NULL{} if the object
1537 does not allow writing into its returned buffers.
1539 The third slot is
\member{bf_getsegcount
}, with type
1540 \ctype{getsegcountproc
}. This slot must not be
\NULL{} and is used
1541 to inform the caller how many segments the object contains. Simple
1542 objects such as
\ctype{PyString_Type
} and
\ctype{PyBuffer_Type
}
1543 objects contain a single segment.
1545 The last slot is
\member{bf_getcharbuffer
}, of type
1546 \ctype{getcharbufferproc
}. This slot will only be present if the
1547 \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER
} flag is present in the
1548 \member{tp_flags
} field of the object's
\ctype{PyTypeObject
}.
1549 Before using this slot, the caller should test whether it is present
1551 \cfunction{PyType_HasFeature()
}\ttindex{PyType_HasFeature()
}
1552 function. If the flag is present,
\member{bf_getcharbuffer
} may be
1554 indicating that the object's
1555 contents cannot be used as
\emph{8-bit characters
}.
1556 The slot function may also raise an error if the object's contents
1557 cannot be interpreted as
8-bit characters. For example, if the
1558 object is an array which is configured to hold floating point
1559 values, an exception may be raised if a caller attempts to use
1560 \member{bf_getcharbuffer
} to fetch a sequence of
8-bit characters.
1561 This notion of exporting the internal buffers as ``text'' is used to
1562 distinguish between objects that are binary in nature, and those
1563 which have character-based content.
1565 \note{The current policy seems to state that these characters
1566 may be multi-byte characters. This implies that a buffer size of
1567 \var{N
} does not mean there are
\var{N
} characters present.
}
1570 \begin{datadesc
}{Py_TPFLAGS_HAVE_GETCHARBUFFER
}
1571 Flag bit set in the type structure to indicate that the
1572 \member{bf_getcharbuffer
} slot is known. This being set does not
1573 indicate that the object supports the buffer interface or that the
1574 \member{bf_getcharbuffer
} slot is non-
\NULL.
1577 \begin{ctypedesc
}[getreadbufferproc
]{Py_ssize_t
(*readbufferproc)
1578 (PyObject *self, Py_ssize_t segment, void **ptrptr)}
1579 Return a pointer to a readable segment of the buffer in
1580 \code{*\var{ptrptr}}. This function
1581 is allowed to raise an exception, in which case it must return
1582 \code{-1}. The \var{segment} which is specified must be zero or
1583 positive, and strictly less than the number of segments returned by
1584 the \member{bf_getsegcount} slot function. On success, it returns
1585 the length of the segment, and sets \code{*\var{ptrptr}} to a
1586 pointer to that memory.
1589 \begin{ctypedesc}[getwritebufferproc]{Py_ssize_t (*writebufferproc)
1590 (PyObject *self, Py_ssize_t segment, void **ptrptr)}
1591 Return a pointer to a writable memory buffer in
1592 \code{*\var{ptrptr}}, and the length of that segment as the function
1593 return value. The memory buffer must correspond to buffer segment
1594 \var{segment}. Must return \code{-1} and set an exception on
1595 error. \exception{TypeError} should be raised if the object only
1596 supports read-only buffers, and \exception{SystemError} should be
1597 raised when \var{segment} specifies a segment that doesn't exist.
1598 % Why doesn't it raise ValueError for this one?
1599 % GJS: because you shouldn't be calling it with an invalid
1600 % segment. That indicates a blatant programming error in the C
1604 \begin{ctypedesc}[getsegcountproc]{Py_ssize_t (*segcountproc)
1605 (PyObject *self, Py_ssize_t *lenp)}
1606 Return the number of memory segments which comprise the buffer. If
1607 \var{lenp} is not \NULL, the implementation must report the sum of
1608 the sizes (in bytes) of all segments in \code{*\var{lenp}}.
1609 The function cannot fail.
1612 \begin{ctypedesc}[getcharbufferproc]{Py_ssize_t (*charbufferproc)
1613 (PyObject *self, Py_ssize_t segment, const char **ptrptr)}
1614 Return the size of the segment \var{segment} that \var{ptrptr}
1615 is set to. \code{*\var{ptrptr}} is set to the memory buffer.
1616 Returns \code{-1} on error.
1620 \section{Supporting the Iterator Protocol
1621 \label{supporting-iteration}}
1624 \section{Supporting Cyclic Garbage Collection
1625 \label{supporting-cycle-detection}}
1627 Python's support for detecting and collecting garbage which involves
1628 circular references requires support from object types which are
1629 ``containers'' for other objects which may also be containers. Types
1630 which do not store references to other objects, or which only store
1631 references to atomic types (such as numbers or strings), do not need
1632 to provide any explicit support for garbage collection.
1634 An example showing the use of these interfaces can be found in
1635 ``\ulink{Supporting the Cycle
1636 Collector}{../ext/example-cycle-support.html}'' in
1637 \citetitle[../ext/ext.html]{Extending and Embedding the Python
1640 To create a container type, the \member{tp_flags} field of the type
1641 object must include the \constant{Py_TPFLAGS_HAVE_GC} and provide an
1642 implementation of the \member{tp_traverse} handler. If instances of the
1643 type are mutable, a \member{tp_clear} implementation must also be
1646 \begin{datadesc}{Py_TPFLAGS_HAVE_GC}
1647 Objects with a type with this flag set must conform with the rules
1648 documented here. For convenience these objects will be referred to
1649 as container objects.
1652 Constructors for container types must conform to two rules:
1655 \item The memory for the object must be allocated using
1656 \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_VarNew()}.
1658 \item Once all the fields which may contain references to other
1659 containers are initialized, it must call
1660 \cfunction{PyObject_GC_Track()}.
1663 \begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_New}{TYPE, PyTypeObject *type}
1664 Analogous to \cfunction{PyObject_New()} but for container objects with
1665 the \constant{Py_TPFLAGS_HAVE_GC} flag set.
1668 \begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_NewVar}{TYPE, PyTypeObject *type,
1670 Analogous to \cfunction{PyObject_NewVar()} but for container objects
1671 with the \constant{Py_TPFLAGS_HAVE_GC} flag set.
1674 \begin{cfuncdesc}{PyVarObject *}{PyObject_GC_Resize}{PyVarObject *op, Py_ssize_t}
1675 Resize an object allocated by \cfunction{PyObject_NewVar()}. Returns
1676 the resized object or \NULL{} on failure.
1679 \begin{cfuncdesc}{void}{PyObject_GC_Track}{PyObject *op}
1680 Adds the object \var{op} to the set of container objects tracked by
1681 the collector. The collector can run at unexpected times so objects
1682 must be valid while being tracked. This should be called once all
1683 the fields followed by the \member{tp_traverse} handler become valid,
1684 usually near the end of the constructor.
1687 \begin{cfuncdesc}{void}{_PyObject_GC_TRACK}{PyObject *op}
1688 A macro version of \cfunction{PyObject_GC_Track()}. It should not be
1689 used for extension modules.
1692 Similarly, the deallocator for the object must conform to a similar
1696 \item Before fields which refer to other containers are invalidated,
1697 \cfunction{PyObject_GC_UnTrack()} must be called.
1699 \item The object's memory must be deallocated using
1700 \cfunction{PyObject_GC_Del()}.
1703 \begin{cfuncdesc}{void}{PyObject_GC_Del}{void *op}
1704 Releases memory allocated to an object using
1705 \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_NewVar()}.
1708 \begin{cfuncdesc}{void}{PyObject_GC_UnTrack}{void *op}
1709 Remove the object \var{op} from the set of container objects tracked
1710 by the collector. Note that \cfunction{PyObject_GC_Track()} can be
1711 called again on this object to add it back to the set of tracked
1712 objects. The deallocator (\member{tp_dealloc} handler) should call
1713 this for the object before any of the fields used by the
1714 \member{tp_traverse} handler become invalid.
1717 \begin{cfuncdesc}{void}{_PyObject_GC_UNTRACK}{PyObject *op}
1718 A macro version of \cfunction{PyObject_GC_UnTrack()}. It should not be
1719 used for extension modules.
1722 The \member{tp_traverse} handler accepts a function parameter of this
1725 \begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
1726 Type of the visitor function passed to the \member{tp_traverse}
1727 handler. The function should be called with an object to traverse
1728 as \var{object} and the third parameter to the \member{tp_traverse}
1729 handler as \var{arg}. The Python core uses several visitor functions
1730 to implement cyclic garbage detection; it's not expected that users will
1731 need to write their own visitor functions.
1734 The \member{tp_traverse} handler must have the following type:
1736 \begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
1737 visitproc visit, void *arg)}
1738 Traversal function for a container object. Implementations must
1739 call the \var{visit} function for each object directly contained by
1740 \var{self}, with the parameters to \var{visit} being the contained
1741 object and the \var{arg} value passed to the handler. The \var{visit}
1742 function must not be called with a \NULL{} object argument. If
1743 \var{visit} returns a non-zero value
1744 that value should be returned immediately.
1747 To simplify writing \member{tp_traverse} handlers, a
1748 \cfunction{Py_VISIT()} macro is provided. In order to use this macro,
1749 the \member{tp_traverse} implementation must name its arguments
1750 exactly \var{visit} and \var{arg}:
1752 \begin{cfuncdesc}{void}{Py_VISIT}{PyObject *o}
1753 Call the \var{visit} callback, with arguments \var{o} and \var{arg}.
1754 If \var{visit} returns a non-zero value, then return it. Using this
1755 macro, \member{tp_traverse} handlers look like:
1759 my_traverse(Noddy *self, visitproc visit, void *arg)
1761 Py_VISIT(self->foo);
1762 Py_VISIT(self->bar);
1771 The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
1772 \NULL{} if the object is immutable.
1774 \begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
1775 Drop references that may have created reference cycles. Immutable
1776 objects do not have to define this method since they can never
1777 directly create reference cycles. Note that the object must still
1778 be valid after calling this method (don't just call
1779 \cfunction{Py_DECREF()} on a reference). The collector will call
1780 this method if it detects that this object is involved in a