8 Perhaps one of the most important structures of the Python object system is the
9 structure that defines a new type: the :ctype:`PyTypeObject` structure. Type
10 objects can be handled using any of the :cfunc:`PyObject_\*` or
11 :cfunc:`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.
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
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
28 The structure definition for :ctype:`PyTypeObject` can be found in
29 :file:`Include/object.h`. For convenience of reference, this repeats the
30 definition found there:
32 .. literalinclude:: ../includes/typestruct.h
35 The type object structure extends the :ctype:`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 :cdata:`PyType_Type` (the
38 metatype) initializes :attr:`tp_itemsize`, which means that its instances (i.e.
39 type objects) *must* have the :attr:`ob_size` field.
42 .. cmember:: PyObject* PyObject._ob_next
43 PyObject* PyObject._ob_prev
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.
54 These fields are not inherited by subtypes.
57 .. cmember:: Py_ssize_t PyObject.ob_refcnt
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.
65 This field is not inherited by subtypes.
68 .. cmember:: PyTypeObject* PyObject.ob_type
70 This is the type's type, in other words its metatype. It is initialized by the
71 argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be
72 ``&PyType_Type``. However, for dynamically loadable extension modules that must
73 be usable on Windows (at least), the compiler complains that this is not a valid
74 initializer. Therefore, the convention is to pass *NULL* to the
75 ``PyObject_HEAD_INIT`` macro and to initialize this field explicitly at the
76 start of the module's initialization function, before doing anything else. This
77 is typically done like this::
79 Foo_Type.ob_type = &PyType_Type;
81 This should be done before any instances of the type are created.
82 :cfunc:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so,
83 initializes it: in Python 2.2, it is set to ``&PyType_Type``; in Python 2.2.1
84 and later it is initialized to the :attr:`ob_type` field of the base class.
85 :cfunc:`PyType_Ready` will not change this field if it is non-zero.
87 In Python 2.2, this field is not inherited by subtypes. In 2.2.1, and in 2.3
88 and beyond, it is inherited by subtypes.
91 .. cmember:: Py_ssize_t PyVarObject.ob_size
93 For statically allocated type objects, this should be initialized to zero. For
94 dynamically allocated type objects, this field has a special internal meaning.
96 This field is not inherited by subtypes.
99 .. cmember:: char* PyTypeObject.tp_name
101 Pointer to a NUL-terminated string containing the name of the type. For types
102 that are accessible as module globals, the string should be the full module
103 name, followed by a dot, followed by the type name; for built-in types, it
104 should be just the type name. If the module is a submodule of a package, the
105 full package name is part of the full module name. For example, a type named
106 :class:`T` defined in module :mod:`M` in subpackage :mod:`Q` in package :mod:`P`
107 should have the :attr:`tp_name` initializer ``"P.Q.M.T"``.
109 For dynamically allocated type objects, this should just be the type name, and
110 the module name explicitly stored in the type dict as the value for key
113 For statically allocated type objects, the tp_name field should contain a dot.
114 Everything before the last dot is made accessible as the :attr:`__module__`
115 attribute, and everything after the last dot is made accessible as the
116 :attr:`__name__` attribute.
118 If no dot is present, the entire :attr:`tp_name` field is made accessible as the
119 :attr:`__name__` attribute, and the :attr:`__module__` attribute is undefined
120 (unless explicitly set in the dictionary, as explained above). This means your
121 type will be impossible to pickle.
123 This field is not inherited by subtypes.
126 .. cmember:: Py_ssize_t PyTypeObject.tp_basicsize
127 Py_ssize_t PyTypeObject.tp_itemsize
129 These fields allow calculating the size in bytes of instances of the type.
131 There are two kinds of types: types with fixed-length instances have a zero
132 :attr:`tp_itemsize` field, types with variable-length instances have a non-zero
133 :attr:`tp_itemsize` field. For a type with fixed-length instances, all
134 instances have the same size, given in :attr:`tp_basicsize`.
136 For a type with variable-length instances, the instances must have an
137 :attr:`ob_size` field, and the instance size is :attr:`tp_basicsize` plus N
138 times :attr:`tp_itemsize`, where N is the "length" of the object. The value of
139 N is typically stored in the instance's :attr:`ob_size` field. There are
140 exceptions: for example, long ints use a negative :attr:`ob_size` to indicate a
141 negative number, and N is ``abs(ob_size)`` there. Also, the presence of an
142 :attr:`ob_size` field in the instance layout doesn't mean that the instance
143 structure is variable-length (for example, the structure for the list type has
144 fixed-length instances, yet those instances have a meaningful :attr:`ob_size`
147 The basic size includes the fields in the instance declared by the macro
148 :cmacro:`PyObject_HEAD` or :cmacro:`PyObject_VAR_HEAD` (whichever is used to
149 declare the instance struct) and this in turn includes the :attr:`_ob_prev` and
150 :attr:`_ob_next` fields if they are present. This means that the only correct
151 way to get an initializer for the :attr:`tp_basicsize` is to use the
152 ``sizeof`` operator on the struct used to declare the instance layout.
153 The basic size does not include the GC header size (this is new in Python 2.2;
154 in 2.1 and 2.0, the GC header size was included in :attr:`tp_basicsize`).
156 These fields are inherited separately by subtypes. If the base type has a
157 non-zero :attr:`tp_itemsize`, it is generally not safe to set
158 :attr:`tp_itemsize` to a different non-zero value in a subtype (though this
159 depends on the implementation of the base type).
161 A note about alignment: if the variable items require a particular alignment,
162 this should be taken care of by the value of :attr:`tp_basicsize`. Example:
163 suppose a type implements an array of ``double``. :attr:`tp_itemsize` is
164 ``sizeof(double)``. It is the programmer's responsibility that
165 :attr:`tp_basicsize` is a multiple of ``sizeof(double)`` (assuming this is the
166 alignment requirement for ``double``).
169 .. cmember:: destructor PyTypeObject.tp_dealloc
171 A pointer to the instance destructor function. This function must be defined
172 unless the type guarantees that its instances will never be deallocated (as is
173 the case for the singletons ``None`` and ``Ellipsis``).
175 The destructor function is called by the :cfunc:`Py_DECREF` and
176 :cfunc:`Py_XDECREF` macros when the new reference count is zero. At this point,
177 the instance is still in existence, but there are no references to it. The
178 destructor function should free all references which the instance owns, free all
179 memory buffers owned by the instance (using the freeing function corresponding
180 to the allocation function used to allocate the buffer), and finally (as its
181 last action) call the type's :attr:`tp_free` function. If the type is not
182 subtypable (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is
183 permissible to call the object deallocator directly instead of via
184 :attr:`tp_free`. The object deallocator should be the one used to allocate the
185 instance; this is normally :cfunc:`PyObject_Del` if the instance was allocated
186 using :cfunc:`PyObject_New` or :cfunc:`PyObject_VarNew`, or
187 :cfunc:`PyObject_GC_Del` if the instance was allocated using
188 :cfunc:`PyObject_GC_New` or :cfunc:`PyObject_GC_VarNew`.
190 This field is inherited by subtypes.
193 .. cmember:: printfunc PyTypeObject.tp_print
195 An optional pointer to the instance print function.
197 The print function is only called when the instance is printed to a *real* file;
198 when it is printed to a pseudo-file (like a :class:`StringIO` instance), the
199 instance's :attr:`tp_repr` or :attr:`tp_str` function is called to convert it to
200 a string. These are also called when the type's :attr:`tp_print` field is
201 *NULL*. A type should never implement :attr:`tp_print` in a way that produces
202 different output than :attr:`tp_repr` or :attr:`tp_str` would.
204 The print function is called with the same signature as :cfunc:`PyObject_Print`:
205 ``int tp_print(PyObject *self, FILE *file, int flags)``. The *self* argument is
206 the instance to be printed. The *file* argument is the stdio file to which it
207 is to be printed. The *flags* argument is composed of flag bits. The only flag
208 bit currently defined is :const:`Py_PRINT_RAW`. When the :const:`Py_PRINT_RAW`
209 flag bit is set, the instance should be printed the same way as :attr:`tp_str`
210 would format it; when the :const:`Py_PRINT_RAW` flag bit is clear, the instance
211 should be printed the same was as :attr:`tp_repr` would format it. It should
212 return ``-1`` and set an exception condition when an error occurred during the
215 It is possible that the :attr:`tp_print` field will be deprecated. In any case,
216 it is recommended not to define :attr:`tp_print`, but instead to rely on
217 :attr:`tp_repr` and :attr:`tp_str` for printing.
219 This field is inherited by subtypes.
222 .. cmember:: getattrfunc PyTypeObject.tp_getattr
224 An optional pointer to the get-attribute-string function.
226 This field is deprecated. When it is defined, it should point to a function
227 that acts the same as the :attr:`tp_getattro` function, but taking a C string
228 instead of a Python string object to give the attribute name. The signature is
229 the same as for :cfunc:`PyObject_GetAttrString`.
231 This field is inherited by subtypes together with :attr:`tp_getattro`: a subtype
232 inherits both :attr:`tp_getattr` and :attr:`tp_getattro` from its base type when
233 the subtype's :attr:`tp_getattr` and :attr:`tp_getattro` are both *NULL*.
236 .. cmember:: setattrfunc PyTypeObject.tp_setattr
238 An optional pointer to the set-attribute-string function.
240 This field is deprecated. When it is defined, it should point to a function
241 that acts the same as the :attr:`tp_setattro` function, but taking a C string
242 instead of a Python string object to give the attribute name. The signature is
243 the same as for :cfunc:`PyObject_SetAttrString`.
245 This field is inherited by subtypes together with :attr:`tp_setattro`: a subtype
246 inherits both :attr:`tp_setattr` and :attr:`tp_setattro` from its base type when
247 the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*.
250 .. cmember:: cmpfunc PyTypeObject.tp_compare
252 An optional pointer to the three-way comparison function.
254 The signature is the same as for :cfunc:`PyObject_Compare`. The function should
255 return ``1`` if *self* greater than *other*, ``0`` if *self* is equal to
256 *other*, and ``-1`` if *self* less than *other*. It should return ``-1`` and
257 set an exception condition when an error occurred during the comparison.
259 This field is inherited by subtypes together with :attr:`tp_richcompare` and
260 :attr:`tp_hash`: a subtypes inherits all three of :attr:`tp_compare`,
261 :attr:`tp_richcompare`, and :attr:`tp_hash` when the subtype's
262 :attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*.
265 .. cmember:: reprfunc PyTypeObject.tp_repr
267 .. index:: builtin: repr
269 An optional pointer to a function that implements the built-in function
272 The signature is the same as for :cfunc:`PyObject_Repr`; it must return a string
273 or a Unicode object. Ideally, this function should return a string that, when
274 passed to :func:`eval`, given a suitable environment, returns an object with the
275 same value. If this is not feasible, it should return a string starting with
276 ``'<'`` and ending with ``'>'`` from which both the type and the value of the
277 object can be deduced.
279 When this field is not set, a string of the form ``<%s object at %p>`` is
280 returned, where ``%s`` is replaced by the type name, and ``%p`` by the object's
283 This field is inherited by subtypes.
285 .. cmember:: PyNumberMethods* tp_as_number
287 Pointer to an additional structure that contains fields relevant only to
288 objects which implement the number protocol. These fields are documented in
289 :ref:`number-structs`.
291 The :attr:`tp_as_number` field is not inherited, but the contained fields are
292 inherited individually.
295 .. cmember:: PySequenceMethods* tp_as_sequence
297 Pointer to an additional structure that contains fields relevant only to
298 objects which implement the sequence protocol. These fields are documented
299 in :ref:`sequence-structs`.
301 The :attr:`tp_as_sequence` field is not inherited, but the contained fields
302 are inherited individually.
305 .. cmember:: PyMappingMethods* tp_as_mapping
307 Pointer to an additional structure that contains fields relevant only to
308 objects which implement the mapping protocol. These fields are documented in
309 :ref:`mapping-structs`.
311 The :attr:`tp_as_mapping` field is not inherited, but the contained fields
312 are inherited individually.
315 .. cmember:: hashfunc PyTypeObject.tp_hash
317 .. index:: builtin: hash
319 An optional pointer to a function that implements the built-in function
322 The signature is the same as for :cfunc:`PyObject_Hash`; it must return a C
323 long. The value ``-1`` should not be returned as a normal return value; when an
324 error occurs during the computation of the hash value, the function should set
325 an exception and return ``-1``.
327 When this field is not set, two possibilities exist: if the :attr:`tp_compare`
328 and :attr:`tp_richcompare` fields are both *NULL*, a default hash value based on
329 the object's address is returned; otherwise, a :exc:`TypeError` is raised.
331 This field is inherited by subtypes together with :attr:`tp_richcompare` and
332 :attr:`tp_compare`: a subtypes inherits all three of :attr:`tp_compare`,
333 :attr:`tp_richcompare`, and :attr:`tp_hash`, when the subtype's
334 :attr:`tp_compare`, :attr:`tp_richcompare` and :attr:`tp_hash` are all *NULL*.
337 .. cmember:: ternaryfunc PyTypeObject.tp_call
339 An optional pointer to a function that implements calling the object. This
340 should be *NULL* if the object is not callable. The signature is the same as
341 for :cfunc:`PyObject_Call`.
343 This field is inherited by subtypes.
346 .. cmember:: reprfunc PyTypeObject.tp_str
348 An optional pointer to a function that implements the built-in operation
349 :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the
350 constructor for that type. This constructor calls :cfunc:`PyObject_Str` to do
351 the actual work, and :cfunc:`PyObject_Str` will call this handler.)
353 The signature is the same as for :cfunc:`PyObject_Str`; it must return a string
354 or a Unicode object. This function should return a "friendly" string
355 representation of the object, as this is the representation that will be used by
358 When this field is not set, :cfunc:`PyObject_Repr` is called to return a string
361 This field is inherited by subtypes.
364 .. cmember:: getattrofunc PyTypeObject.tp_getattro
366 An optional pointer to the get-attribute function.
368 The signature is the same as for :cfunc:`PyObject_GetAttr`. It is usually
369 convenient to set this field to :cfunc:`PyObject_GenericGetAttr`, which
370 implements the normal way of looking for object attributes.
372 This field is inherited by subtypes together with :attr:`tp_getattr`: a subtype
373 inherits both :attr:`tp_getattr` and :attr:`tp_getattro` from its base type when
374 the subtype's :attr:`tp_getattr` and :attr:`tp_getattro` are both *NULL*.
377 .. cmember:: setattrofunc PyTypeObject.tp_setattro
379 An optional pointer to the set-attribute function.
381 The signature is the same as for :cfunc:`PyObject_SetAttr`. It is usually
382 convenient to set this field to :cfunc:`PyObject_GenericSetAttr`, which
383 implements the normal way of setting object attributes.
385 This field is inherited by subtypes together with :attr:`tp_setattr`: a subtype
386 inherits both :attr:`tp_setattr` and :attr:`tp_setattro` from its base type when
387 the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*.
390 .. cmember:: PyBufferProcs* PyTypeObject.tp_as_buffer
392 Pointer to an additional structure that contains fields relevant only to objects
393 which implement the buffer interface. These fields are documented in
394 :ref:`buffer-structs`.
396 The :attr:`tp_as_buffer` field is not inherited, but the contained fields are
397 inherited individually.
400 .. cmember:: long PyTypeObject.tp_flags
402 This field is a bit mask of various flags. Some flags indicate variant
403 semantics for certain situations; others are used to indicate that certain
404 fields in the type object (or in the extension structures referenced via
405 :attr:`tp_as_number`, :attr:`tp_as_sequence`, :attr:`tp_as_mapping`, and
406 :attr:`tp_as_buffer`) that were historically not always present are valid; if
407 such a flag bit is clear, the type fields it guards must not be accessed and
408 must be considered to have a zero or *NULL* value instead.
410 Inheritance of this field is complicated. Most flag bits are inherited
411 individually, i.e. if the base type has a flag bit set, the subtype inherits
412 this flag bit. The flag bits that pertain to extension structures are strictly
413 inherited if the extension structure is inherited, i.e. the base type's value of
414 the flag bit is copied into the subtype together with a pointer to the extension
415 structure. The :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with
416 the :attr:`tp_traverse` and :attr:`tp_clear` fields, i.e. if the
417 :const:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the
418 :attr:`tp_traverse` and :attr:`tp_clear` fields in the subtype exist (as
419 indicated by the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit) and have *NULL*
422 The following bit masks are currently defined; these can be ORed together using
423 the ``|`` operator to form the value of the :attr:`tp_flags` field. The macro
424 :cfunc:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and
425 checks whether ``tp->tp_flags & f`` is non-zero.
428 .. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER
430 If this bit is set, the :ctype:`PyBufferProcs` struct referenced by
431 :attr:`tp_as_buffer` has the :attr:`bf_getcharbuffer` field.
434 .. data:: Py_TPFLAGS_HAVE_SEQUENCE_IN
436 If this bit is set, the :ctype:`PySequenceMethods` struct referenced by
437 :attr:`tp_as_sequence` has the :attr:`sq_contains` field.
440 .. data:: Py_TPFLAGS_GC
442 This bit is obsolete. The bit it used to name is no longer in use. The symbol
443 is now defined as zero.
446 .. data:: Py_TPFLAGS_HAVE_INPLACEOPS
448 If this bit is set, the :ctype:`PySequenceMethods` struct referenced by
449 :attr:`tp_as_sequence` and the :ctype:`PyNumberMethods` structure referenced by
450 :attr:`tp_as_number` contain the fields for in-place operators. In particular,
451 this means that the :ctype:`PyNumberMethods` structure has the fields
452 :attr:`nb_inplace_add`, :attr:`nb_inplace_subtract`,
453 :attr:`nb_inplace_multiply`, :attr:`nb_inplace_divide`,
454 :attr:`nb_inplace_remainder`, :attr:`nb_inplace_power`,
455 :attr:`nb_inplace_lshift`, :attr:`nb_inplace_rshift`, :attr:`nb_inplace_and`,
456 :attr:`nb_inplace_xor`, and :attr:`nb_inplace_or`; and the
457 :ctype:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and
458 :attr:`sq_inplace_repeat`.
461 .. data:: Py_TPFLAGS_CHECKTYPES
463 If this bit is set, the binary and ternary operations in the
464 :ctype:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept
465 arguments of arbitrary object types, and do their own type conversions if
466 needed. If this bit is clear, those operations require that all arguments have
467 the current type as their type, and the caller is supposed to perform a coercion
468 operation first. This applies to :attr:`nb_add`, :attr:`nb_subtract`,
469 :attr:`nb_multiply`, :attr:`nb_divide`, :attr:`nb_remainder`, :attr:`nb_divmod`,
470 :attr:`nb_power`, :attr:`nb_lshift`, :attr:`nb_rshift`, :attr:`nb_and`,
471 :attr:`nb_xor`, and :attr:`nb_or`.
474 .. data:: Py_TPFLAGS_HAVE_RICHCOMPARE
476 If this bit is set, the type object has the :attr:`tp_richcompare` field, as
477 well as the :attr:`tp_traverse` and the :attr:`tp_clear` fields.
480 .. data:: Py_TPFLAGS_HAVE_WEAKREFS
482 If this bit is set, the :attr:`tp_weaklistoffset` field is defined. Instances
483 of a type are weakly referenceable if the type's :attr:`tp_weaklistoffset` field
484 has a value greater than zero.
487 .. data:: Py_TPFLAGS_HAVE_ITER
489 If this bit is set, the type object has the :attr:`tp_iter` and
490 :attr:`tp_iternext` fields.
493 .. data:: Py_TPFLAGS_HAVE_CLASS
495 If this bit is set, the type object has several new fields defined starting in
496 Python 2.2: :attr:`tp_methods`, :attr:`tp_members`, :attr:`tp_getset`,
497 :attr:`tp_base`, :attr:`tp_dict`, :attr:`tp_descr_get`, :attr:`tp_descr_set`,
498 :attr:`tp_dictoffset`, :attr:`tp_init`, :attr:`tp_alloc`, :attr:`tp_new`,
499 :attr:`tp_free`, :attr:`tp_is_gc`, :attr:`tp_bases`, :attr:`tp_mro`,
500 :attr:`tp_cache`, :attr:`tp_subclasses`, and :attr:`tp_weaklist`.
503 .. data:: Py_TPFLAGS_HEAPTYPE
505 This bit is set when the type object itself is allocated on the heap. In this
506 case, the :attr:`ob_type` field of its instances is considered a reference to
507 the type, and the type object is INCREF'ed when a new instance is created, and
508 DECREF'ed when an instance is destroyed (this does not apply to instances of
509 subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or
513 .. data:: Py_TPFLAGS_BASETYPE
515 This bit is set when the type can be used as the base type of another type. If
516 this bit is clear, the type cannot be subtyped (similar to a "final" class in
520 .. data:: Py_TPFLAGS_READY
522 This bit is set when the type object has been fully initialized by
523 :cfunc:`PyType_Ready`.
526 .. data:: Py_TPFLAGS_READYING
528 This bit is set while :cfunc:`PyType_Ready` is in the process of initializing
532 .. data:: Py_TPFLAGS_HAVE_GC
534 This bit is set when the object supports garbage collection. If this bit
535 is set, instances must be created using :cfunc:`PyObject_GC_New` and
536 destroyed using :cfunc:`PyObject_GC_Del`. More information in section
537 :ref:`supporting-cycle-detection`. This bit also implies that the
538 GC-related fields :attr:`tp_traverse` and :attr:`tp_clear` are present in
539 the type object; but those fields also exist when
540 :const:`Py_TPFLAGS_HAVE_GC` is clear but
541 :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` is set.
544 .. data:: Py_TPFLAGS_DEFAULT
546 This is a bitmask of all the bits that pertain to the existence of certain
547 fields in the type object and its extension structures. Currently, it includes
548 the following bits: :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`,
549 :const:`Py_TPFLAGS_HAVE_SEQUENCE_IN`, :const:`Py_TPFLAGS_HAVE_INPLACEOPS`,
550 :const:`Py_TPFLAGS_HAVE_RICHCOMPARE`, :const:`Py_TPFLAGS_HAVE_WEAKREFS`,
551 :const:`Py_TPFLAGS_HAVE_ITER`, and :const:`Py_TPFLAGS_HAVE_CLASS`.
554 .. cmember:: char* PyTypeObject.tp_doc
556 An optional pointer to a NUL-terminated C string giving the docstring for this
557 type object. This is exposed as the :attr:`__doc__` attribute on the type and
558 instances of the type.
560 This field is *not* inherited by subtypes.
562 The following three fields only exist if the
563 :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit is set.
566 .. cmember:: traverseproc PyTypeObject.tp_traverse
568 An optional pointer to a traversal function for the garbage collector. This is
569 only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. More information
570 about Python's garbage collection scheme can be found in section
571 :ref:`supporting-cycle-detection`.
573 The :attr:`tp_traverse` pointer is used by the garbage collector to detect
574 reference cycles. A typical implementation of a :attr:`tp_traverse` function
575 simply calls :cfunc:`Py_VISIT` on each of the instance's members that are Python
576 objects. For example, this is function :cfunc:`local_traverse` from the
577 :mod:`thread` extension module::
580 local_traverse(localobject *self, visitproc visit, void *arg)
582 Py_VISIT(self->args);
584 Py_VISIT(self->dict);
588 Note that :cfunc:`Py_VISIT` is called only on those members that can participate
589 in reference cycles. Although there is also a ``self->key`` member, it can only
590 be *NULL* or a Python string and therefore cannot be part of a reference cycle.
592 On the other hand, even if you know a member can never be part of a cycle, as a
593 debugging aid you may want to visit it anyway just so the :mod:`gc` module's
594 :func:`get_referents` function will include it.
596 Note that :cfunc:`Py_VISIT` requires the *visit* and *arg* parameters to
597 :cfunc:`local_traverse` to have these specific names; don't name them just
600 This field is inherited by subtypes together with :attr:`tp_clear` and the
601 :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :attr:`tp_traverse`, and
602 :attr:`tp_clear` are all inherited from the base type if they are all zero in
603 the subtype *and* the subtype has the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag
607 .. cmember:: inquiry PyTypeObject.tp_clear
609 An optional pointer to a clear function for the garbage collector. This is only
610 used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set.
612 The :attr:`tp_clear` member function is used to break reference cycles in cyclic
613 garbage detected by the garbage collector. Taken together, all :attr:`tp_clear`
614 functions in the system must combine to break all reference cycles. This is
615 subtle, and if in any doubt supply a :attr:`tp_clear` function. For example,
616 the tuple type does not implement a :attr:`tp_clear` function, because it's
617 possible to prove that no reference cycle can be composed entirely of tuples.
618 Therefore the :attr:`tp_clear` functions of other types must be sufficient to
619 break any cycle containing a tuple. This isn't immediately obvious, and there's
620 rarely a good reason to avoid implementing :attr:`tp_clear`.
622 Implementations of :attr:`tp_clear` should drop the instance's references to
623 those of its members that may be Python objects, and set its pointers to those
624 members to *NULL*, as in the following example::
627 local_clear(localobject *self)
630 Py_CLEAR(self->args);
632 Py_CLEAR(self->dict);
636 The :cfunc:`Py_CLEAR` macro should be used, because clearing references is
637 delicate: the reference to the contained object must not be decremented until
638 after the pointer to the contained object is set to *NULL*. This is because
639 decrementing the reference count may cause the contained object to become trash,
640 triggering a chain of reclamation activity that may include invoking arbitrary
641 Python code (due to finalizers, or weakref callbacks, associated with the
642 contained object). If it's possible for such code to reference *self* again,
643 it's important that the pointer to the contained object be *NULL* at that time,
644 so that *self* knows the contained object can no longer be used. The
645 :cfunc:`Py_CLEAR` macro performs the operations in a safe order.
647 Because the goal of :attr:`tp_clear` functions is to break reference cycles,
648 it's not necessary to clear contained objects like Python strings or Python
649 integers, which can't participate in reference cycles. On the other hand, it may
650 be convenient to clear all contained Python objects, and write the type's
651 :attr:`tp_dealloc` function to invoke :attr:`tp_clear`.
653 More information about Python's garbage collection scheme can be found in
654 section :ref:`supporting-cycle-detection`.
656 This field is inherited by subtypes together with :attr:`tp_traverse` and the
657 :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :attr:`tp_traverse`, and
658 :attr:`tp_clear` are all inherited from the base type if they are all zero in
659 the subtype *and* the subtype has the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag
663 .. cmember:: richcmpfunc PyTypeObject.tp_richcompare
665 An optional pointer to the rich comparison function, whose signature is
666 ``PyObject *tp_richcompare(PyObject *a, PyObject *b, int op)``.
668 The function should return the result of the comparison (usually ``Py_True``
669 or ``Py_False``). If the comparison is undefined, it must return
670 ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and
671 set an exception condition.
675 If you want to implement a type for which only a limited set of
676 comparisons makes sense (e.g. ``==`` and ``!=``, but not ``<`` and
677 friends), directly raise :exc:`TypeError` in the rich comparison function.
679 This field is inherited by subtypes together with :attr:`tp_compare` and
680 :attr:`tp_hash`: a subtype inherits all three of :attr:`tp_compare`,
681 :attr:`tp_richcompare`, and :attr:`tp_hash`, when the subtype's
682 :attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*.
684 The following constants are defined to be used as the third argument for
685 :attr:`tp_richcompare` and for :cfunc:`PyObject_RichCompare`:
687 +----------------+------------+
688 | Constant | Comparison |
689 +================+============+
690 | :const:`Py_LT` | ``<`` |
691 +----------------+------------+
692 | :const:`Py_LE` | ``<=`` |
693 +----------------+------------+
694 | :const:`Py_EQ` | ``==`` |
695 +----------------+------------+
696 | :const:`Py_NE` | ``!=`` |
697 +----------------+------------+
698 | :const:`Py_GT` | ``>`` |
699 +----------------+------------+
700 | :const:`Py_GE` | ``>=`` |
701 +----------------+------------+
704 The next field only exists if the :const:`Py_TPFLAGS_HAVE_WEAKREFS` flag bit is
707 .. cmember:: long PyTypeObject.tp_weaklistoffset
709 If the instances of this type are weakly referenceable, this field is greater
710 than zero and contains the offset in the instance structure of the weak
711 reference list head (ignoring the GC header, if present); this offset is used by
712 :cfunc:`PyObject_ClearWeakRefs` and the :cfunc:`PyWeakref_\*` functions. The
713 instance structure needs to include a field of type :ctype:`PyObject\*` which is
714 initialized to *NULL*.
716 Do not confuse this field with :attr:`tp_weaklist`; that is the list head for
717 weak references to the type object itself.
719 This field is inherited by subtypes, but see the rules listed below. A subtype
720 may override this offset; this means that the subtype uses a different weak
721 reference list head than the base type. Since the list head is always found via
722 :attr:`tp_weaklistoffset`, this should not be a problem.
724 When a type defined by a class statement has no :attr:`__slots__` declaration,
725 and none of its base types are weakly referenceable, the type is made weakly
726 referenceable by adding a weak reference list head slot to the instance layout
727 and setting the :attr:`tp_weaklistoffset` of that slot's offset.
729 When a type's :attr:`__slots__` declaration contains a slot named
730 :attr:`__weakref__`, that slot becomes the weak reference list head for
731 instances of the type, and the slot's offset is stored in the type's
732 :attr:`tp_weaklistoffset`.
734 When a type's :attr:`__slots__` declaration does not contain a slot named
735 :attr:`__weakref__`, the type inherits its :attr:`tp_weaklistoffset` from its
738 The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_CLASS` flag bit is
742 .. cmember:: getiterfunc PyTypeObject.tp_iter
744 An optional pointer to a function that returns an iterator for the object. Its
745 presence normally signals that the instances of this type are iterable (although
746 sequences may be iterable without this function, and classic instances always
747 have this function, even if they don't define an :meth:`__iter__` method).
749 This function has the same signature as :cfunc:`PyObject_GetIter`.
751 This field is inherited by subtypes.
754 .. cmember:: iternextfunc PyTypeObject.tp_iternext
756 An optional pointer to a function that returns the next item in an iterator.
757 When the iterator is exhausted, it must return *NULL*; a :exc:`StopIteration`
758 exception may or may not be set. When another error occurs, it must return
759 *NULL* too. Its presence normally signals that the instances of this type
760 are iterators (although classic instances always have this function, even if
761 they don't define a :meth:`next` method).
763 Iterator types should also define the :attr:`tp_iter` function, and that
764 function should return the iterator instance itself (not a new iterator
767 This function has the same signature as :cfunc:`PyIter_Next`.
769 This field is inherited by subtypes.
771 The next fields, up to and including :attr:`tp_weaklist`, only exist if the
772 :const:`Py_TPFLAGS_HAVE_CLASS` flag bit is set.
775 .. cmember:: struct PyMethodDef* PyTypeObject.tp_methods
777 An optional pointer to a static *NULL*-terminated array of :ctype:`PyMethodDef`
778 structures, declaring regular methods of this type.
780 For each entry in the array, an entry is added to the type's dictionary (see
781 :attr:`tp_dict` below) containing a method descriptor.
783 This field is not inherited by subtypes (methods are inherited through a
784 different mechanism).
787 .. cmember:: struct PyMemberDef* PyTypeObject.tp_members
789 An optional pointer to a static *NULL*-terminated array of :ctype:`PyMemberDef`
790 structures, declaring regular data members (fields or slots) of instances of
793 For each entry in the array, an entry is added to the type's dictionary (see
794 :attr:`tp_dict` below) containing a member descriptor.
796 This field is not inherited by subtypes (members are inherited through a
797 different mechanism).
800 .. cmember:: struct PyGetSetDef* PyTypeObject.tp_getset
802 An optional pointer to a static *NULL*-terminated array of :ctype:`PyGetSetDef`
803 structures, declaring computed attributes of instances of this type.
805 For each entry in the array, an entry is added to the type's dictionary (see
806 :attr:`tp_dict` below) containing a getset descriptor.
808 This field is not inherited by subtypes (computed attributes are inherited
809 through a different mechanism).
811 Docs for PyGetSetDef (XXX belong elsewhere)::
813 typedef PyObject *(*getter)(PyObject *, void *);
814 typedef int (*setter)(PyObject *, PyObject *, void *);
816 typedef struct PyGetSetDef {
817 char *name; /* attribute name */
818 getter get; /* C function to get the attribute */
819 setter set; /* C function to set the attribute */
820 char *doc; /* optional doc string */
821 void *closure; /* optional additional data for getter and setter */
825 .. cmember:: PyTypeObject* PyTypeObject.tp_base
827 An optional pointer to a base type from which type properties are inherited. At
828 this level, only single inheritance is supported; multiple inheritance require
829 dynamically creating a type object by calling the metatype.
831 This field is not inherited by subtypes (obviously), but it defaults to
832 ``&PyBaseObject_Type`` (which to Python programmers is known as the type
836 .. cmember:: PyObject* PyTypeObject.tp_dict
838 The type's dictionary is stored here by :cfunc:`PyType_Ready`.
840 This field should normally be initialized to *NULL* before PyType_Ready is
841 called; it may also be initialized to a dictionary containing initial attributes
842 for the type. Once :cfunc:`PyType_Ready` has initialized the type, extra
843 attributes for the type may be added to this dictionary only if they don't
844 correspond to overloaded operations (like :meth:`__add__`).
846 This field is not inherited by subtypes (though the attributes defined in here
847 are inherited through a different mechanism).
850 .. cmember:: descrgetfunc PyTypeObject.tp_descr_get
852 An optional pointer to a "descriptor get" function.
854 The function signature is ::
856 PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
860 This field is inherited by subtypes.
863 .. cmember:: descrsetfunc PyTypeObject.tp_descr_set
865 An optional pointer to a "descriptor set" function.
867 The function signature is ::
869 int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
871 This field is inherited by subtypes.
876 .. cmember:: long PyTypeObject.tp_dictoffset
878 If the instances of this type have a dictionary containing instance variables,
879 this field is non-zero and contains the offset in the instances of the type of
880 the instance variable dictionary; this offset is used by
881 :cfunc:`PyObject_GenericGetAttr`.
883 Do not confuse this field with :attr:`tp_dict`; that is the dictionary for
884 attributes of the type object itself.
886 If the value of this field is greater than zero, it specifies the offset from
887 the start of the instance structure. If the value is less than zero, it
888 specifies the offset from the *end* of the instance structure. A negative
889 offset is more expensive to use, and should only be used when the instance
890 structure contains a variable-length part. This is used for example to add an
891 instance variable dictionary to subtypes of :class:`str` or :class:`tuple`. Note
892 that the :attr:`tp_basicsize` field should account for the dictionary added to
893 the end in that case, even though the dictionary is not included in the basic
894 object layout. On a system with a pointer size of 4 bytes,
895 :attr:`tp_dictoffset` should be set to ``-4`` to indicate that the dictionary is
896 at the very end of the structure.
898 The real dictionary offset in an instance can be computed from a negative
899 :attr:`tp_dictoffset` as follows::
901 dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
902 if dictoffset is not aligned on sizeof(void*):
903 round up to sizeof(void*)
905 where :attr:`tp_basicsize`, :attr:`tp_itemsize` and :attr:`tp_dictoffset` are
906 taken from the type object, and :attr:`ob_size` is taken from the instance. The
907 absolute value is taken because long ints use the sign of :attr:`ob_size` to
908 store the sign of the number. (There's never a need to do this calculation
909 yourself; it is done for you by :cfunc:`_PyObject_GetDictPtr`.)
911 This field is inherited by subtypes, but see the rules listed below. A subtype
912 may override this offset; this means that the subtype instances store the
913 dictionary at a difference offset than the base type. Since the dictionary is
914 always found via :attr:`tp_dictoffset`, this should not be a problem.
916 When a type defined by a class statement has no :attr:`__slots__` declaration,
917 and none of its base types has an instance variable dictionary, a dictionary
918 slot is added to the instance layout and the :attr:`tp_dictoffset` is set to
921 When a type defined by a class statement has a :attr:`__slots__` declaration,
922 the type inherits its :attr:`tp_dictoffset` from its base type.
924 (Adding a slot named :attr:`__dict__` to the :attr:`__slots__` declaration does
925 not have the expected effect, it just causes confusion. Maybe this should be
926 added as a feature just like :attr:`__weakref__` though.)
929 .. cmember:: initproc PyTypeObject.tp_init
931 An optional pointer to an instance initialization function.
933 This function corresponds to the :meth:`__init__` method of classes. Like
934 :meth:`__init__`, it is possible to create an instance without calling
935 :meth:`__init__`, and it is possible to reinitialize an instance by calling its
936 :meth:`__init__` method again.
938 The function signature is ::
940 int tp_init(PyObject *self, PyObject *args, PyObject *kwds)
942 The self argument is the instance to be initialized; the *args* and *kwds*
943 arguments represent positional and keyword arguments of the call to
946 The :attr:`tp_init` function, if not *NULL*, is called when an instance is
947 created normally by calling its type, after the type's :attr:`tp_new` function
948 has returned an instance of the type. If the :attr:`tp_new` function returns an
949 instance of some other type that is not a subtype of the original type, no
950 :attr:`tp_init` function is called; if :attr:`tp_new` returns an instance of a
951 subtype of the original type, the subtype's :attr:`tp_init` is called. (VERSION
952 NOTE: described here is what is implemented in Python 2.2.1 and later. In
953 Python 2.2, the :attr:`tp_init` of the type of the object returned by
954 :attr:`tp_new` was always called, if not *NULL*.)
956 This field is inherited by subtypes.
959 .. cmember:: allocfunc PyTypeObject.tp_alloc
961 An optional pointer to an instance allocation function.
963 The function signature is ::
965 PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems)
967 The purpose of this function is to separate memory allocation from memory
968 initialization. It should return a pointer to a block of memory of adequate
969 length for the instance, suitably aligned, and initialized to zeros, but with
970 :attr:`ob_refcnt` set to ``1`` and :attr:`ob_type` set to the type argument. If
971 the type's :attr:`tp_itemsize` is non-zero, the object's :attr:`ob_size` field
972 should be initialized to *nitems* and the length of the allocated memory block
973 should be ``tp_basicsize + nitems*tp_itemsize``, rounded up to a multiple of
974 ``sizeof(void*)``; otherwise, *nitems* is not used and the length of the block
975 should be :attr:`tp_basicsize`.
977 Do not use this function to do any other instance initialization, not even to
978 allocate additional memory; that should be done by :attr:`tp_new`.
980 This field is inherited by static subtypes, but not by dynamic subtypes
981 (subtypes created by a class statement); in the latter, this field is always set
982 to :cfunc:`PyType_GenericAlloc`, to force a standard heap allocation strategy.
983 That is also the recommended value for statically defined types.
986 .. cmember:: newfunc PyTypeObject.tp_new
988 An optional pointer to an instance creation function.
990 If this function is *NULL* for a particular type, that type cannot be called to
991 create new instances; presumably there is some other way to create instances,
992 like a factory function.
994 The function signature is ::
996 PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
998 The subtype argument is the type of the object being created; the *args* and
999 *kwds* arguments represent positional and keyword arguments of the call to the
1000 type. Note that subtype doesn't have to equal the type whose :attr:`tp_new`
1001 function is called; it may be a subtype of that type (but not an unrelated
1004 The :attr:`tp_new` function should call ``subtype->tp_alloc(subtype, nitems)``
1005 to allocate space for the object, and then do only as much further
1006 initialization as is absolutely necessary. Initialization that can safely be
1007 ignored or repeated should be placed in the :attr:`tp_init` handler. A good
1008 rule of thumb is that for immutable types, all initialization should take place
1009 in :attr:`tp_new`, while for mutable types, most initialization should be
1010 deferred to :attr:`tp_init`.
1012 This field is inherited by subtypes, except it is not inherited by static types
1013 whose :attr:`tp_base` is *NULL* or ``&PyBaseObject_Type``. The latter exception
1014 is a precaution so that old extension types don't become callable simply by
1015 being linked with Python 2.2.
1018 .. cmember:: destructor PyTypeObject.tp_free
1020 An optional pointer to an instance deallocation function.
1022 The signature of this function has changed slightly: in Python 2.2 and 2.2.1,
1023 its signature is :ctype:`destructor`::
1025 void tp_free(PyObject *)
1027 In Python 2.3 and beyond, its signature is :ctype:`freefunc`::
1029 void tp_free(void *)
1031 The only initializer that is compatible with both versions is ``_PyObject_Del``,
1032 whose definition has suitably adapted in Python 2.3.
1034 This field is inherited by static subtypes, but not by dynamic subtypes
1035 (subtypes created by a class statement); in the latter, this field is set to a
1036 deallocator suitable to match :cfunc:`PyType_GenericAlloc` and the value of the
1037 :const:`Py_TPFLAGS_HAVE_GC` flag bit.
1040 .. cmember:: inquiry PyTypeObject.tp_is_gc
1042 An optional pointer to a function called by the garbage collector.
1044 The garbage collector needs to know whether a particular object is collectible
1045 or not. Normally, it is sufficient to look at the object's type's
1046 :attr:`tp_flags` field, and check the :const:`Py_TPFLAGS_HAVE_GC` flag bit. But
1047 some types have a mixture of statically and dynamically allocated instances, and
1048 the statically allocated instances are not collectible. Such types should
1049 define this function; it should return ``1`` for a collectible instance, and
1050 ``0`` for a non-collectible instance. The signature is ::
1052 int tp_is_gc(PyObject *self)
1054 (The only example of this are types themselves. The metatype,
1055 :cdata:`PyType_Type`, defines this function to distinguish between statically
1056 and dynamically allocated types.)
1058 This field is inherited by subtypes. (VERSION NOTE: in Python 2.2, it was not
1059 inherited. It is inherited in 2.2.1 and later versions.)
1062 .. cmember:: PyObject* PyTypeObject.tp_bases
1064 Tuple of base types.
1066 This is set for types created by a class statement. It should be *NULL* for
1067 statically defined types.
1069 This field is not inherited.
1072 .. cmember:: PyObject* PyTypeObject.tp_mro
1074 Tuple containing the expanded set of base types, starting with the type itself
1075 and ending with :class:`object`, in Method Resolution Order.
1077 This field is not inherited; it is calculated fresh by :cfunc:`PyType_Ready`.
1080 .. cmember:: PyObject* PyTypeObject.tp_cache
1082 Unused. Not inherited. Internal use only.
1085 .. cmember:: PyObject* PyTypeObject.tp_subclasses
1087 List of weak references to subclasses. Not inherited. Internal use only.
1090 .. cmember:: PyObject* PyTypeObject.tp_weaklist
1092 Weak reference list head, for weak references to this type object. Not
1093 inherited. Internal use only.
1095 The remaining fields are only defined if the feature test macro
1096 :const:`COUNT_ALLOCS` is defined, and are for internal use only. They are
1097 documented here for completeness. None of these fields are inherited by
1101 .. cmember:: Py_ssize_t PyTypeObject.tp_allocs
1103 Number of allocations.
1106 .. cmember:: Py_ssize_t PyTypeObject.tp_frees
1111 .. cmember:: Py_ssize_t PyTypeObject.tp_maxalloc
1113 Maximum simultaneously allocated objects.
1116 .. cmember:: PyTypeObject* PyTypeObject.tp_next
1118 Pointer to the next type object with a non-zero :attr:`tp_allocs` field.
1120 Also, note that, in a garbage collected Python, tp_dealloc may be called from
1121 any Python thread, not just the thread which created the object (if the object
1122 becomes part of a refcount cycle, that cycle might be collected by a garbage
1123 collection on any thread). This is not a problem for Python API calls, since
1124 the thread on which tp_dealloc is called will own the Global Interpreter Lock
1125 (GIL). However, if the object being destroyed in turn destroys objects from some
1126 other C or C++ library, care should be taken to ensure that destroying those
1127 objects on the thread which called tp_dealloc will not violate any assumptions
1133 Number Object Structures
1134 ========================
1136 .. sectionauthor:: Amaury Forgeot d'Arc
1139 .. ctype:: PyNumberMethods
1141 This structure holds pointers to the functions which an object uses to
1142 implement the number protocol. Almost every function below is used by the
1143 function of similar name documented in the :ref:`number` section.
1145 Here is the structure definition::
1149 binaryfunc nb_subtract;
1150 binaryfunc nb_multiply;
1151 binaryfunc nb_remainder;
1152 binaryfunc nb_divmod;
1153 ternaryfunc nb_power;
1154 unaryfunc nb_negative;
1155 unaryfunc nb_positive;
1156 unaryfunc nb_absolute;
1157 inquiry nb_nonzero; /* Used by PyObject_IsTrue */
1158 unaryfunc nb_invert;
1159 binaryfunc nb_lshift;
1160 binaryfunc nb_rshift;
1164 coercion nb_coerce; /* Used by the coerce() function */
1171 /* Added in release 2.0 */
1172 binaryfunc nb_inplace_add;
1173 binaryfunc nb_inplace_subtract;
1174 binaryfunc nb_inplace_multiply;
1175 binaryfunc nb_inplace_remainder;
1176 ternaryfunc nb_inplace_power;
1177 binaryfunc nb_inplace_lshift;
1178 binaryfunc nb_inplace_rshift;
1179 binaryfunc nb_inplace_and;
1180 binaryfunc nb_inplace_xor;
1181 binaryfunc nb_inplace_or;
1183 /* Added in release 2.2 */
1184 binaryfunc nb_floor_divide;
1185 binaryfunc nb_true_divide;
1186 binaryfunc nb_inplace_floor_divide;
1187 binaryfunc nb_inplace_true_divide;
1189 /* Added in release 2.5 */
1194 Binary and ternary functions may receive different kinds of arguments, depending
1195 on the flag bit :const:`Py_TPFLAGS_CHECKTYPES`:
1197 - If :const:`Py_TPFLAGS_CHECKTYPES` is not set, the function arguments are
1198 guaranteed to be of the object's type; the caller is responsible for calling
1199 the coercion method specified by the :attr:`nb_coerce` member to convert the
1202 .. cmember:: coercion PyNumberMethods.nb_coerce
1204 This function is used by :cfunc:`PyNumber_CoerceEx` and has the same
1205 signature. The first argument is always a pointer to an object of the
1206 defined type. If the conversion to a common "larger" type is possible, the
1207 function replaces the pointers with new references to the converted objects
1208 and returns ``0``. If the conversion is not possible, the function returns
1209 ``1``. If an error condition is set, it will return ``-1``.
1211 - If the :const:`Py_TPFLAGS_CHECKTYPES` flag is set, binary and ternary
1212 functions must check the type of all their operands, and implement the
1213 necessary conversions (at least one of the operands is an instance of the
1214 defined type). This is the recommended way; with Python 3.0 coercion will
1215 disappear completely.
1217 If the operation is not defined for the given operands, binary and ternary
1218 functions must return ``Py_NotImplemented``, if another error occurred they must
1219 return ``NULL`` and set an exception.
1222 .. _mapping-structs:
1224 Mapping Object Structures
1225 =========================
1227 .. sectionauthor:: Amaury Forgeot d'Arc
1230 .. ctype:: PyMappingMethods
1232 This structure holds pointers to the functions which an object uses to
1233 implement the mapping protocol. It has three members:
1235 .. cmember:: lenfunc PyMappingMethods.mp_length
1237 This function is used by :cfunc:`PyMapping_Length` and
1238 :cfunc:`PyObject_Size`, and has the same signature. This slot may be set to
1239 *NULL* if the object has no defined length.
1241 .. cmember:: binaryfunc PyMappingMethods.mp_subscript
1243 This function is used by :cfunc:`PyObject_GetItem` and has the same
1244 signature. This slot must be filled for the :cfunc:`PyMapping_Check`
1245 function to return ``1``, it can be *NULL* otherwise.
1247 .. cmember:: objobjargproc PyMappingMethods.mp_ass_subscript
1249 This function is used by :cfunc:`PyObject_SetItem` and has the same
1250 signature. If this slot is *NULL*, the object does not support item
1254 .. _sequence-structs:
1256 Sequence Object Structures
1257 ==========================
1259 .. sectionauthor:: Amaury Forgeot d'Arc
1262 .. ctype:: PySequenceMethods
1264 This structure holds pointers to the functions which an object uses to
1265 implement the sequence protocol.
1267 .. cmember:: lenfunc PySequenceMethods.sq_length
1269 This function is used by :cfunc:`PySequence_Size` and :cfunc:`PyObject_Size`,
1270 and has the same signature.
1272 .. cmember:: binaryfunc PySequenceMethods.sq_concat
1274 This function is used by :cfunc:`PySequence_Concat` and has the same
1275 signature. It is also used by the ``+`` operator, after trying the numeric
1276 addition via the :attr:`tp_as_number.nb_add` slot.
1278 .. cmember:: ssizeargfunc PySequenceMethods.sq_repeat
1280 This function is used by :cfunc:`PySequence_Repeat` and has the same
1281 signature. It is also used by the ``*`` operator, after trying numeric
1282 multiplication via the :attr:`tp_as_number.nb_mul` slot.
1284 .. cmember:: ssizeargfunc PySequenceMethods.sq_item
1286 This function is used by :cfunc:`PySequence_GetItem` and has the same
1287 signature. This slot must be filled for the :cfunc:`PySequence_Check`
1288 function to return ``1``, it can be *NULL* otherwise.
1290 Negative indexes are handled as follows: if the :attr:`sq_length` slot is
1291 filled, it is called and the sequence length is used to compute a positive
1292 index which is passed to :attr:`sq_item`. If :attr:`sq_length` is *NULL*,
1293 the index is passed as is to the function.
1295 .. cmember:: ssizeobjargproc PySequenceMethods.sq_ass_item
1297 This function is used by :cfunc:`PySequence_SetItem` and has the same
1298 signature. This slot may be left to *NULL* if the object does not support
1301 .. cmember:: objobjproc PySequenceMethods.sq_contains
1303 This function may be used by :cfunc:`PySequence_Contains` and has the same
1304 signature. This slot may be left to *NULL*, in this case
1305 :cfunc:`PySequence_Contains` simply traverses the sequence until it finds a
1308 .. cmember:: binaryfunc PySequenceMethods.sq_inplace_concat
1310 This function is used by :cfunc:`PySequence_InPlaceConcat` and has the same
1311 signature. It should modify its first operand, and return it.
1313 .. cmember:: ssizeargfunc PySequenceMethods.sq_inplace_repeat
1315 This function is used by :cfunc:`PySequence_InPlaceRepeat` and has the same
1316 signature. It should modify its first operand, and return it.
1318 .. XXX need to explain precedence between mapping and sequence
1319 .. XXX explains when to implement the sq_inplace_* slots
1324 Buffer Object Structures
1325 ========================
1327 .. sectionauthor:: Greg J. Stein <greg@lyra.org>
1330 The buffer interface exports a model where an object can expose its internal
1331 data as a set of chunks of data, where each chunk is specified as a
1332 pointer/length pair. These chunks are called :dfn:`segments` and are presumed
1333 to be non-contiguous in memory.
1335 If an object does not export the buffer interface, then its :attr:`tp_as_buffer`
1336 member in the :ctype:`PyTypeObject` structure should be *NULL*. Otherwise, the
1337 :attr:`tp_as_buffer` will point to a :ctype:`PyBufferProcs` structure.
1341 It is very important that your :ctype:`PyTypeObject` structure uses
1342 :const:`Py_TPFLAGS_DEFAULT` for the value of the :attr:`tp_flags` member rather
1343 than ``0``. This tells the Python runtime that your :ctype:`PyBufferProcs`
1344 structure contains the :attr:`bf_getcharbuffer` slot. Older versions of Python
1345 did not have this member, so a new Python interpreter using an old extension
1346 needs to be able to test for its presence before using it.
1349 .. ctype:: PyBufferProcs
1351 Structure used to hold the function pointers which define an implementation of
1352 the buffer protocol.
1354 The first slot is :attr:`bf_getreadbuffer`, of type :ctype:`getreadbufferproc`.
1355 If this slot is *NULL*, then the object does not support reading from the
1356 internal data. This is non-sensical, so implementors should fill this in, but
1357 callers should test that the slot contains a non-*NULL* value.
1359 The next slot is :attr:`bf_getwritebuffer` having type
1360 :ctype:`getwritebufferproc`. This slot may be *NULL* if the object does not
1361 allow writing into its returned buffers.
1363 The third slot is :attr:`bf_getsegcount`, with type :ctype:`getsegcountproc`.
1364 This slot must not be *NULL* and is used to inform the caller how many segments
1365 the object contains. Simple objects such as :ctype:`PyString_Type` and
1366 :ctype:`PyBuffer_Type` objects contain a single segment.
1368 .. index:: single: PyType_HasFeature()
1370 The last slot is :attr:`bf_getcharbuffer`, of type :ctype:`getcharbufferproc`.
1371 This slot will only be present if the :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`
1372 flag is present in the :attr:`tp_flags` field of the object's
1373 :ctype:`PyTypeObject`. Before using this slot, the caller should test whether it
1374 is present by using the :cfunc:`PyType_HasFeature` function. If the flag is
1375 present, :attr:`bf_getcharbuffer` may be *NULL*, indicating that the object's
1376 contents cannot be used as *8-bit characters*. The slot function may also raise
1377 an error if the object's contents cannot be interpreted as 8-bit characters.
1378 For example, if the object is an array which is configured to hold floating
1379 point values, an exception may be raised if a caller attempts to use
1380 :attr:`bf_getcharbuffer` to fetch a sequence of 8-bit characters. This notion of
1381 exporting the internal buffers as "text" is used to distinguish between objects
1382 that are binary in nature, and those which have character-based content.
1386 The current policy seems to state that these characters may be multi-byte
1387 characters. This implies that a buffer size of *N* does not mean there are *N*
1391 .. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER
1393 Flag bit set in the type structure to indicate that the :attr:`bf_getcharbuffer`
1394 slot is known. This being set does not indicate that the object supports the
1395 buffer interface or that the :attr:`bf_getcharbuffer` slot is non-*NULL*.
1398 .. ctype:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
1400 Return a pointer to a readable segment of the buffer in ``*ptrptr``. This
1401 function is allowed to raise an exception, in which case it must return ``-1``.
1402 The *segment* which is specified must be zero or positive, and strictly less
1403 than the number of segments returned by the :attr:`bf_getsegcount` slot
1404 function. On success, it returns the length of the segment, and sets
1405 ``*ptrptr`` to a pointer to that memory.
1408 .. ctype:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
1410 Return a pointer to a writable memory buffer in ``*ptrptr``, and the length of
1411 that segment as the function return value. The memory buffer must correspond to
1412 buffer segment *segment*. Must return ``-1`` and set an exception on error.
1413 :exc:`TypeError` should be raised if the object only supports read-only buffers,
1414 and :exc:`SystemError` should be raised when *segment* specifies a segment that
1417 .. Why doesn't it raise ValueError for this one?
1418 GJS: because you shouldn't be calling it with an invalid
1419 segment. That indicates a blatant programming error in the C code.
1422 .. ctype:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp)
1424 Return the number of memory segments which comprise the buffer. If *lenp* is
1425 not *NULL*, the implementation must report the sum of the sizes (in bytes) of
1426 all segments in ``*lenp``. The function cannot fail.
1429 .. ctype:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, const char **ptrptr)
1431 Return the size of the segment *segment* that *ptrptr* is set to. ``*ptrptr``
1432 is set to the memory buffer. Returns ``-1`` on error.