Perhaps one of the most important structures of the Python object system is thestructure that defines a new type: thePyTypeObject structure. Typeobjects can be handled using any of thePyObject_*() orPyType_*() functions, but do not offer much that’s interesting to mostPython applications. These objects are fundamental to how objects behave, sothey are very important to the interpreter itself and to any extension modulethat implements new types.
Type objects are fairly large compared to most of the standard types. The reasonfor the size is that each type object stores a large number of values, mostly Cfunction pointers, each of which implements a small part of the type’sfunctionality. The fields of the type object are examined in detail in thissection. The fields will be described in the order in which they occur in thestructure.
Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, intargfunc,intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor,freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc,reprfunc, hashfunc
The structure definition forPyTypeObject can be found inInclude/object.h. For convenience of reference, this repeats thedefinition found there:
typedefstruct_typeobject{PyObject_VAR_HEADchar*tp_name;/* For printing, in format "<module>.<name>" */inttp_basicsize,tp_itemsize;/* For allocation *//* Methods to implement standard operations */destructortp_dealloc;printfunctp_print;getattrfunctp_getattr;setattrfunctp_setattr;void*tp_reserved;reprfunctp_repr;/* Method suites for standard classes */PyNumberMethods*tp_as_number;PySequenceMethods*tp_as_sequence;PyMappingMethods*tp_as_mapping;/* More standard operations (here for binary compatibility) */hashfunctp_hash;ternaryfunctp_call;reprfunctp_str;getattrofunctp_getattro;setattrofunctp_setattro;/* Functions to access object as input/output buffer */PyBufferProcs*tp_as_buffer;/* Flags to define presence of optional/expanded features */longtp_flags;char*tp_doc;/* Documentation string *//* call function for all accessible objects */traverseproctp_traverse;/* delete references to contained objects */inquirytp_clear;/* rich comparisons */richcmpfunctp_richcompare;/* weak reference enabler */longtp_weaklistoffset;/* Iterators */getiterfunctp_iter;iternextfunctp_iternext;/* Attribute descriptor and subclassing stuff */structPyMethodDef*tp_methods;structPyMemberDef*tp_members;structPyGetSetDef*tp_getset;struct_typeobject*tp_base;PyObject*tp_dict;descrgetfunctp_descr_get;descrsetfunctp_descr_set;longtp_dictoffset;initproctp_init;allocfunctp_alloc;newfunctp_new;freefunctp_free;/* Low-level free-memory routine */inquirytp_is_gc;/* For PyObject_IS_GC */PyObject*tp_bases;PyObject*tp_mro;/* method resolution order */PyObject*tp_cache;PyObject*tp_subclasses;PyObject*tp_weaklist;}PyTypeObject;
The type object structure extends thePyVarObject structure. Theob_size field is used for dynamic types (created bytype_new(),usually called from a class statement). Note thatPyType_Type (themetatype) initializestp_itemsize, which means that its instances (i.e.type objects)must have theob_size field.
These fields are only present when the macroPy_TRACE_REFS is defined.Their initialization toNULL is taken care of by thePyObject_HEAD_INITmacro. For statically allocated objects, these fields always remainNULL.For dynamically allocated objects, these two fields are used to link the objectinto a doubly-linked list ofall live objects on the heap. This could be usedfor various debugging purposes; currently the only use is to print the objectsthat are still alive at the end of a run when the environment variablePYTHONDUMPREFS is set.
These fields are not inherited by subtypes.
This is the type object’s reference count, initialized to1 by thePyObject_HEAD_INIT macro. Note that for statically allocated type objects,the type’s instances (objects whoseob_type points back to the type) donot count as references. But for dynamically allocated type objects, theinstancesdo count as references.
This field is not inherited by subtypes.
This is the type’s type, in other words its metatype. It is initialized by theargument to thePyObject_HEAD_INIT macro, and its value should normally be&PyType_Type. However, for dynamically loadable extension modules that mustbe usable on Windows (at least), the compiler complains that this is not a validinitializer. Therefore, the convention is to passNULL to thePyObject_HEAD_INIT macro and to initialize this field explicitly at thestart of the module’s initialization function, before doing anything else. Thisis typically done like this:
Foo_Type.ob_type=&PyType_Type;
This should be done before any instances of the type are created.PyType_Ready() checks ifob_type isNULL, and if so,initializes it to theob_type field of the base class.PyType_Ready() will not change this field if it is non-zero.
This field is inherited by subtypes.
For statically allocated type objects, this should be initialized to zero. Fordynamically allocated type objects, this field has a special internal meaning.
This field is not inherited by subtypes.
Pointer to a NUL-terminated string containing the name of the type. For typesthat are accessible as module globals, the string should be the full modulename, followed by a dot, followed by the type name; for built-in types, itshould be just the type name. If the module is a submodule of a package, thefull package name is part of the full module name. For example, a type namedT defined in moduleM in subpackageQ in packagePshould have thetp_name initializer"P.Q.M.T".
For dynamically allocated type objects, this should just be the type name, andthe module name explicitly stored in the type dict as the value for key'__module__'.
For statically allocated type objects, the tp_name field should contain a dot.Everything before the last dot is made accessible as the__module__attribute, and everything after the last dot is made accessible as the__name__ attribute.
If no dot is present, the entiretp_name field is made accessible as the__name__ attribute, and the__module__ attribute is undefined(unless explicitly set in the dictionary, as explained above). This means yourtype will be impossible to pickle.
This field is not inherited by subtypes.
These fields allow calculating the size in bytes of instances of the type.
There are two kinds of types: types with fixed-length instances have a zerotp_itemsize field, types with variable-length instances have a non-zerotp_itemsize field. For a type with fixed-length instances, allinstances have the same size, given intp_basicsize.
For a type with variable-length instances, the instances must have anob_size field, and the instance size istp_basicsize plus Ntimestp_itemsize, where N is the “length” of the object. The value ofN is typically stored in the instance’sob_size field. There areexceptions: for example, ints use a negativeob_size to indicate anegative number, and N isabs(ob_size) there. Also, the presence of anob_size field in the instance layout doesn’t mean that the instancestructure is variable-length (for example, the structure for the list type hasfixed-length instances, yet those instances have a meaningfulob_sizefield).
The basic size includes the fields in the instance declared by the macroPyObject_HEAD orPyObject_VAR_HEAD (whichever is used todeclare the instance struct) and this in turn includes the_ob_prev and_ob_next fields if they are present. This means that the only correctway to get an initializer for thetp_basicsize is to use thesizeof operator on the struct used to declare the instance layout.The basic size does not include the GC header size.
These fields are inherited separately by subtypes. If the base type has anon-zerotp_itemsize, it is generally not safe to settp_itemsize to a different non-zero value in a subtype (though thisdepends on the implementation of the base type).
A note about alignment: if the variable items require a particular alignment,this should be taken care of by the value oftp_basicsize. Example:suppose a type implements an array ofdouble.tp_itemsize issizeof(double). It is the programmer’s responsibility thattp_basicsize is a multiple ofsizeof(double) (assuming this is thealignment requirement fordouble).
A pointer to the instance destructor function. This function must be definedunless the type guarantees that its instances will never be deallocated (as isthe case for the singletonsNone andEllipsis).
The destructor function is called by thePy_DECREF() andPy_XDECREF() macros when the new reference count is zero. At this point,the instance is still in existence, but there are no references to it. Thedestructor function should free all references which the instance owns, free allmemory buffers owned by the instance (using the freeing function correspondingto the allocation function used to allocate the buffer), and finally (as itslast action) call the type’stp_free function. If the type is notsubtypable (doesn’t have thePy_TPFLAGS_BASETYPE flag bit set), it ispermissible to call the object deallocator directly instead of viatp_free. The object deallocator should be the one used to allocate theinstance; this is normallyPyObject_Del() if the instance was allocatedusingPyObject_New() orPyObject_VarNew(), orPyObject_GC_Del() if the instance was allocated usingPyObject_GC_New() orPyObject_GC_NewVar().
This field is inherited by subtypes.
An optional pointer to the instance print function.
The print function is only called when the instance is printed to areal file;when it is printed to a pseudo-file (like aio.StringIO instance), theinstance’stp_repr ortp_str function is called to convert it toa string. These are also called when the type’stp_print field isNULL. A type should never implementtp_print in a way that producesdifferent output thantp_repr ortp_str would.
The print function is called with the same signature asPyObject_Print():inttp_print(PyObject*self,FILE*file,intflags). Theself argument isthe instance to be printed. Thefile argument is the stdio file to which itis to be printed. Theflags argument is composed of flag bits. The only flagbit currently defined isPy_PRINT_RAW. When thePy_PRINT_RAWflag bit is set, the instance should be printed the same way astp_strwould format it; when thePy_PRINT_RAW flag bit is clear, the instanceshould be printed the same way astp_repr would format it. It shouldreturn-1 and set an exception condition when an error occurs.
It is possible that thetp_print field will be deprecated. In any case,it is recommended not to definetp_print, but instead to rely ontp_repr andtp_str for printing.
This field is inherited by subtypes.
An optional pointer to the get-attribute-string function.
This field is deprecated. When it is defined, it should point to a functionthat acts the same as thetp_getattro function, but taking a C stringinstead of a Python string object to give the attribute name. The signature isthe same as forPyObject_GetAttrString().
This field is inherited by subtypes together withtp_getattro: a subtypeinherits bothtp_getattr andtp_getattro from its base type whenthe subtype’stp_getattr andtp_getattro are bothNULL.
An optional pointer to the set-attribute-string function.
This field is deprecated. When it is defined, it should point to a functionthat acts the same as thetp_setattro function, but taking a C stringinstead of a Python string object to give the attribute name. The signature isthe same as forPyObject_SetAttrString().
This field is inherited by subtypes together withtp_setattro: a subtypeinherits bothtp_setattr andtp_setattro from its base type whenthe subtype’stp_setattr andtp_setattro are bothNULL.
Reserved slot, formerly known as tp_compare.
An optional pointer to a function that implements the built-in functionrepr().
The signature is the same as forPyObject_Repr(); it must return a stringor a Unicode object. Ideally, this function should return a string that, whenpassed toeval(), given a suitable environment, returns an object with thesame value. If this is not feasible, it should return a string starting with'<' and ending with'>' from which both the type and the value of theobject can be deduced.
When this field is not set, a string of the form<%sobjectat%p> isreturned, where%s is replaced by the type name, and%p by the object’smemory address.
This field is inherited by subtypes.
Pointer to an additional structure that contains fields relevant only toobjects which implement the number protocol. These fields are documented inNumber Object Structures.
Thetp_as_number field is not inherited, but the contained fields areinherited individually.
Pointer to an additional structure that contains fields relevant only toobjects which implement the sequence protocol. These fields are documentedinSequence Object Structures.
Thetp_as_sequence field is not inherited, but the contained fieldsare inherited individually.
Pointer to an additional structure that contains fields relevant only toobjects which implement the mapping protocol. These fields are documented inMapping Object Structures.
Thetp_as_mapping field is not inherited, but the contained fieldsare inherited individually.
An optional pointer to a function that implements the built-in functionhash().
The signature is the same as forPyObject_Hash(); it must return avalue of the type Py_hash_t. The value-1 should not be returned as anormal return value; when an error occurs during the computation of the hashvalue, the function should set an exception and return-1.
This field can be set explicitly toPyObject_HashNotImplemented() toblock inheritance of the hash method from a parent type. This is interpretedas the equivalent of__hash__=None at the Python level, causingisinstance(o,collections.Hashable) to correctly returnFalse. Notethat the converse is also true - setting__hash__=None on a class atthe Python level will result in thetp_hash slot being set toPyObject_HashNotImplemented().
When this field is not set, an attempt to take the hash of theobject raisesTypeError.
This field is inherited by subtypes together withtp_richcompare: a subtype inherits both oftp_richcompare andtp_hash, when the subtype’stp_richcompare andtp_hash are bothNULL.
An optional pointer to a function that implements calling the object. Thisshould beNULL if the object is not callable. The signature is the same asforPyObject_Call().
This field is inherited by subtypes.
An optional pointer to a function that implements the built-in operationstr(). (Note thatstr is a type now, andstr() calls theconstructor for that type. This constructor callsPyObject_Str() to dothe actual work, andPyObject_Str() will call this handler.)
The signature is the same as forPyObject_Str(); it must return a stringor a Unicode object. This function should return a “friendly” stringrepresentation of the object, as this is the representation that will be used,among other things, by theprint() function.
When this field is not set,PyObject_Repr() is called to return a stringrepresentation.
This field is inherited by subtypes.
An optional pointer to the get-attribute function.
The signature is the same as forPyObject_GetAttr(). It is usuallyconvenient to set this field toPyObject_GenericGetAttr(), whichimplements the normal way of looking for object attributes.
This field is inherited by subtypes together withtp_getattr: a subtypeinherits bothtp_getattr andtp_getattro from its base type whenthe subtype’stp_getattr andtp_getattro are bothNULL.
An optional pointer to the set-attribute function.
The signature is the same as forPyObject_SetAttr(). It is usuallyconvenient to set this field toPyObject_GenericSetAttr(), whichimplements the normal way of setting object attributes.
This field is inherited by subtypes together withtp_setattr: a subtypeinherits bothtp_setattr andtp_setattro from its base type whenthe subtype’stp_setattr andtp_setattro are bothNULL.
Pointer to an additional structure that contains fields relevant only to objectswhich implement the buffer interface. These fields are documented inBuffer Object Structures.
Thetp_as_buffer field is not inherited, but the contained fields areinherited individually.
This field is a bit mask of various flags. Some flags indicate variantsemantics for certain situations; others are used to indicate that certainfields in the type object (or in the extension structures referenced viatp_as_number,tp_as_sequence,tp_as_mapping, andtp_as_buffer) that were historically not always present are valid; ifsuch a flag bit is clear, the type fields it guards must not be accessed andmust be considered to have a zero orNULL value instead.
Inheritance of this field is complicated. Most flag bits are inheritedindividually, i.e. if the base type has a flag bit set, the subtype inheritsthis flag bit. The flag bits that pertain to extension structures are strictlyinherited if the extension structure is inherited, i.e. the base type’s value ofthe flag bit is copied into the subtype together with a pointer to the extensionstructure. ThePy_TPFLAGS_HAVE_GC flag bit is inherited together withthetp_traverse andtp_clear fields, i.e. if thePy_TPFLAGS_HAVE_GC flag bit is clear in the subtype and thetp_traverse andtp_clear fields in the subtype exist and haveNULL values.
The following bit masks are currently defined; these can be ORed together usingthe| operator to form the value of thetp_flags field. The macroPyType_HasFeature() takes a type and a flags value,tp andf, andchecks whethertp->tp_flags&f is non-zero.
This bit is set when the type object itself is allocated on the heap. In thiscase, theob_type field of its instances is considered a reference tothe type, and the type object is INCREF’ed when a new instance is created, andDECREF’ed when an instance is destroyed (this does not apply to instances ofsubtypes; only the type referenced by the instance’s ob_type gets INCREF’ed orDECREF’ed).
This bit is set when the type can be used as the base type of another type. Ifthis bit is clear, the type cannot be subtyped (similar to a “final” class inJava).
This bit is set when the type object has been fully initialized byPyType_Ready().
This bit is set whilePyType_Ready() is in the process of initializingthe type object.
This bit is set when the object supports garbage collection. If this bitis set, instances must be created usingPyObject_GC_New() anddestroyed usingPyObject_GC_Del(). More information in sectionSupporting Cyclic Garbage Collection. This bit also implies that theGC-related fieldstp_traverse andtp_clear are present inthe type object.
This is a bitmask of all the bits that pertain to the existence of certainfields in the type object and its extension structures. Currently, it includesthe following bits:Py_TPFLAGS_HAVE_STACKLESS_EXTENSION,Py_TPFLAGS_HAVE_VERSION_TAG.
An optional pointer to a NUL-terminated C string giving the docstring for thistype object. This is exposed as the__doc__ attribute on the type andinstances of the type.
This field isnot inherited by subtypes.
An optional pointer to a traversal function for the garbage collector. This isonly used if thePy_TPFLAGS_HAVE_GC flag bit is set. More informationabout Python’s garbage collection scheme can be found in sectionSupporting Cyclic Garbage Collection.
Thetp_traverse pointer is used by the garbage collector to detectreference cycles. A typical implementation of atp_traverse functionsimply callsPy_VISIT() on each of the instance’s members that are Pythonobjects. For example, this is functionlocal_traverse() from the_thread extension module:
staticintlocal_traverse(localobject*self,visitprocvisit,void*arg){Py_VISIT(self->args);Py_VISIT(self->kw);Py_VISIT(self->dict);return0;}
Note thatPy_VISIT() is called only on those members that can participatein reference cycles. Although there is also aself->key member, it can onlybeNULL or a Python string and therefore cannot be part of a reference cycle.
On the other hand, even if you know a member can never be part of a cycle, as adebugging aid you may want to visit it anyway just so thegc module’sget_referents() function will include it.
Note thatPy_VISIT() requires thevisit andarg parameters tolocal_traverse() to have these specific names; don’t name them justanything.
This field is inherited by subtypes together withtp_clear and thePy_TPFLAGS_HAVE_GC flag bit: the flag bit,tp_traverse, andtp_clear are all inherited from the base type if they are all zero inthe subtype.
An optional pointer to a clear function for the garbage collector. This is onlyused if thePy_TPFLAGS_HAVE_GC flag bit is set.
Thetp_clear member function is used to break reference cycles in cyclicgarbage detected by the garbage collector. Taken together, alltp_clearfunctions in the system must combine to break all reference cycles. This issubtle, and if in any doubt supply atp_clear function. For example,the tuple type does not implement atp_clear function, because it’spossible to prove that no reference cycle can be composed entirely of tuples.Therefore thetp_clear functions of other types must be sufficient tobreak any cycle containing a tuple. This isn’t immediately obvious, and there’srarely a good reason to avoid implementingtp_clear.
Implementations oftp_clear should drop the instance’s references tothose of its members that may be Python objects, and set its pointers to thosemembers toNULL, as in the following example:
staticintlocal_clear(localobject*self){Py_CLEAR(self->key);Py_CLEAR(self->args);Py_CLEAR(self->kw);Py_CLEAR(self->dict);return0;}
ThePy_CLEAR() macro should be used, because clearing references isdelicate: the reference to the contained object must not be decremented untilafter the pointer to the contained object is set toNULL. This is becausedecrementing the reference count may cause the contained object to become trash,triggering a chain of reclamation activity that may include invoking arbitraryPython code (due to finalizers, or weakref callbacks, associated with thecontained object). If it’s possible for such code to referenceself again,it’s important that the pointer to the contained object beNULL at that time,so thatself knows the contained object can no longer be used. ThePy_CLEAR() macro performs the operations in a safe order.
Because the goal oftp_clear functions is to break reference cycles,it’s not necessary to clear contained objects like Python strings or Pythonintegers, which can’t participate in reference cycles. On the other hand, it maybe convenient to clear all contained Python objects, and write the type’stp_dealloc function to invoketp_clear.
More information about Python’s garbage collection scheme can be found insectionSupporting Cyclic Garbage Collection.
This field is inherited by subtypes together withtp_traverse and thePy_TPFLAGS_HAVE_GC flag bit: the flag bit,tp_traverse, andtp_clear are all inherited from the base type if they are all zero inthe subtype.
An optional pointer to the rich comparison function, whose signature isPyObject*tp_richcompare(PyObject*a,PyObject*b,intop).
The function should return the result of the comparison (usuallyPy_TrueorPy_False). If the comparison is undefined, it must returnPy_NotImplemented, if another error occurred it must returnNULL andset an exception condition.
Note
If you want to implement a type for which only a limited set ofcomparisons makes sense (e.g.== and!=, but not< andfriends), directly raiseTypeError in the rich comparison function.
This field is inherited by subtypes together withtp_hash:a subtype inheritstp_richcompare andtp_hash whenthe subtype’stp_richcompare andtp_hash are bothNULL.
The following constants are defined to be used as the third argument fortp_richcompare and forPyObject_RichCompare():
| Constant | Comparison |
|---|---|
| Py_LT | < |
| Py_LE | <= |
| Py_EQ | == |
| Py_NE | != |
| Py_GT | > |
| Py_GE | >= |
If the instances of this type are weakly referenceable, this field is greaterthan zero and contains the offset in the instance structure of the weakreference list head (ignoring the GC header, if present); this offset is used byPyObject_ClearWeakRefs() and thePyWeakref_*() functions. Theinstance structure needs to include a field of typePyObject* which isinitialized toNULL.
Do not confuse this field withtp_weaklist; that is the list head forweak references to the type object itself.
This field is inherited by subtypes, but see the rules listed below. A subtypemay override this offset; this means that the subtype uses a different weakreference list head than the base type. Since the list head is always found viatp_weaklistoffset, this should not be a problem.
When a type defined by a class statement has no__slots__ declaration,and none of its base types are weakly referenceable, the type is made weaklyreferenceable by adding a weak reference list head slot to the instance layoutand setting thetp_weaklistoffset of that slot’s offset.
When a type’s__slots__ declaration contains a slot named__weakref__, that slot becomes the weak reference list head forinstances of the type, and the slot’s offset is stored in the type’stp_weaklistoffset.
When a type’s__slots__ declaration does not contain a slot named__weakref__, the type inherits itstp_weaklistoffset from itsbase type.
An optional pointer to a function that returns an iterator for the object. Itspresence normally signals that the instances of this type are iterable (althoughsequences may be iterable without this function).
This function has the same signature asPyObject_GetIter().
This field is inherited by subtypes.
An optional pointer to a function that returns the next item in an iterator.When the iterator is exhausted, it must returnNULL; aStopIterationexception may or may not be set. When another error occurs, it must returnNULL too. Its presence signals that the instances of this type areiterators.
Iterator types should also define thetp_iter function, and thatfunction should return the iterator instance itself (not a new iteratorinstance).
This function has the same signature asPyIter_Next().
This field is inherited by subtypes.
An optional pointer to a staticNULL-terminated array ofPyMethodDefstructures, declaring regular methods of this type.
For each entry in the array, an entry is added to the type’s dictionary (seetp_dict below) containing a method descriptor.
This field is not inherited by subtypes (methods are inherited through adifferent mechanism).
An optional pointer to a staticNULL-terminated array ofPyMemberDefstructures, declaring regular data members (fields or slots) of instances ofthis type.
For each entry in the array, an entry is added to the type’s dictionary (seetp_dict below) containing a member descriptor.
This field is not inherited by subtypes (members are inherited through adifferent mechanism).
An optional pointer to a staticNULL-terminated array ofPyGetSetDefstructures, declaring computed attributes of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (seetp_dict below) containing a getset descriptor.
This field is not inherited by subtypes (computed attributes are inheritedthrough a different mechanism).
Docs for PyGetSetDef:
typedefPyObject*(*getter)(PyObject*,void*);typedefint(*setter)(PyObject*,PyObject*,void*);typedefstructPyGetSetDef{char*name;/* attribute name */getterget;/* C function to get the attribute */setterset;/* C function to set the attribute */char*doc;/* optional doc string */void*closure;/* optional additional data for getter and setter */}PyGetSetDef;
An optional pointer to a base type from which type properties are inherited. Atthis level, only single inheritance is supported; multiple inheritance requiredynamically creating a type object by calling the metatype.
This field is not inherited by subtypes (obviously), but it defaults to&PyBaseObject_Type (which to Python programmers is known as the typeobject).
The type’s dictionary is stored here byPyType_Ready().
This field should normally be initialized toNULL before PyType_Ready iscalled; it may also be initialized to a dictionary containing initial attributesfor the type. OncePyType_Ready() has initialized the type, extraattributes for the type may be added to this dictionary only if they don’tcorrespond to overloaded operations (like__add__()).
This field is not inherited by subtypes (though the attributes defined in hereare inherited through a different mechanism).
Warning
It is not safe to usePyDict_SetItem() on or otherwise modifytp_dict with the dictionary C-API.
An optional pointer to a “descriptor get” function.
The function signature is
PyObject*tp_descr_get(PyObject*self,PyObject*obj,PyObject*type);
This field is inherited by subtypes.
An optional pointer to a “descriptor set” function.
The function signature is
inttp_descr_set(PyObject*self,PyObject*obj,PyObject*value);
This field is inherited by subtypes.
If the instances of this type have a dictionary containing instance variables,this field is non-zero and contains the offset in the instances of the type ofthe instance variable dictionary; this offset is used byPyObject_GenericGetAttr().
Do not confuse this field withtp_dict; that is the dictionary forattributes of the type object itself.
If the value of this field is greater than zero, it specifies the offset fromthe start of the instance structure. If the value is less than zero, itspecifies the offset from theend of the instance structure. A negativeoffset is more expensive to use, and should only be used when the instancestructure contains a variable-length part. This is used for example to add aninstance variable dictionary to subtypes ofstr ortuple. Notethat thetp_basicsize field should account for the dictionary added tothe end in that case, even though the dictionary is not included in the basicobject layout. On a system with a pointer size of 4 bytes,tp_dictoffset should be set to-4 to indicate that the dictionary isat the very end of the structure.
The real dictionary offset in an instance can be computed from a negativetp_dictoffset as follows:
dictoffset=tp_basicsize+abs(ob_size)*tp_itemsize+tp_dictoffsetifdictoffsetisnotalignedonsizeof(void*):rounduptosizeof(void*)
wheretp_basicsize,tp_itemsize andtp_dictoffset aretaken from the type object, andob_size is taken from the instance. Theabsolute value is taken because ints use the sign ofob_size tostore the sign of the number. (There’s never a need to do this calculationyourself; it is done for you by_PyObject_GetDictPtr().)
This field is inherited by subtypes, but see the rules listed below. A subtypemay override this offset; this means that the subtype instances store thedictionary at a difference offset than the base type. Since the dictionary isalways found viatp_dictoffset, this should not be a problem.
When a type defined by a class statement has no__slots__ declaration,and none of its base types has an instance variable dictionary, a dictionaryslot is added to the instance layout and thetp_dictoffset is set tothat slot’s offset.
When a type defined by a class statement has a__slots__ declaration,the type inherits itstp_dictoffset from its base type.
(Adding a slot named__dict__ to the__slots__ declaration doesnot have the expected effect, it just causes confusion. Maybe this should beadded as a feature just like__weakref__ though.)
An optional pointer to an instance initialization function.
This function corresponds to the__init__() method of classes. Like__init__(), it is possible to create an instance without calling__init__(), and it is possible to reinitialize an instance by calling its__init__() method again.
The function signature is
inttp_init(PyObject*self,PyObject*args,PyObject*kwds)
The self argument is the instance to be initialized; theargs andkwdsarguments represent positional and keyword arguments of the call to__init__().
Thetp_init function, if notNULL, is called when an instance iscreated normally by calling its type, after the type’stp_new functionhas returned an instance of the type. If thetp_new function returns aninstance of some other type that is not a subtype of the original type, notp_init function is called; iftp_new returns an instance of asubtype of the original type, the subtype’stp_init is called.
This field is inherited by subtypes.
An optional pointer to an instance allocation function.
The function signature is
PyObject*tp_alloc(PyTypeObject*self,Py_ssize_tnitems)
The purpose of this function is to separate memory allocation from memoryinitialization. It should return a pointer to a block of memory of adequatelength for the instance, suitably aligned, and initialized to zeros, but withob_refcnt set to1 andob_type set to the type argument. Ifthe type’stp_itemsize is non-zero, the object’sob_size fieldshould be initialized tonitems and the length of the allocated memory blockshould betp_basicsize+nitems*tp_itemsize, rounded up to a multiple ofsizeof(void*); otherwise,nitems is not used and the length of the blockshould betp_basicsize.
Do not use this function to do any other instance initialization, not even toallocate additional memory; that should be done bytp_new.
This field is inherited by static subtypes, but not by dynamic subtypes(subtypes created by a class statement); in the latter, this field is always settoPyType_GenericAlloc(), to force a standard heap allocation strategy.That is also the recommended value for statically defined types.
An optional pointer to an instance creation function.
If this function isNULL for a particular type, that type cannot be called tocreate new instances; presumably there is some other way to create instances,like a factory function.
The function signature is
PyObject*tp_new(PyTypeObject*subtype,PyObject*args,PyObject*kwds)
The subtype argument is the type of the object being created; theargs andkwds arguments represent positional and keyword arguments of the call to thetype. Note that subtype doesn’t have to equal the type whosetp_newfunction is called; it may be a subtype of that type (but not an unrelatedtype).
Thetp_new function should callsubtype->tp_alloc(subtype,nitems)to allocate space for the object, and then do only as much furtherinitialization as is absolutely necessary. Initialization that can safely beignored or repeated should be placed in thetp_init handler. A goodrule of thumb is that for immutable types, all initialization should take placeintp_new, while for mutable types, most initialization should bedeferred totp_init.
This field is inherited by subtypes, except it is not inherited by static typeswhosetp_base isNULL or&PyBaseObject_Type.
An optional pointer to an instance deallocation function. Its signature isfreefunc:
voidtp_free(void*)
An initializer that is compatible with this signature isPyObject_Free().
This field is inherited by static subtypes, but not by dynamic subtypes(subtypes created by a class statement); in the latter, this field is set to adeallocator suitable to matchPyType_GenericAlloc() and the value of thePy_TPFLAGS_HAVE_GC flag bit.
An optional pointer to a function called by the garbage collector.
The garbage collector needs to know whether a particular object is collectibleor not. Normally, it is sufficient to look at the object’s type’stp_flags field, and check thePy_TPFLAGS_HAVE_GC flag bit. Butsome types have a mixture of statically and dynamically allocated instances, andthe statically allocated instances are not collectible. Such types shoulddefine this function; it should return1 for a collectible instance, and0 for a non-collectible instance. The signature is
inttp_is_gc(PyObject*self)
(The only example of this are types themselves. The metatype,PyType_Type, defines this function to distinguish between staticallyand dynamically allocated types.)
This field is inherited by subtypes.
Tuple of base types.
This is set for types created by a class statement. It should beNULL forstatically defined types.
This field is not inherited.
Tuple containing the expanded set of base types, starting with the type itselfand ending withobject, in Method Resolution Order.
This field is not inherited; it is calculated fresh byPyType_Ready().
List of weak references to subclasses. Not inherited. Internal use only.
Weak reference list head, for weak references to this type object. Notinherited. Internal use only.
The remaining fields are only defined if the feature test macroCOUNT_ALLOCS is defined, and are for internal use only. They aredocumented here for completeness. None of these fields are inherited bysubtypes.
Number of allocations.
Number of frees.
Maximum simultaneously allocated objects.
Pointer to the next type object with a non-zerotp_allocs field.
Also, note that, in a garbage collected Python, tp_dealloc may be called fromany Python thread, not just the thread which created the object (if the objectbecomes part of a refcount cycle, that cycle might be collected by a garbagecollection on any thread). This is not a problem for Python API calls, sincethe thread on which tp_dealloc is called will own the Global Interpreter Lock(GIL). However, if the object being destroyed in turn destroys objects from someother C or C++ library, care should be taken to ensure that destroying thoseobjects on the thread which called tp_dealloc will not violate any assumptionsof the library.
This structure holds pointers to the functions which an object uses toimplement the number protocol. Each function is used by the function ofsimilar name documented in theNumber Protocol section.
Here is the structure definition:
typedefstruct{binaryfuncnb_add;binaryfuncnb_subtract;binaryfuncnb_multiply;binaryfuncnb_remainder;binaryfuncnb_divmod;ternaryfuncnb_power;unaryfuncnb_negative;unaryfuncnb_positive;unaryfuncnb_absolute;inquirynb_bool;unaryfuncnb_invert;binaryfuncnb_lshift;binaryfuncnb_rshift;binaryfuncnb_and;binaryfuncnb_xor;binaryfuncnb_or;unaryfuncnb_int;void*nb_reserved;unaryfuncnb_float;binaryfuncnb_inplace_add;binaryfuncnb_inplace_subtract;binaryfuncnb_inplace_multiply;binaryfuncnb_inplace_remainder;ternaryfuncnb_inplace_power;binaryfuncnb_inplace_lshift;binaryfuncnb_inplace_rshift;binaryfuncnb_inplace_and;binaryfuncnb_inplace_xor;binaryfuncnb_inplace_or;binaryfuncnb_floor_divide;binaryfuncnb_true_divide;binaryfuncnb_inplace_floor_divide;binaryfuncnb_inplace_true_divide;unaryfuncnb_index;}PyNumberMethods;
Note
Binary and ternary functions must check the type of all their operands,and implement the necessary conversions (at least one of the operands isan instance of the defined type). If the operation is not defined for thegiven operands, binary and ternary functions must returnPy_NotImplemented, if another error occurred they must returnNULLand set an exception.
Note
Thenb_reserved field should always beNULL. Itwas previously callednb_long, and was renamed inPython 3.0.1.
This structure holds pointers to the functions which an object uses toimplement the mapping protocol. It has three members:
This function is used byPyMapping_Length() andPyObject_Size(), and has the same signature. This slot may be set toNULL if the object has no defined length.
This function is used byPyObject_GetItem() and has the samesignature. This slot must be filled for thePyMapping_Check()function to return1, it can beNULL otherwise.
This function is used byPyObject_SetItem() and has the samesignature. If this slot isNULL, the object does not support itemassignment.
This structure holds pointers to the functions which an object uses toimplement the sequence protocol.
This function is used byPySequence_Size() andPyObject_Size(),and has the same signature.
This function is used byPySequence_Concat() and has the samesignature. It is also used by the+ operator, after trying the numericaddition via thenb_add slot.
This function is used byPySequence_Repeat() and has the samesignature. It is also used by the* operator, after trying numericmultiplication via thenb_mul slot.
This function is used byPySequence_GetItem() and has the samesignature. This slot must be filled for thePySequence_Check()function to return1, it can beNULL otherwise.
Negative indexes are handled as follows: if thesq_length slot isfilled, it is called and the sequence length is used to compute a positiveindex which is passed tosq_item. Ifsq_length isNULL,the index is passed as is to the function.
This function is used byPySequence_SetItem() and has the samesignature. This slot may be left toNULL if the object does not supportitem assignment.
This function may be used byPySequence_Contains() and has the samesignature. This slot may be left toNULL, in this casePySequence_Contains() simply traverses the sequence until it finds amatch.
This function is used byPySequence_InPlaceConcat() and has the samesignature. It should modify its first operand, and return it.
This function is used byPySequence_InPlaceRepeat() and has the samesignature. It should modify its first operand, and return it.
This structure holds pointers to the functions required by theBuffer protocol. The protocol defines howan exporter object can expose its internal data to consumer objects.
The signature of this function is:
int(PyObject*exporter,Py_buffer*view,intflags);
Handle a request toexporter to fill inview as specified byflags.Except for point (3), an implementation of this function MUST take thesesteps:
Ifexporter is part of a chain or tree of buffer providers, two mainschemes can be used:
The individual fields ofview are described in sectionBuffer structure, the rules how an exportermust react to specific requests are in sectionBuffer request types.
All memory pointed to in thePy_buffer structure belongs tothe exporter and must remain valid until there are no consumers left.format,shape,strides,suboffsetsandinternalare read-only for the consumer.
PyBuffer_FillInfo() provides an easy way of exposing a simplebytes buffer while dealing correctly with all request types.
PyObject_GetBuffer() is the interface for the consumer thatwraps this function.
The signature of this function is:
void(PyObject*exporter,Py_buffer*view);
Handle a request to release the resources of the buffer. If no resourcesneed to be released,PyBufferProcs.bf_releasebuffer may beNULL. Otherwise, a standard implementation of this function will takethese optional steps:
The exporter MUST use theinternal field to keeptrack of buffer-specific resources. This field is guaranteed to remainconstant, while a consumer MAY pass a copy of the original buffer as theview argument.
This function MUST NOT decrementview->obj, since that isdone automatically inPyBuffer_Release() (this scheme isuseful for breaking reference cycles).
PyBuffer_Release() is the interface for the consumer thatwraps this function.
Supporting Cyclic Garbage Collection
Enter search terms or a module, class or function name.