Debian Codegraph @

cpython27/Doc/c-api/typeobj.rst

raw
1 .. highlightlang:: c
2
3 .. _type-structs:
4
5 Type Objects
6 ============
7
8 Perhaps one of the most important structures of the Python object system is the
9 structure that defines a new type: the :c:type:`PyTypeObject` structure. Type
10 objects can be handled using any of the :c:func:`PyObject_\*` or
11 :c:func:`PyType_\*` functions, but do not offer much that's interesting to most
12 Python applications. These objects are fundamental to how objects behave, so
13 they are very important to the interpreter itself and to any extension module
14 that implements new types.
15
16 Type objects are fairly large compared to most of the standard types. The reason
17 for the size is that each type object stores a large number of values, mostly C
18 function pointers, each of which implements a small part of the type's
19 functionality. The fields of the type object are examined in detail in this
20 section. The fields will be described in the order in which they occur in the
21 structure.
22
23 Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
24 intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor,
25 freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc,
26 cmpfunc, reprfunc, hashfunc
27
28 The structure definition for :c:type:`PyTypeObject` can be found in
29 :file:`Include/object.h`. For convenience of reference, this repeats the
30 definition found there:
31
32 .. literalinclude:: ../includes/typestruct.h
33
34
35 The type object structure extends the :c:type:`PyVarObject` structure. The
36 :attr:`ob_size` field is used for dynamic types (created by :func:`type_new`,
37 usually called from a class statement). Note that :c:data:`PyType_Type` (the
38 metatype) initializes :c:member:`~PyTypeObject.tp_itemsize`, which means that its instances (i.e.
39 type objects) *must* have the :attr:`ob_size` field.
40
41
42 .. c:member:: PyObject* PyObject._ob_next
43 PyObject* PyObject._ob_prev
44
45 These fields are only present when the macro ``Py_TRACE_REFS`` is defined.
46 Their initialization to *NULL* is taken care of by the ``PyObject_HEAD_INIT``
47 macro. For statically allocated objects, these fields always remain *NULL*.
48 For dynamically allocated objects, these two fields are used to link the object
49 into a doubly-linked list of *all* live objects on the heap. This could be used
50 for various debugging purposes; currently the only use is to print the objects
51 that are still alive at the end of a run when the environment variable
52 :envvar:`PYTHONDUMPREFS` is set.
53
54 These fields are not inherited by subtypes.
55
56
57 .. c:member:: Py_ssize_t PyObject.ob_refcnt
58
59 This is the type object's reference count, initialized to ``1`` by the
60 ``PyObject_HEAD_INIT`` macro. Note that for statically allocated type objects,
61 the type's instances (objects whose :attr:`ob_type` points back to the type) do
62 *not* count as references. But for dynamically allocated type objects, the
63 instances *do* count as references.
64
65 This field is not inherited by subtypes.
66
67 .. versionchanged:: 2.5
68 This field used to be an :c:type:`int` type. This might require changes
69 in your code for properly supporting 64-bit systems.
70
71
72 .. c:member:: PyTypeObject* PyObject.ob_type
73
74 This is the type's type, in other words its metatype. It is initialized by the
75 argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be
76 ``&PyType_Type``. However, for dynamically loadable extension modules that must
77 be usable on Windows (at least), the compiler complains that this is not a valid
78 initializer. Therefore, the convention is to pass *NULL* to the
79 ``PyObject_HEAD_INIT`` macro and to initialize this field explicitly at the
80 start of the module's initialization function, before doing anything else. This
81 is typically done like this::
82
83 Foo_Type.ob_type = &PyType_Type;
84
85 This should be done before any instances of the type are created.
86 :c:func:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so,
87 initializes it: in Python 2.2, it is set to ``&PyType_Type``; in Python 2.2.1
88 and later it is initialized to the :attr:`ob_type` field of the base class.
89 :c:func:`PyType_Ready` will not change this field if it is non-zero.
90
91 In Python 2.2, this field is not inherited by subtypes. In 2.2.1, and in 2.3
92 and beyond, it is inherited by subtypes.
93
94
95 .. c:member:: Py_ssize_t PyVarObject.ob_size
96
97 For statically allocated type objects, this should be initialized to zero. For
98 dynamically allocated type objects, this field has a special internal meaning.
99
100 This field is not inherited by subtypes.
101
102
103 .. c:member:: char* PyTypeObject.tp_name
104
105 Pointer to a NUL-terminated string containing the name of the type. For types
106 that are accessible as module globals, the string should be the full module
107 name, followed by a dot, followed by the type name; for built-in types, it
108 should be just the type name. If the module is a submodule of a package, the
109 full package name is part of the full module name. For example, a type named
110 :class:`T` defined in module :mod:`M` in subpackage :mod:`Q` in package :mod:`P`
111 should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``.
112
113 For dynamically allocated type objects, this should just be the type name, and
114 the module name explicitly stored in the type dict as the value for key
115 ``'__module__'``.
116
117 For statically allocated type objects, the tp_name field should contain a dot.
118 Everything before the last dot is made accessible as the :attr:`__module__`
119 attribute, and everything after the last dot is made accessible as the
120 :attr:`~definition.__name__` attribute.
121
122 If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the
123 :attr:`~definition.__name__` attribute, and the :attr:`__module__` attribute is undefined
124 (unless explicitly set in the dictionary, as explained above). This means your
125 type will be impossible to pickle. Additionally, it will not be listed in
126 module documentations created with pydoc.
127
128 This field is not inherited by subtypes.
129
130
131 .. c:member:: Py_ssize_t PyTypeObject.tp_basicsize
132 Py_ssize_t PyTypeObject.tp_itemsize
133
134 These fields allow calculating the size in bytes of instances of the type.
135
136 There are two kinds of types: types with fixed-length instances have a zero
137 :c:member:`~PyTypeObject.tp_itemsize` field, types with variable-length instances have a non-zero
138 :c:member:`~PyTypeObject.tp_itemsize` field. For a type with fixed-length instances, all
139 instances have the same size, given in :c:member:`~PyTypeObject.tp_basicsize`.
140
141 For a type with variable-length instances, the instances must have an
142 :attr:`ob_size` field, and the instance size is :c:member:`~PyTypeObject.tp_basicsize` plus N
143 times :c:member:`~PyTypeObject.tp_itemsize`, where N is the "length" of the object. The value of
144 N is typically stored in the instance's :attr:`ob_size` field. There are
145 exceptions: for example, long ints use a negative :attr:`ob_size` to indicate a
146 negative number, and N is ``abs(ob_size)`` there. Also, the presence of an
147 :attr:`ob_size` field in the instance layout doesn't mean that the instance
148 structure is variable-length (for example, the structure for the list type has
149 fixed-length instances, yet those instances have a meaningful :attr:`ob_size`
150 field).
151
152 The basic size includes the fields in the instance declared by the macro
153 :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to
154 declare the instance struct) and this in turn includes the :attr:`_ob_prev` and
155 :attr:`_ob_next` fields if they are present. This means that the only correct
156 way to get an initializer for the :c:member:`~PyTypeObject.tp_basicsize` is to use the
157 ``sizeof`` operator on the struct used to declare the instance layout.
158 The basic size does not include the GC header size (this is new in Python 2.2;
159 in 2.1 and 2.0, the GC header size was included in :c:member:`~PyTypeObject.tp_basicsize`).
160
161 These fields are inherited separately by subtypes. If the base type has a
162 non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is generally not safe to set
163 :c:member:`~PyTypeObject.tp_itemsize` to a different non-zero value in a subtype (though this
164 depends on the implementation of the base type).
165
166 A note about alignment: if the variable items require a particular alignment,
167 this should be taken care of by the value of :c:member:`~PyTypeObject.tp_basicsize`. Example:
168 suppose a type implements an array of ``double``. :c:member:`~PyTypeObject.tp_itemsize` is
169 ``sizeof(double)``. It is the programmer's responsibility that
170 :c:member:`~PyTypeObject.tp_basicsize` is a multiple of ``sizeof(double)`` (assuming this is the
171 alignment requirement for ``double``).
172
173
174 .. c:member:: destructor PyTypeObject.tp_dealloc
175
176 A pointer to the instance destructor function. This function must be defined
177 unless the type guarantees that its instances will never be deallocated (as is
178 the case for the singletons ``None`` and ``Ellipsis``).
179
180 The destructor function is called by the :c:func:`Py_DECREF` and
181 :c:func:`Py_XDECREF` macros when the new reference count is zero. At this point,
182 the instance is still in existence, but there are no references to it. The
183 destructor function should free all references which the instance owns, free all
184 memory buffers owned by the instance (using the freeing function corresponding
185 to the allocation function used to allocate the buffer), and finally (as its
186 last action) call the type's :c:member:`~PyTypeObject.tp_free` function. If the type is not
187 subtypable (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is
188 permissible to call the object deallocator directly instead of via
189 :c:member:`~PyTypeObject.tp_free`. The object deallocator should be the one used to allocate the
190 instance; this is normally :c:func:`PyObject_Del` if the instance was allocated
191 using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or
192 :c:func:`PyObject_GC_Del` if the instance was allocated using
193 :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`.
194
195 This field is inherited by subtypes.
196
197
198 .. c:member:: printfunc PyTypeObject.tp_print
199
200 An optional pointer to the instance print function.
201
202 The print function is only called when the instance is printed to a *real* file;
203 when it is printed to a pseudo-file (like a :class:`~StringIO.StringIO` instance), the
204 instance's :c:member:`~PyTypeObject.tp_repr` or :c:member:`~PyTypeObject.tp_str` function is called to convert it to
205 a string. These are also called when the type's :c:member:`~PyTypeObject.tp_print` field is
206 *NULL*. A type should never implement :c:member:`~PyTypeObject.tp_print` in a way that produces
207 different output than :c:member:`~PyTypeObject.tp_repr` or :c:member:`~PyTypeObject.tp_str` would.
208
209 The print function is called with the same signature as :c:func:`PyObject_Print`:
210 ``int tp_print(PyObject *self, FILE *file, int flags)``. The *self* argument is
211 the instance to be printed. The *file* argument is the stdio file to which it
212 is to be printed. The *flags* argument is composed of flag bits. The only flag
213 bit currently defined is :const:`Py_PRINT_RAW`. When the :const:`Py_PRINT_RAW`
214 flag bit is set, the instance should be printed the same way as :c:member:`~PyTypeObject.tp_str`
215 would format it; when the :const:`Py_PRINT_RAW` flag bit is clear, the instance
216 should be printed the same was as :c:member:`~PyTypeObject.tp_repr` would format it. It should
217 return ``-1`` and set an exception condition when an error occurred during the
218 comparison.
219
220 It is possible that the :c:member:`~PyTypeObject.tp_print` field will be deprecated. In any case,
221 it is recommended not to define :c:member:`~PyTypeObject.tp_print`, but instead to rely on
222 :c:member:`~PyTypeObject.tp_repr` and :c:member:`~PyTypeObject.tp_str` for printing.
223
224 This field is inherited by subtypes.
225
226
227 .. c:member:: getattrfunc PyTypeObject.tp_getattr
228
229 An optional pointer to the get-attribute-string function.
230
231 This field is deprecated. When it is defined, it should point to a function
232 that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string
233 instead of a Python string object to give the attribute name. The signature is ::
234
235 PyObject * tp_getattr(PyObject *o, char *attr_name);
236
237 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattro`: a subtype
238 inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
239 the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both *NULL*.
240
241
242 .. c:member:: setattrfunc PyTypeObject.tp_setattr
243
244 An optional pointer to the function for setting and deleting attributes.
245
246 This field is deprecated. When it is defined, it should point to a function
247 that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string
248 instead of a Python string object to give the attribute name. The signature is ::
249
250 PyObject * tp_setattr(PyObject *o, char *attr_name, PyObject *v);
251
252 The *v* argument is set to *NULL* to delete the attribute.
253 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattro`: a subtype
254 inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
255 the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both *NULL*.
256
257
258 .. c:member:: cmpfunc PyTypeObject.tp_compare
259
260 An optional pointer to the three-way comparison function.
261
262 The signature is the same as for :c:func:`PyObject_Compare`. The function should
263 return ``1`` if *self* greater than *other*, ``0`` if *self* is equal to
264 *other*, and ``-1`` if *self* less than *other*. It should return ``-1`` and
265 set an exception condition when an error occurred during the comparison.
266
267 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_richcompare` and
268 :c:member:`~PyTypeObject.tp_hash`: a subtypes inherits all three of :c:member:`~PyTypeObject.tp_compare`,
269 :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash` when the subtype's
270 :c:member:`~PyTypeObject.tp_compare`, :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash` are all *NULL*.
271
272
273 .. c:member:: reprfunc PyTypeObject.tp_repr
274
275 .. index:: builtin: repr
276
277 An optional pointer to a function that implements the built-in function
278 :func:`repr`.
279
280 The signature is the same as for :c:func:`PyObject_Repr`; it must return a string
281 or a Unicode object. Ideally, this function should return a string that, when
282 passed to :func:`eval`, given a suitable environment, returns an object with the
283 same value. If this is not feasible, it should return a string starting with
284 ``'<'`` and ending with ``'>'`` from which both the type and the value of the
285 object can be deduced.
286
287 When this field is not set, a string of the form ``<%s object at %p>`` is
288 returned, where ``%s`` is replaced by the type name, and ``%p`` by the object's
289 memory address.
290
291 This field is inherited by subtypes.
292
293 .. c:member:: PyNumberMethods* tp_as_number
294
295 Pointer to an additional structure that contains fields relevant only to
296 objects which implement the number protocol. These fields are documented in
297 :ref:`number-structs`.
298
299 The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the contained fields are
300 inherited individually.
301
302
303 .. c:member:: PySequenceMethods* tp_as_sequence
304
305 Pointer to an additional structure that contains fields relevant only to
306 objects which implement the sequence protocol. These fields are documented
307 in :ref:`sequence-structs`.
308
309 The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the contained fields
310 are inherited individually.
311
312
313 .. c:member:: PyMappingMethods* tp_as_mapping
314
315 Pointer to an additional structure that contains fields relevant only to
316 objects which implement the mapping protocol. These fields are documented in
317 :ref:`mapping-structs`.
318
319 The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the contained fields
320 are inherited individually.
321
322
323 .. c:member:: hashfunc PyTypeObject.tp_hash
324
325 .. index:: builtin: hash
326
327 An optional pointer to a function that implements the built-in function
328 :func:`hash`.
329
330 The signature is the same as for :c:func:`PyObject_Hash`; it must return a C
331 long. The value ``-1`` should not be returned as a normal return value; when an
332 error occurs during the computation of the hash value, the function should set
333 an exception and return ``-1``.
334
335 This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to
336 block inheritance of the hash method from a parent type. This is interpreted
337 as the equivalent of ``__hash__ = None`` at the Python level, causing
338 ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note
339 that the converse is also true - setting ``__hash__ = None`` on a class at
340 the Python level will result in the ``tp_hash`` slot being set to
341 :c:func:`PyObject_HashNotImplemented`.
342
343 When this field is not set, two possibilities exist: if the :c:member:`~PyTypeObject.tp_compare`
344 and :c:member:`~PyTypeObject.tp_richcompare` fields are both *NULL*, a default hash value based on
345 the object's address is returned; otherwise, a :exc:`TypeError` is raised.
346
347 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_richcompare` and
348 :c:member:`~PyTypeObject.tp_compare`: a subtypes inherits all three of :c:member:`~PyTypeObject.tp_compare`,
349 :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash`, when the subtype's
350 :c:member:`~PyTypeObject.tp_compare`, :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are all *NULL*.
351
352
353 .. c:member:: ternaryfunc PyTypeObject.tp_call
354
355 An optional pointer to a function that implements calling the object. This
356 should be *NULL* if the object is not callable. The signature is the same as
357 for :c:func:`PyObject_Call`.
358
359 This field is inherited by subtypes.
360
361
362 .. c:member:: reprfunc PyTypeObject.tp_str
363
364 An optional pointer to a function that implements the built-in operation
365 :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the
366 constructor for that type. This constructor calls :c:func:`PyObject_Str` to do
367 the actual work, and :c:func:`PyObject_Str` will call this handler.)
368
369 The signature is the same as for :c:func:`PyObject_Str`; it must return a string
370 or a Unicode object. This function should return a "friendly" string
371 representation of the object, as this is the representation that will be used by
372 the print statement.
373
374 When this field is not set, :c:func:`PyObject_Repr` is called to return a string
375 representation.
376
377 This field is inherited by subtypes.
378
379
380 .. c:member:: getattrofunc PyTypeObject.tp_getattro
381
382 An optional pointer to the get-attribute function.
383
384 The signature is the same as for :c:func:`PyObject_GetAttr`. It is usually
385 convenient to set this field to :c:func:`PyObject_GenericGetAttr`, which
386 implements the normal way of looking for object attributes.
387
388 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattr`: a subtype
389 inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
390 the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both *NULL*.
391
392
393 .. c:member:: setattrofunc PyTypeObject.tp_setattro
394
395 An optional pointer to the function for setting and deleting attributes.
396
397 The signature is the same as for :c:func:`PyObject_SetAttr`, but setting
398 *v* to *NULL* to delete an attribute must be supported. It is usually
399 convenient to set this field to :c:func:`PyObject_GenericSetAttr`, which
400 implements the normal way of setting object attributes.
401
402 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattr`: a subtype
403 inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
404 the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both *NULL*.
405
406
407 .. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer
408
409 Pointer to an additional structure that contains fields relevant only to objects
410 which implement the buffer interface. These fields are documented in
411 :ref:`buffer-structs`.
412
413 The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited, but the contained fields are
414 inherited individually.
415
416
417 .. c:member:: long PyTypeObject.tp_flags
418
419 This field is a bit mask of various flags. Some flags indicate variant
420 semantics for certain situations; others are used to indicate that certain
421 fields in the type object (or in the extension structures referenced via
422 :c:member:`~PyTypeObject.tp_as_number`, :c:member:`~PyTypeObject.tp_as_sequence`, :c:member:`~PyTypeObject.tp_as_mapping`, and
423 :c:member:`~PyTypeObject.tp_as_buffer`) that were historically not always present are valid; if
424 such a flag bit is clear, the type fields it guards must not be accessed and
425 must be considered to have a zero or *NULL* value instead.
426
427 Inheritance of this field is complicated. Most flag bits are inherited
428 individually, i.e. if the base type has a flag bit set, the subtype inherits
429 this flag bit. The flag bits that pertain to extension structures are strictly
430 inherited if the extension structure is inherited, i.e. the base type's value of
431 the flag bit is copied into the subtype together with a pointer to the extension
432 structure. The :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with
433 the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields, i.e. if the
434 :const:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the
435 :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist (as
436 indicated by the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit) and have *NULL*
437 values.
438
439 The following bit masks are currently defined; these can be ORed together using
440 the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field. The macro
441 :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and
442 checks whether ``tp->tp_flags & f`` is non-zero.
443
444
445 .. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER
446
447 If this bit is set, the :c:type:`PyBufferProcs` struct referenced by
448 :c:member:`~PyTypeObject.tp_as_buffer` has the :attr:`bf_getcharbuffer` field.
449
450
451 .. data:: Py_TPFLAGS_HAVE_SEQUENCE_IN
452
453 If this bit is set, the :c:type:`PySequenceMethods` struct referenced by
454 :c:member:`~PyTypeObject.tp_as_sequence` has the :attr:`sq_contains` field.
455
456
457 .. data:: Py_TPFLAGS_GC
458
459 This bit is obsolete. The bit it used to name is no longer in use. The symbol
460 is now defined as zero.
461
462
463 .. data:: Py_TPFLAGS_HAVE_INPLACEOPS
464
465 If this bit is set, the :c:type:`PySequenceMethods` struct referenced by
466 :c:member:`~PyTypeObject.tp_as_sequence` and the :c:type:`PyNumberMethods` structure referenced by
467 :c:member:`~PyTypeObject.tp_as_number` contain the fields for in-place operators. In particular,
468 this means that the :c:type:`PyNumberMethods` structure has the fields
469 :attr:`nb_inplace_add`, :attr:`nb_inplace_subtract`,
470 :attr:`nb_inplace_multiply`, :attr:`nb_inplace_divide`,
471 :attr:`nb_inplace_remainder`, :attr:`nb_inplace_power`,
472 :attr:`nb_inplace_lshift`, :attr:`nb_inplace_rshift`, :attr:`nb_inplace_and`,
473 :attr:`nb_inplace_xor`, and :attr:`nb_inplace_or`; and the
474 :c:type:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and
475 :attr:`sq_inplace_repeat`.
476
477
478 .. data:: Py_TPFLAGS_CHECKTYPES
479
480 If this bit is set, the binary and ternary operations in the
481 :c:type:`PyNumberMethods` structure referenced by :c:member:`~PyTypeObject.tp_as_number` accept
482 arguments of arbitrary object types, and do their own type conversions if
483 needed. If this bit is clear, those operations require that all arguments have
484 the current type as their type, and the caller is supposed to perform a coercion
485 operation first. This applies to :attr:`nb_add`, :attr:`nb_subtract`,
486 :attr:`nb_multiply`, :attr:`nb_divide`, :attr:`nb_remainder`, :attr:`nb_divmod`,
487 :attr:`nb_power`, :attr:`nb_lshift`, :attr:`nb_rshift`, :attr:`nb_and`,
488 :attr:`nb_xor`, and :attr:`nb_or`.
489
490
491 .. data:: Py_TPFLAGS_HAVE_RICHCOMPARE
492
493 If this bit is set, the type object has the :c:member:`~PyTypeObject.tp_richcompare` field, as
494 well as the :c:member:`~PyTypeObject.tp_traverse` and the :c:member:`~PyTypeObject.tp_clear` fields.
495
496
497 .. data:: Py_TPFLAGS_HAVE_WEAKREFS
498
499 If this bit is set, the :c:member:`~PyTypeObject.tp_weaklistoffset` field is defined. Instances
500 of a type are weakly referenceable if the type's :c:member:`~PyTypeObject.tp_weaklistoffset` field
501 has a value greater than zero.
502
503
504 .. data:: Py_TPFLAGS_HAVE_ITER
505
506 If this bit is set, the type object has the :c:member:`~PyTypeObject.tp_iter` and
507 :c:member:`~PyTypeObject.tp_iternext` fields.
508
509
510 .. data:: Py_TPFLAGS_HAVE_CLASS
511
512 If this bit is set, the type object has several new fields defined starting in
513 Python 2.2: :c:member:`~PyTypeObject.tp_methods`, :c:member:`~PyTypeObject.tp_members`, :c:member:`~PyTypeObject.tp_getset`,
514 :c:member:`~PyTypeObject.tp_base`, :c:member:`~PyTypeObject.tp_dict`, :c:member:`~PyTypeObject.tp_descr_get`, :c:member:`~PyTypeObject.tp_descr_set`,
515 :c:member:`~PyTypeObject.tp_dictoffset`, :c:member:`~PyTypeObject.tp_init`, :c:member:`~PyTypeObject.tp_alloc`, :c:member:`~PyTypeObject.tp_new`,
516 :c:member:`~PyTypeObject.tp_free`, :c:member:`~PyTypeObject.tp_is_gc`, :c:member:`~PyTypeObject.tp_bases`, :c:member:`~PyTypeObject.tp_mro`,
517 :c:member:`~PyTypeObject.tp_cache`, :c:member:`~PyTypeObject.tp_subclasses`, and :c:member:`~PyTypeObject.tp_weaklist`.
518
519
520 .. data:: Py_TPFLAGS_HEAPTYPE
521
522 This bit is set when the type object itself is allocated on the heap. In this
523 case, the :attr:`ob_type` field of its instances is considered a reference to
524 the type, and the type object is INCREF'ed when a new instance is created, and
525 DECREF'ed when an instance is destroyed (this does not apply to instances of
526 subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or
527 DECREF'ed).
528
529
530 .. data:: Py_TPFLAGS_BASETYPE
531
532 This bit is set when the type can be used as the base type of another type. If
533 this bit is clear, the type cannot be subtyped (similar to a "final" class in
534 Java).
535
536
537 .. data:: Py_TPFLAGS_READY
538
539 This bit is set when the type object has been fully initialized by
540 :c:func:`PyType_Ready`.
541
542
543 .. data:: Py_TPFLAGS_READYING
544
545 This bit is set while :c:func:`PyType_Ready` is in the process of initializing
546 the type object.
547
548
549 .. data:: Py_TPFLAGS_HAVE_GC
550
551 This bit is set when the object supports garbage collection. If this bit
552 is set, instances must be created using :c:func:`PyObject_GC_New` and
553 destroyed using :c:func:`PyObject_GC_Del`. More information in section
554 :ref:`supporting-cycle-detection`. This bit also implies that the
555 GC-related fields :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` are present in
556 the type object; but those fields also exist when
557 :const:`Py_TPFLAGS_HAVE_GC` is clear but
558 :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` is set.
559
560
561 .. data:: Py_TPFLAGS_DEFAULT
562
563 This is a bitmask of all the bits that pertain to the existence of certain
564 fields in the type object and its extension structures. Currently, it includes
565 the following bits: :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`,
566 :const:`Py_TPFLAGS_HAVE_SEQUENCE_IN`, :const:`Py_TPFLAGS_HAVE_INPLACEOPS`,
567 :const:`Py_TPFLAGS_HAVE_RICHCOMPARE`, :const:`Py_TPFLAGS_HAVE_WEAKREFS`,
568 :const:`Py_TPFLAGS_HAVE_ITER`, and :const:`Py_TPFLAGS_HAVE_CLASS`.
569
570
571 .. c:member:: char* PyTypeObject.tp_doc
572
573 An optional pointer to a NUL-terminated C string giving the docstring for this
574 type object. This is exposed as the :attr:`__doc__` attribute on the type and
575 instances of the type.
576
577 This field is *not* inherited by subtypes.
578
579 The following three fields only exist if the
580 :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit is set.
581
582
583 .. c:member:: traverseproc PyTypeObject.tp_traverse
584
585 An optional pointer to a traversal function for the garbage collector. This is
586 only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. More information
587 about Python's garbage collection scheme can be found in section
588 :ref:`supporting-cycle-detection`.
589
590 The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
591 reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
592 simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
593 objects. For example, this is function :c:func:`local_traverse` from the
594 :mod:`thread` extension module::
595
596 static int
597 local_traverse(localobject *self, visitproc visit, void *arg)
598 {
599 Py_VISIT(self->args);
600 Py_VISIT(self->kw);
601 Py_VISIT(self->dict);
602 return 0;
603 }
604
605 Note that :c:func:`Py_VISIT` is called only on those members that can participate
606 in reference cycles. Although there is also a ``self->key`` member, it can only
607 be *NULL* or a Python string and therefore cannot be part of a reference cycle.
608
609 On the other hand, even if you know a member can never be part of a cycle, as a
610 debugging aid you may want to visit it anyway just so the :mod:`gc` module's
611 :func:`~gc.get_referents` function will include it.
612
613 Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
614 :c:func:`local_traverse` to have these specific names; don't name them just
615 anything.
616
617 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_clear` and the
618 :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
619 :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
620 the subtype *and* the subtype has the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag
621 bit set.
622
623
624 .. c:member:: inquiry PyTypeObject.tp_clear
625
626 An optional pointer to a clear function for the garbage collector. This is only
627 used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set.
628
629 The :c:member:`~PyTypeObject.tp_clear` member function is used to break reference cycles in cyclic
630 garbage detected by the garbage collector. Taken together, all :c:member:`~PyTypeObject.tp_clear`
631 functions in the system must combine to break all reference cycles. This is
632 subtle, and if in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function. For example,
633 the tuple type does not implement a :c:member:`~PyTypeObject.tp_clear` function, because it's
634 possible to prove that no reference cycle can be composed entirely of tuples.
635 Therefore the :c:member:`~PyTypeObject.tp_clear` functions of other types must be sufficient to
636 break any cycle containing a tuple. This isn't immediately obvious, and there's
637 rarely a good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`.
638
639 Implementations of :c:member:`~PyTypeObject.tp_clear` should drop the instance's references to
640 those of its members that may be Python objects, and set its pointers to those
641 members to *NULL*, as in the following example::
642
643 static int
644 local_clear(localobject *self)
645 {
646 Py_CLEAR(self->key);
647 Py_CLEAR(self->args);
648 Py_CLEAR(self->kw);
649 Py_CLEAR(self->dict);
650 return 0;
651 }
652
653 The :c:func:`Py_CLEAR` macro should be used, because clearing references is
654 delicate: the reference to the contained object must not be decremented until
655 after the pointer to the contained object is set to *NULL*. This is because
656 decrementing the reference count may cause the contained object to become trash,
657 triggering a chain of reclamation activity that may include invoking arbitrary
658 Python code (due to finalizers, or weakref callbacks, associated with the
659 contained object). If it's possible for such code to reference *self* again,
660 it's important that the pointer to the contained object be *NULL* at that time,
661 so that *self* knows the contained object can no longer be used. The
662 :c:func:`Py_CLEAR` macro performs the operations in a safe order.
663
664 Because the goal of :c:member:`~PyTypeObject.tp_clear` functions is to break reference cycles,
665 it's not necessary to clear contained objects like Python strings or Python
666 integers, which can't participate in reference cycles. On the other hand, it may
667 be convenient to clear all contained Python objects, and write the type's
668 :c:member:`~PyTypeObject.tp_dealloc` function to invoke :c:member:`~PyTypeObject.tp_clear`.
669
670 More information about Python's garbage collection scheme can be found in
671 section :ref:`supporting-cycle-detection`.
672
673 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_traverse` and the
674 :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
675 :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
676 the subtype *and* the subtype has the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag
677 bit set.
678
679
680 .. c:member:: richcmpfunc PyTypeObject.tp_richcompare
681
682 An optional pointer to the rich comparison function, whose signature is
683 ``PyObject *tp_richcompare(PyObject *a, PyObject *b, int op)``.
684
685 The function should return the result of the comparison (usually ``Py_True``
686 or ``Py_False``). If the comparison is undefined, it must return
687 ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and
688 set an exception condition.
689
690 .. note::
691
692 If you want to implement a type for which only a limited set of
693 comparisons makes sense (e.g. ``==`` and ``!=``, but not ``<`` and
694 friends), directly raise :exc:`TypeError` in the rich comparison function.
695
696 This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_compare` and
697 :c:member:`~PyTypeObject.tp_hash`: a subtype inherits all three of :c:member:`~PyTypeObject.tp_compare`,
698 :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash`, when the subtype's
699 :c:member:`~PyTypeObject.tp_compare`, :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash` are all *NULL*.
700
701 The following constants are defined to be used as the third argument for
702 :c:member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`:
703
704 +----------------+------------+
705 | Constant | Comparison |
706 +================+============+
707 | :const:`Py_LT` | ``<`` |
708 +----------------+------------+
709 | :const:`Py_LE` | ``<=`` |
710 +----------------+------------+
711 | :const:`Py_EQ` | ``==`` |
712 +----------------+------------+
713 | :const:`Py_NE` | ``!=`` |
714 +----------------+------------+
715 | :const:`Py_GT` | ``>`` |
716 +----------------+------------+
717 | :const:`Py_GE` | ``>=`` |
718 +----------------+------------+
719
720
721 The next field only exists if the :const:`Py_TPFLAGS_HAVE_WEAKREFS` flag bit is
722 set.
723
724 .. c:member:: long PyTypeObject.tp_weaklistoffset
725
726 If the instances of this type are weakly referenceable, this field is greater
727 than zero and contains the offset in the instance structure of the weak
728 reference list head (ignoring the GC header, if present); this offset is used by
729 :c:func:`PyObject_ClearWeakRefs` and the :c:func:`PyWeakref_\*` functions. The
730 instance structure needs to include a field of type :c:type:`PyObject\*` which is
731 initialized to *NULL*.
732
733 Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that is the list head for
734 weak references to the type object itself.
735
736 This field is inherited by subtypes, but see the rules listed below. A subtype
737 may override this offset; this means that the subtype uses a different weak
738 reference list head than the base type. Since the list head is always found via
739 :c:member:`~PyTypeObject.tp_weaklistoffset`, this should not be a problem.
740
741 When a type defined by a class statement has no :attr:`~object.__slots__` declaration,
742 and none of its base types are weakly referenceable, the type is made weakly
743 referenceable by adding a weak reference list head slot to the instance layout
744 and setting the :c:member:`~PyTypeObject.tp_weaklistoffset` of that slot's offset.
745
746 When a type's :attr:`__slots__` declaration contains a slot named
747 :attr:`__weakref__`, that slot becomes the weak reference list head for
748 instances of the type, and the slot's offset is stored in the type's
749 :c:member:`~PyTypeObject.tp_weaklistoffset`.
750
751 When a type's :attr:`__slots__` declaration does not contain a slot named
752 :attr:`__weakref__`, the type inherits its :c:member:`~PyTypeObject.tp_weaklistoffset` from its
753 base type.
754
755 The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_ITER` flag bit is
756 set.
757
758
759 .. c:member:: getiterfunc PyTypeObject.tp_iter
760
761 An optional pointer to a function that returns an iterator for the object. Its
762 presence normally signals that the instances of this type are iterable (although
763 sequences may be iterable without this function, and classic instances always
764 have this function, even if they don't define an :meth:`__iter__` method).
765
766 This function has the same signature as :c:func:`PyObject_GetIter`.
767
768 This field is inherited by subtypes.
769
770
771 .. c:member:: iternextfunc PyTypeObject.tp_iternext
772
773 An optional pointer to a function that returns the next item in an iterator.
774 When the iterator is exhausted, it must return *NULL*; a :exc:`StopIteration`
775 exception may or may not be set. When another error occurs, it must return
776 *NULL* too. Its presence normally signals that the instances of this type
777 are iterators (although classic instances always have this function, even if
778 they don't define a :meth:`~iterator.next` method).
779
780 Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` function, and that
781 function should return the iterator instance itself (not a new iterator
782 instance).
783
784 This function has the same signature as :c:func:`PyIter_Next`.
785
786 This field is inherited by subtypes.
787
788 The next fields, up to and including :c:member:`~PyTypeObject.tp_weaklist`, only exist if the
789 :const:`Py_TPFLAGS_HAVE_CLASS` flag bit is set.
790
791
792 .. c:member:: struct PyMethodDef* PyTypeObject.tp_methods
793
794 An optional pointer to a static *NULL*-terminated array of :c:type:`PyMethodDef`
795 structures, declaring regular methods of this type.
796
797 For each entry in the array, an entry is added to the type's dictionary (see
798 :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor.
799
800 This field is not inherited by subtypes (methods are inherited through a
801 different mechanism).
802
803
804 .. c:member:: struct PyMemberDef* PyTypeObject.tp_members
805
806 An optional pointer to a static *NULL*-terminated array of :c:type:`PyMemberDef`
807 structures, declaring regular data members (fields or slots) of instances of
808 this type.
809
810 For each entry in the array, an entry is added to the type's dictionary (see
811 :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor.
812
813 This field is not inherited by subtypes (members are inherited through a
814 different mechanism).
815
816
817 .. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset
818
819 An optional pointer to a static *NULL*-terminated array of :c:type:`PyGetSetDef`
820 structures, declaring computed attributes of instances of this type.
821
822 For each entry in the array, an entry is added to the type's dictionary (see
823 :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor.
824
825 This field is not inherited by subtypes (computed attributes are inherited
826 through a different mechanism).
827
828
829 .. c:member:: PyTypeObject* PyTypeObject.tp_base
830
831 An optional pointer to a base type from which type properties are inherited. At
832 this level, only single inheritance is supported; multiple inheritance require
833 dynamically creating a type object by calling the metatype.
834
835 This field is not inherited by subtypes (obviously), but it defaults to
836 ``&PyBaseObject_Type`` (which to Python programmers is known as the type
837 :class:`object`).
838
839
840 .. c:member:: PyObject* PyTypeObject.tp_dict
841
842 The type's dictionary is stored here by :c:func:`PyType_Ready`.
843
844 This field should normally be initialized to *NULL* before PyType_Ready is
845 called; it may also be initialized to a dictionary containing initial attributes
846 for the type. Once :c:func:`PyType_Ready` has initialized the type, extra
847 attributes for the type may be added to this dictionary only if they don't
848 correspond to overloaded operations (like :meth:`__add__`).
849
850 This field is not inherited by subtypes (though the attributes defined in here
851 are inherited through a different mechanism).
852
853
854 .. c:member:: descrgetfunc PyTypeObject.tp_descr_get
855
856 An optional pointer to a "descriptor get" function.
857
858 The function signature is ::
859
860 PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
861
862 .. XXX explain.
863
864 This field is inherited by subtypes.
865
866
867 .. c:member:: descrsetfunc PyTypeObject.tp_descr_set
868
869 An optional pointer to a function for setting and deleting
870 a descriptor's value.
871
872 The function signature is ::
873
874 int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
875
876 The *value* argument is set to *NULL* to delete the value.
877 This field is inherited by subtypes.
878
879 .. XXX explain.
880
881
882 .. c:member:: long PyTypeObject.tp_dictoffset
883
884 If the instances of this type have a dictionary containing instance variables,
885 this field is non-zero and contains the offset in the instances of the type of
886 the instance variable dictionary; this offset is used by
887 :c:func:`PyObject_GenericGetAttr`.
888
889 Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is the dictionary for
890 attributes of the type object itself.
891
892 If the value of this field is greater than zero, it specifies the offset from
893 the start of the instance structure. If the value is less than zero, it
894 specifies the offset from the *end* of the instance structure. A negative
895 offset is more expensive to use, and should only be used when the instance
896 structure contains a variable-length part. This is used for example to add an
897 instance variable dictionary to subtypes of :class:`str` or :class:`tuple`. Note
898 that the :c:member:`~PyTypeObject.tp_basicsize` field should account for the dictionary added to
899 the end in that case, even though the dictionary is not included in the basic
900 object layout. On a system with a pointer size of 4 bytes,
901 :c:member:`~PyTypeObject.tp_dictoffset` should be set to ``-4`` to indicate that the dictionary is
902 at the very end of the structure.
903
904 The real dictionary offset in an instance can be computed from a negative
905 :c:member:`~PyTypeObject.tp_dictoffset` as follows::
906
907 dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
908 if dictoffset is not aligned on sizeof(void*):
909 round up to sizeof(void*)
910
911 where :c:member:`~PyTypeObject.tp_basicsize`, :c:member:`~PyTypeObject.tp_itemsize` and :c:member:`~PyTypeObject.tp_dictoffset` are
912 taken from the type object, and :attr:`ob_size` is taken from the instance. The
913 absolute value is taken because long ints use the sign of :attr:`ob_size` to
914 store the sign of the number. (There's never a need to do this calculation
915 yourself; it is done for you by :c:func:`_PyObject_GetDictPtr`.)
916
917 This field is inherited by subtypes, but see the rules listed below. A subtype
918 may override this offset; this means that the subtype instances store the
919 dictionary at a difference offset than the base type. Since the dictionary is
920 always found via :c:member:`~PyTypeObject.tp_dictoffset`, this should not be a problem.
921
922 When a type defined by a class statement has no :attr:`~object.__slots__` declaration,
923 and none of its base types has an instance variable dictionary, a dictionary
924 slot is added to the instance layout and the :c:member:`~PyTypeObject.tp_dictoffset` is set to
925 that slot's offset.
926
927 When a type defined by a class statement has a :attr:`__slots__` declaration,
928 the type inherits its :c:member:`~PyTypeObject.tp_dictoffset` from its base type.
929
930 (Adding a slot named :attr:`~object.__dict__` to the :attr:`__slots__` declaration does
931 not have the expected effect, it just causes confusion. Maybe this should be
932 added as a feature just like :attr:`__weakref__` though.)
933
934
935 .. c:member:: initproc PyTypeObject.tp_init
936
937 An optional pointer to an instance initialization function.
938
939 This function corresponds to the :meth:`__init__` method of classes. Like
940 :meth:`__init__`, it is possible to create an instance without calling
941 :meth:`__init__`, and it is possible to reinitialize an instance by calling its
942 :meth:`__init__` method again.
943
944 The function signature is ::
945
946 int tp_init(PyObject *self, PyObject *args, PyObject *kwds)
947
948 The self argument is the instance to be initialized; the *args* and *kwds*
949 arguments represent positional and keyword arguments of the call to
950 :meth:`__init__`.
951
952 The :c:member:`~PyTypeObject.tp_init` function, if not *NULL*, is called when an instance is
953 created normally by calling its type, after the type's :c:member:`~PyTypeObject.tp_new` function
954 has returned an instance of the type. If the :c:member:`~PyTypeObject.tp_new` function returns an
955 instance of some other type that is not a subtype of the original type, no
956 :c:member:`~PyTypeObject.tp_init` function is called; if :c:member:`~PyTypeObject.tp_new` returns an instance of a
957 subtype of the original type, the subtype's :c:member:`~PyTypeObject.tp_init` is called. (VERSION
958 NOTE: described here is what is implemented in Python 2.2.1 and later. In
959 Python 2.2, the :c:member:`~PyTypeObject.tp_init` of the type of the object returned by
960 :c:member:`~PyTypeObject.tp_new` was always called, if not *NULL*.)
961
962 This field is inherited by subtypes.
963
964
965 .. c:member:: allocfunc PyTypeObject.tp_alloc
966
967 An optional pointer to an instance allocation function.
968
969 The function signature is ::
970
971 PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems)
972
973 The purpose of this function is to separate memory allocation from memory
974 initialization. It should return a pointer to a block of memory of adequate
975 length for the instance, suitably aligned, and initialized to zeros, but with
976 :attr:`ob_refcnt` set to ``1`` and :attr:`ob_type` set to the type argument. If
977 the type's :c:member:`~PyTypeObject.tp_itemsize` is non-zero, the object's :attr:`ob_size` field
978 should be initialized to *nitems* and the length of the allocated memory block
979 should be ``tp_basicsize + nitems*tp_itemsize``, rounded up to a multiple of
980 ``sizeof(void*)``; otherwise, *nitems* is not used and the length of the block
981 should be :c:member:`~PyTypeObject.tp_basicsize`.
982
983 Do not use this function to do any other instance initialization, not even to
984 allocate additional memory; that should be done by :c:member:`~PyTypeObject.tp_new`.
985
986 This field is inherited by static subtypes, but not by dynamic subtypes
987 (subtypes created by a class statement); in the latter, this field is always set
988 to :c:func:`PyType_GenericAlloc`, to force a standard heap allocation strategy.
989 That is also the recommended value for statically defined types.
990
991
992 .. c:member:: newfunc PyTypeObject.tp_new
993
994 An optional pointer to an instance creation function.
995
996 If this function is *NULL* for a particular type, that type cannot be called to
997 create new instances; presumably there is some other way to create instances,
998 like a factory function.
999
1000 The function signature is ::
1001
1002 PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
1003
1004 The subtype argument is the type of the object being created; the *args* and
1005 *kwds* arguments represent positional and keyword arguments of the call to the
1006 type. Note that subtype doesn't have to equal the type whose :c:member:`~PyTypeObject.tp_new`
1007 function is called; it may be a subtype of that type (but not an unrelated
1008 type).
1009
1010 The :c:member:`~PyTypeObject.tp_new` function should call ``subtype->tp_alloc(subtype, nitems)``
1011 to allocate space for the object, and then do only as much further
1012 initialization as is absolutely necessary. Initialization that can safely be
1013 ignored or repeated should be placed in the :c:member:`~PyTypeObject.tp_init` handler. A good
1014 rule of thumb is that for immutable types, all initialization should take place
1015 in :c:member:`~PyTypeObject.tp_new`, while for mutable types, most initialization should be
1016 deferred to :c:member:`~PyTypeObject.tp_init`.
1017
1018 This field is inherited by subtypes, except it is not inherited by static types
1019 whose :c:member:`~PyTypeObject.tp_base` is *NULL* or ``&PyBaseObject_Type``. The latter exception
1020 is a precaution so that old extension types don't become callable simply by
1021 being linked with Python 2.2.
1022
1023
1024 .. c:member:: destructor PyTypeObject.tp_free
1025
1026 An optional pointer to an instance deallocation function.
1027
1028 The signature of this function has changed slightly: in Python 2.2 and 2.2.1,
1029 its signature is :c:type:`destructor`::
1030
1031 void tp_free(PyObject *)
1032
1033 In Python 2.3 and beyond, its signature is :c:type:`freefunc`::
1034
1035 void tp_free(void *)
1036
1037 The only initializer that is compatible with both versions is ``_PyObject_Del``,
1038 whose definition has suitably adapted in Python 2.3.
1039
1040 This field is inherited by static subtypes, but not by dynamic subtypes
1041 (subtypes created by a class statement); in the latter, this field is set to a
1042 deallocator suitable to match :c:func:`PyType_GenericAlloc` and the value of the
1043 :const:`Py_TPFLAGS_HAVE_GC` flag bit.
1044
1045
1046 .. c:member:: inquiry PyTypeObject.tp_is_gc
1047
1048 An optional pointer to a function called by the garbage collector.
1049
1050 The garbage collector needs to know whether a particular object is collectible
1051 or not. Normally, it is sufficient to look at the object's type's
1052 :c:member:`~PyTypeObject.tp_flags` field, and check the :const:`Py_TPFLAGS_HAVE_GC` flag bit. But
1053 some types have a mixture of statically and dynamically allocated instances, and
1054 the statically allocated instances are not collectible. Such types should
1055 define this function; it should return ``1`` for a collectible instance, and
1056 ``0`` for a non-collectible instance. The signature is ::
1057
1058 int tp_is_gc(PyObject *self)
1059
1060 (The only example of this are types themselves. The metatype,
1061 :c:data:`PyType_Type`, defines this function to distinguish between statically
1062 and dynamically allocated types.)
1063
1064 This field is inherited by subtypes. (VERSION NOTE: in Python 2.2, it was not
1065 inherited. It is inherited in 2.2.1 and later versions.)
1066
1067
1068 .. c:member:: PyObject* PyTypeObject.tp_bases
1069
1070 Tuple of base types.
1071
1072 This is set for types created by a class statement. It should be *NULL* for
1073 statically defined types.
1074
1075 This field is not inherited.
1076
1077
1078 .. c:member:: PyObject* PyTypeObject.tp_mro
1079
1080 Tuple containing the expanded set of base types, starting with the type itself
1081 and ending with :class:`object`, in Method Resolution Order.
1082
1083 This field is not inherited; it is calculated fresh by :c:func:`PyType_Ready`.
1084
1085
1086 .. c:member:: PyObject* PyTypeObject.tp_cache
1087
1088 Unused. Not inherited. Internal use only.
1089
1090
1091 .. c:member:: PyObject* PyTypeObject.tp_subclasses
1092
1093 List of weak references to subclasses. Not inherited. Internal use only.
1094
1095
1096 .. c:member:: PyObject* PyTypeObject.tp_weaklist
1097
1098 Weak reference list head, for weak references to this type object. Not
1099 inherited. Internal use only.
1100
1101 The remaining fields are only defined if the feature test macro
1102 :const:`COUNT_ALLOCS` is defined, and are for internal use only. They are
1103 documented here for completeness. None of these fields are inherited by
1104 subtypes. See the :envvar:`PYTHONSHOWALLOCCOUNT` environment variable.
1105
1106
1107 .. c:member:: Py_ssize_t PyTypeObject.tp_allocs
1108
1109 Number of allocations.
1110
1111
1112 .. c:member:: Py_ssize_t PyTypeObject.tp_frees
1113
1114 Number of frees.
1115
1116
1117 .. c:member:: Py_ssize_t PyTypeObject.tp_maxalloc
1118
1119 Maximum simultaneously allocated objects.
1120
1121
1122 .. c:member:: PyTypeObject* PyTypeObject.tp_next
1123
1124 Pointer to the next type object with a non-zero :c:member:`~PyTypeObject.tp_allocs` field.
1125
1126 Also, note that, in a garbage collected Python, tp_dealloc may be called from
1127 any Python thread, not just the thread which created the object (if the object
1128 becomes part of a refcount cycle, that cycle might be collected by a garbage
1129 collection on any thread). This is not a problem for Python API calls, since
1130 the thread on which tp_dealloc is called will own the Global Interpreter Lock
1131 (GIL). However, if the object being destroyed in turn destroys objects from some
1132 other C or C++ library, care should be taken to ensure that destroying those
1133 objects on the thread which called tp_dealloc will not violate any assumptions
1134 of the library.
1135
1136
1137 .. _number-structs:
1138
1139 Number Object Structures
1140 ========================
1141
1142 .. sectionauthor:: Amaury Forgeot d'Arc
1143
1144
1145 .. c:type:: PyNumberMethods
1146
1147 This structure holds pointers to the functions which an object uses to
1148 implement the number protocol. Almost every function below is used by the
1149 function of similar name documented in the :ref:`number` section.
1150
1151 Here is the structure definition::
1152
1153 typedef struct {
1154 binaryfunc nb_add;
1155 binaryfunc nb_subtract;
1156 binaryfunc nb_multiply;
1157 binaryfunc nb_divide;
1158 binaryfunc nb_remainder;
1159 binaryfunc nb_divmod;
1160 ternaryfunc nb_power;
1161 unaryfunc nb_negative;
1162 unaryfunc nb_positive;
1163 unaryfunc nb_absolute;
1164 inquiry nb_nonzero; /* Used by PyObject_IsTrue */
1165 unaryfunc nb_invert;
1166 binaryfunc nb_lshift;
1167 binaryfunc nb_rshift;
1168 binaryfunc nb_and;
1169 binaryfunc nb_xor;
1170 binaryfunc nb_or;
1171 coercion nb_coerce; /* Used by the coerce() function */
1172 unaryfunc nb_int;
1173 unaryfunc nb_long;
1174 unaryfunc nb_float;
1175 unaryfunc nb_oct;
1176 unaryfunc nb_hex;
1177
1178 /* Added in release 2.0 */
1179 binaryfunc nb_inplace_add;
1180 binaryfunc nb_inplace_subtract;
1181 binaryfunc nb_inplace_multiply;
1182 binaryfunc nb_inplace_divide;
1183 binaryfunc nb_inplace_remainder;
1184 ternaryfunc nb_inplace_power;
1185 binaryfunc nb_inplace_lshift;
1186 binaryfunc nb_inplace_rshift;
1187 binaryfunc nb_inplace_and;
1188 binaryfunc nb_inplace_xor;
1189 binaryfunc nb_inplace_or;
1190
1191 /* Added in release 2.2 */
1192 binaryfunc nb_floor_divide;
1193 binaryfunc nb_true_divide;
1194 binaryfunc nb_inplace_floor_divide;
1195 binaryfunc nb_inplace_true_divide;
1196
1197 /* Added in release 2.5 */
1198 unaryfunc nb_index;
1199 } PyNumberMethods;
1200
1201
1202 Binary and ternary functions may receive different kinds of arguments, depending
1203 on the flag bit :const:`Py_TPFLAGS_CHECKTYPES`:
1204
1205 - If :const:`Py_TPFLAGS_CHECKTYPES` is not set, the function arguments are
1206 guaranteed to be of the object's type; the caller is responsible for calling
1207 the coercion method specified by the :attr:`nb_coerce` member to convert the
1208 arguments:
1209
1210 .. c:member:: coercion PyNumberMethods.nb_coerce
1211
1212 This function is used by :c:func:`PyNumber_CoerceEx` and has the same
1213 signature. The first argument is always a pointer to an object of the
1214 defined type. If the conversion to a common "larger" type is possible, the
1215 function replaces the pointers with new references to the converted objects
1216 and returns ``0``. If the conversion is not possible, the function returns
1217 ``1``. If an error condition is set, it will return ``-1``.
1218
1219 - If the :const:`Py_TPFLAGS_CHECKTYPES` flag is set, binary and ternary
1220 functions must check the type of all their operands, and implement the
1221 necessary conversions (at least one of the operands is an instance of the
1222 defined type). This is the recommended way; with Python 3 coercion will
1223 disappear completely.
1224
1225 If the operation is not defined for the given operands, binary and ternary
1226 functions must return ``Py_NotImplemented``, if another error occurred they must
1227 return ``NULL`` and set an exception.
1228
1229
1230 .. _mapping-structs:
1231
1232 Mapping Object Structures
1233 =========================
1234
1235 .. sectionauthor:: Amaury Forgeot d'Arc
1236
1237
1238 .. c:type:: PyMappingMethods
1239
1240 This structure holds pointers to the functions which an object uses to
1241 implement the mapping protocol. It has three members:
1242
1243 .. c:member:: lenfunc PyMappingMethods.mp_length
1244
1245 This function is used by :c:func:`PyMapping_Length` and
1246 :c:func:`PyObject_Size`, and has the same signature. This slot may be set to
1247 *NULL* if the object has no defined length.
1248
1249 .. c:member:: binaryfunc PyMappingMethods.mp_subscript
1250
1251 This function is used by :c:func:`PyObject_GetItem` and has the same
1252 signature. This slot must be filled for the :c:func:`PyMapping_Check`
1253 function to return ``1``, it can be *NULL* otherwise.
1254
1255 .. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript
1256
1257 This function is used by :c:func:`PyObject_SetItem` and
1258 :c:func:`PyObject_DelItem`. It has the same signature as
1259 :c:func:`PyObject_SetItem`, but *v* can also be set to *NULL* to delete
1260 an item. If this slot is *NULL*, the object does not support item
1261 assignment and deletion.
1262
1263
1264 .. _sequence-structs:
1265
1266 Sequence Object Structures
1267 ==========================
1268
1269 .. sectionauthor:: Amaury Forgeot d'Arc
1270
1271
1272 .. c:type:: PySequenceMethods
1273
1274 This structure holds pointers to the functions which an object uses to
1275 implement the sequence protocol.
1276
1277 .. c:member:: lenfunc PySequenceMethods.sq_length
1278
1279 This function is used by :c:func:`PySequence_Size` and :c:func:`PyObject_Size`,
1280 and has the same signature.
1281
1282 .. c:member:: binaryfunc PySequenceMethods.sq_concat
1283
1284 This function is used by :c:func:`PySequence_Concat` and has the same
1285 signature. It is also used by the ``+`` operator, after trying the numeric
1286 addition via the :c:member:`~PyTypeObject.tp_as_number.nb_add` slot.
1287
1288 .. c:member:: ssizeargfunc PySequenceMethods.sq_repeat
1289
1290 This function is used by :c:func:`PySequence_Repeat` and has the same
1291 signature. It is also used by the ``*`` operator, after trying numeric
1292 multiplication via the :c:member:`~PyTypeObject.tp_as_number.nb_multiply`
1293 slot.
1294
1295 .. c:member:: ssizeargfunc PySequenceMethods.sq_item
1296
1297 This function is used by :c:func:`PySequence_GetItem` and has the same
1298 signature. This slot must be filled for the :c:func:`PySequence_Check`
1299 function to return ``1``, it can be *NULL* otherwise.
1300
1301 Negative indexes are handled as follows: if the :attr:`sq_length` slot is
1302 filled, it is called and the sequence length is used to compute a positive
1303 index which is passed to :attr:`sq_item`. If :attr:`sq_length` is *NULL*,
1304 the index is passed as is to the function.
1305
1306 .. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item
1307
1308 This function is used by :c:func:`PySequence_SetItem` and has the same
1309 signature. This slot may be left to *NULL* if the object does not support
1310 item assignment and deletion.
1311
1312 .. c:member:: objobjproc PySequenceMethods.sq_contains
1313
1314 This function may be used by :c:func:`PySequence_Contains` and has the same
1315 signature. This slot may be left to *NULL*, in this case
1316 :c:func:`PySequence_Contains` simply traverses the sequence until it finds a
1317 match.
1318
1319 .. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat
1320
1321 This function is used by :c:func:`PySequence_InPlaceConcat` and has the same
1322 signature. It should modify its first operand, and return it.
1323
1324 .. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat
1325
1326 This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same
1327 signature. It should modify its first operand, and return it.
1328
1329 .. XXX need to explain precedence between mapping and sequence
1330 .. XXX explains when to implement the sq_inplace_* slots
1331
1332
1333 .. _buffer-structs:
1334
1335 Buffer Object Structures
1336 ========================
1337
1338 .. sectionauthor:: Greg J. Stein <[email protected]>
1339
1340
1341 The buffer interface exports a model where an object can expose its internal
1342 data as a set of chunks of data, where each chunk is specified as a
1343 pointer/length pair. These chunks are called :dfn:`segments` and are presumed
1344 to be non-contiguous in memory.
1345
1346 If an object does not export the buffer interface, then its :c:member:`~PyTypeObject.tp_as_buffer`
1347 member in the :c:type:`PyTypeObject` structure should be *NULL*. Otherwise, the
1348 :c:member:`~PyTypeObject.tp_as_buffer` will point to a :c:type:`PyBufferProcs` structure.
1349
1350 .. note::
1351
1352 It is very important that your :c:type:`PyTypeObject` structure uses
1353 :const:`Py_TPFLAGS_DEFAULT` for the value of the :c:member:`~PyTypeObject.tp_flags` member rather
1354 than ``0``. This tells the Python runtime that your :c:type:`PyBufferProcs`
1355 structure contains the :attr:`bf_getcharbuffer` slot. Older versions of Python
1356 did not have this member, so a new Python interpreter using an old extension
1357 needs to be able to test for its presence before using it.
1358
1359
1360 .. c:type:: PyBufferProcs
1361
1362 Structure used to hold the function pointers which define an implementation of
1363 the buffer protocol.
1364
1365 The first slot is :attr:`bf_getreadbuffer`, of type :c:type:`readbufferproc`.
1366 If this slot is *NULL*, then the object does not support reading from the
1367 internal data. This is non-sensical, so implementors should fill this in, but
1368 callers should test that the slot contains a non-*NULL* value.
1369
1370 The next slot is :attr:`bf_getwritebuffer` having type
1371 :c:type:`writebufferproc`. This slot may be *NULL* if the object does not
1372 allow writing into its returned buffers.
1373
1374 The third slot is :attr:`bf_getsegcount`, with type :c:type:`segcountproc`.
1375 This slot must not be *NULL* and is used to inform the caller how many segments
1376 the object contains. Simple objects such as :c:type:`PyString_Type` and
1377 :c:type:`PyBuffer_Type` objects contain a single segment.
1378
1379 .. index:: single: PyType_HasFeature()
1380
1381 The last slot is :attr:`bf_getcharbuffer`, of type :c:type:`charbufferproc`.
1382 This slot will only be present if the :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`
1383 flag is present in the :c:member:`~PyTypeObject.tp_flags` field of the object's
1384 :c:type:`PyTypeObject`. Before using this slot, the caller should test whether it
1385 is present by using the :c:func:`PyType_HasFeature` function. If the flag is
1386 present, :attr:`bf_getcharbuffer` may be *NULL*, indicating that the object's
1387 contents cannot be used as *8-bit characters*. The slot function may also raise
1388 an error if the object's contents cannot be interpreted as 8-bit characters.
1389 For example, if the object is an array which is configured to hold floating
1390 point values, an exception may be raised if a caller attempts to use
1391 :attr:`bf_getcharbuffer` to fetch a sequence of 8-bit characters. This notion of
1392 exporting the internal buffers as "text" is used to distinguish between objects
1393 that are binary in nature, and those which have character-based content.
1394
1395 .. note::
1396
1397 The current policy seems to state that these characters may be multi-byte
1398 characters. This implies that a buffer size of *N* does not mean there are *N*
1399 characters present.
1400
1401
1402 .. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER
1403
1404 Flag bit set in the type structure to indicate that the :attr:`bf_getcharbuffer`
1405 slot is known. This being set does not indicate that the object supports the
1406 buffer interface or that the :attr:`bf_getcharbuffer` slot is non-*NULL*.
1407
1408
1409 .. c:type:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
1410
1411 Return a pointer to a readable segment of the buffer in ``*ptrptr``. This
1412 function is allowed to raise an exception, in which case it must return ``-1``.
1413 The *segment* which is specified must be zero or positive, and strictly less
1414 than the number of segments returned by the :attr:`bf_getsegcount` slot
1415 function. On success, it returns the length of the segment, and sets
1416 ``*ptrptr`` to a pointer to that memory.
1417
1418
1419 .. c:type:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
1420
1421 Return a pointer to a writable memory buffer in ``*ptrptr``, and the length of
1422 that segment as the function return value. The memory buffer must correspond to
1423 buffer segment *segment*. Must return ``-1`` and set an exception on error.
1424 :exc:`TypeError` should be raised if the object only supports read-only buffers,
1425 and :exc:`SystemError` should be raised when *segment* specifies a segment that
1426 doesn't exist.
1427
1428 .. Why doesn't it raise ValueError for this one?
1429 GJS: because you shouldn't be calling it with an invalid
1430 segment. That indicates a blatant programming error in the C code.
1431
1432
1433 .. c:type:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp)
1434
1435 Return the number of memory segments which comprise the buffer. If *lenp* is
1436 not *NULL*, the implementation must report the sum of the sizes (in bytes) of
1437 all segments in ``*lenp``. The function cannot fail.
1438
1439
1440 .. c:type:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, char **ptrptr)
1441
1442 Return the size of the segment *segment* that *ptrptr* is set to. ``*ptrptr``
1443 is set to the memory buffer. Returns ``-1`` on error.