PageRenderTime 47ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/c-api/typeobj.rst

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