There are a large number of structures which are used in the definition of object types for Python. This section describes these structures and how they are used.
All Python objects ultimately share a small number of fields at the beginning of the object's representation in memory. These are represented by the :c:type:`PyObject` and :c:type:`PyVarObject` types, which are defined, in turn, by the expansions of some macros also used, whether directly or indirectly, in the definition of all other Python objects. Additional macros can be found under :ref:`reference counting <countingrefs>`.
.. c:type:: PyObjectAllobjecttypesareextensionsofthistype. ThisisatypewhichcontainstheinformationPythonneedstotreatapointertoanobjectasanobject. Inanormal"release"build, itcontainsonlytheobject's referencecountandapointertothecorrespondingtypeobject. Nothingisactuallydeclaredtobea :c:type:`PyObject`, buteverypointertoaPythonobjectcanbecasttoa :c:expr:`PyObject*`. Accesstothemembersmustbedonebyusingthemacros :c:macro:`Py_REFCNT` and :c:macro:`Py_TYPE`.
.. c:type:: PyVarObjectThisisanextensionof :c:type:`PyObject` thataddsthe :c:member:`~PyVarObject.ob_size` field. Thisisonlyusedforobjectsthathavesomenotionof*length*. ThistypedoesnotoftenappearinthePython/CAPI. Accesstothemembersmustbedonebyusingthemacros :c:macro:`Py_REFCNT`, :c:macro:`Py_TYPE`, and :c:macro:`Py_SIZE`.
.. c:macro:: PyObject_HEADThisisamacrousedwhendeclaringnewtypeswhichrepresentobjectswithoutavaryinglength. ThePyObject_HEADmacroexpandsto:: PyObjectob_base; Seedocumentationof :c:type:`PyObject` above.
.. c:macro:: PyObject_VAR_HEADThisisamacrousedwhendeclaringnewtypeswhichrepresentobjectswithalengththatvariesfrominstancetoinstance. ThePyObject_VAR_HEADmacroexpandsto:: PyVarObjectob_base; Seedocumentationof :c:type:`PyVarObject` above.
.. c:var:: PyTypeObjectPyBaseObject_TypeThebaseclassofallotherobjects, thesameas :class:`object` inPython.
.. c:function:: intPy_Is(PyObject*x, PyObject*y) Testifthe*x*objectisthe*y*object, thesameas ``xisy`` inPython. .. versionadded:: 3.10
.. c:function:: intPy_IsNone(PyObject*x) Testifanobjectisthe ``None`` singleton, thesameas ``xisNone`` inPython. .. versionadded:: 3.10
.. c:function:: intPy_IsTrue(PyObject*x) Testifanobjectisthe ``True`` singleton, thesameas ``xisTrue`` inPython. .. versionadded:: 3.10
.. c:function:: intPy_IsFalse(PyObject*x) Testifanobjectisthe ``False`` singleton, thesameas ``xisFalse`` inPython. .. versionadded:: 3.10
.. c:function:: PyTypeObject*Py_TYPE(PyObject*o) GetthetypeofthePythonobject*o*. Returna :term:`borrowedreference`. Usethe :c:func:`Py_SET_TYPE` functiontosetanobjecttype. .. versionchanged:: 3.11 :c:func:`Py_TYPE()` ischangedtoaninlinestaticfunction. Theparametertypeisnolonger :c:expr:`constPyObject*`.
.. c:function:: intPy_IS_TYPE(PyObject*o, PyTypeObject*type) Returnnon-zeroiftheobject*o*typeis*type*. Returnzerootherwise. Equivalentto: ``Py_TYPE(o) ==type``. .. versionadded:: 3.9
.. c:function:: voidPy_SET_TYPE(PyObject*o, PyTypeObject*type) Settheobject*o*typeto*type*. .. versionadded:: 3.9
.. c:function:: Py_ssize_tPy_SIZE(PyVarObject*o) GetthesizeofthePythonobject*o*. Usethe :c:func:`Py_SET_SIZE` functiontosetanobjectsize. .. versionchanged:: 3.11 :c:func:`Py_SIZE()` ischangedtoaninlinestaticfunction. Theparametertypeisnolonger :c:expr:`constPyVarObject*`.
.. c:function:: voidPy_SET_SIZE(PyVarObject*o, Py_ssize_tsize) Settheobject*o*sizeto*size*. .. versionadded:: 3.9
.. c:macro:: PyObject_HEAD_INIT(type) Thisisamacrowhichexpandstoinitializationvaluesforanew :c:type:`PyObject` type. Thismacroexpandsto:: _PyObject_EXTRA_INIT1, type,
.. c:macro:: PyVarObject_HEAD_INIT(type, size) Thisisamacrowhichexpandstoinitializationvaluesforanew :c:type:`PyVarObject` type, includingthe :c:member:`~PyVarObject.ob_size` field. Thismacroexpandsto:: _PyObject_EXTRA_INIT1, type, size,
.. c:type:: PyCFunctionTypeofthefunctionsusedtoimplementmostPythoncallablesinC. Functionsofthistypetaketwo :c:expr:`PyObject*` parametersandreturnonesuchvalue. Ifthereturnvalueis ``NULL``, anexceptionshallhavebeenset. Ifnot ``NULL``, thereturnvalueisinterpretedasthereturnvalueofthefunctionasexposedinPython. Thefunctionmustreturnanewreference. Thefunctionsignatureis:: PyObject*PyCFunction(PyObject*self, PyObject*args);
.. c:type:: PyCFunctionWithKeywordsTypeofthefunctionsusedtoimplementPythoncallablesinCwithsignature :ref:`METH_VARARGS | METH_KEYWORDS<METH_VARARGS-METH_KEYWORDS>`. Thefunctionsignatureis:: PyObject*PyCFunctionWithKeywords(PyObject*self, PyObject*args, PyObject*kwargs);
.. c:type:: PyCFunctionFastTypeofthefunctionsusedtoimplementPythoncallablesinCwithsignature :c:macro:`METH_FASTCALL`. Thefunctionsignatureis:: PyObject*PyCFunctionFast(PyObject*self, PyObject*const*args, Py_ssize_tnargs);
.. c:type:: PyCFunctionFastWithKeywordsTypeofthefunctionsusedtoimplementPythoncallablesinCwithsignature :ref:`METH_FASTCALL | METH_KEYWORDS<METH_FASTCALL-METH_KEYWORDS>`. Thefunctionsignatureis:: PyObject*PyCFunctionFastWithKeywords(PyObject*self, PyObject*const*args, Py_ssize_tnargs, PyObject*kwnames);
.. c:type:: PyCMethodTypeofthefunctionsusedtoimplementPythoncallablesinCwithsignature :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS<METH_METHOD-METH_FASTCALL-METH_KEYWORDS>`. Thefunctionsignatureis:: PyObject*PyCMethod(PyObject*self, PyTypeObject*defining_class, PyObject*const*args, Py_ssize_tnargs, PyObject*kwnames) .. versionadded:: 3.9
.. c:type:: PyMethodDefStructureusedtodescribeamethodofanextensiontype. Thisstructurehasfourfields: .. c:member:: constchar*ml_nameNameofthemethod. .. c:member:: PyCFunctionml_methPointertotheCimplementation. .. c:member:: intml_flagsFlagsbitsindicatinghowthecallshouldbeconstructed. .. c:member:: constchar*ml_docPointstothecontentsofthedocstring.
The :c:member:`~PyMethodDef.ml_meth` is a C function pointer. The functions may be of different types, but they always return :c:expr:`PyObject*`. If the function is not of the :c:type:`PyCFunction`, the compiler will require a cast in the method table. Even though :c:type:`PyCFunction` defines the first parameter as :c:expr:`PyObject*`, it is common that the method implementation uses the specific C type of the self object.
The :c:member:`~PyMethodDef.ml_flags` field is a bitfield which can include the following flags. The individual flags indicate either a calling convention or a binding convention.
There are these calling conventions:
.. c:macro:: METH_VARARGSThisisthetypicalcallingconvention, wherethemethodshavethetype :c:type:`PyCFunction`. Thefunctionexpectstwo :c:expr:`PyObject*` values. Thefirstoneisthe*self*objectformethods; formodulefunctions, itisthemoduleobject. Thesecondparameter (oftencalled*args*) isatupleobjectrepresentingallarguments. Thisparameteristypicallyprocessedusing :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`.
.. c:macro:: METH_KEYWORDSCanonlybeusedincertaincombinationswithotherflags: :ref:`METH_VARARGS | METH_KEYWORDS<METH_VARARGS-METH_KEYWORDS>`, :ref:`METH_FASTCALL | METH_KEYWORDS<METH_FASTCALL-METH_KEYWORDS>` and :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS<METH_METHOD-METH_FASTCALL-METH_KEYWORDS>`.
- :c:expr:`METH_VARARGS | METH_KEYWORDS`
- Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`. The function expects three parameters: self, args, kwargs where kwargs is a dictionary of all the keyword arguments or possibly
NULL
if there are no keyword arguments. The parameters are typically processed using :c:func:`PyArg_ParseTupleAndKeywords`.
.. c:macro:: METH_FASTCALLFastcallingconventionsupportingonlypositionalarguments. Themethodshavethetype :c:type:`PyCFunctionFast`. Thefirstparameteris*self*, thesecondparameterisaCarrayof :c:expr:`PyObject*` valuesindicatingtheargumentsandthethirdparameteristhenumberofarguments (thelengthofthearray). .. versionadded:: 3.7 .. versionchanged:: 3.10 ``METH_FASTCALL`` isnowpartofthe :ref:`stableABI<stable-abi>`.
- :c:expr:`METH_FASTCALL | METH_KEYWORDS`
Extension of :c:macro:`METH_FASTCALL` supporting also keyword arguments, with methods of type :c:type:`PyCFunctionFastWithKeywords`. Keyword arguments are passed the same way as in the :ref:`vectorcall protocol <vectorcall>`: there is an additional fourth :c:expr:`PyObject*` parameter which is a tuple representing the names of the keyword arguments (which are guaranteed to be strings) or possibly
NULL
if there are no keywords. The values of the keyword arguments are stored in the args array, after the positional arguments... versionadded:: 3.7
.. c:macro:: METH_METHODCanonlybeusedinthecombinationwithotherflags: :ref:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS<METH_METHOD-METH_FASTCALL-METH_KEYWORDS>`.
- :c:expr:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS`
Extension of :ref:`METH_FASTCALL | METH_KEYWORDS <METH_FASTCALL-METH_KEYWORDS>` supporting the defining class, that is, the class that contains the method in question. The defining class might be a superclass of
Py_TYPE(self)
.The method needs to be of type :c:type:`PyCMethod`, the same as for
METH_FASTCALL | METH_KEYWORDS
withdefining_class
argument added afterself
... versionadded:: 3.9
.. c:macro:: METH_NOARGSMethodswithoutparametersdon't need to check whether arguments are given if theyarelistedwiththe :c:macro:`METH_NOARGS` flag. Theyneedtobeoftype :c:type:`PyCFunction`. Thefirstparameteristypicallynamed*self*andwillholdareferencetothemoduleorobjectinstance. Inallcasesthesecondparameterwillbe ``NULL``. Thefunctionmusthave2parameters. Sincethesecondparameterisunused, :c:macro:`Py_UNUSED` canbeusedtopreventacompilerwarning.
.. c:macro:: METH_OMethodswithasingleobjectargumentcanbelistedwiththe :c:macro:`METH_O` flag, insteadofinvoking :c:func:`PyArg_ParseTuple` witha ``"O"`` argument. Theyhavethetype :c:type:`PyCFunction`, withthe*self*parameter, anda :c:expr:`PyObject*` parameterrepresentingthesingleargument.
These two constants are not used to indicate the calling convention but the binding when use with methods of classes. These may not be used for functions defined for modules. At most one of these flags may be set for any given method.
.. c:macro:: METH_CLASS .. index:: pair: built-infunction; classmethodThemethodwillbepassedthetypeobjectasthefirstparameterratherthananinstanceofthetype. Thisisusedtocreate*classmethods*, similartowhatiscreatedwhenusingthe :func:`classmethod` built-infunction.
.. c:macro:: METH_STATIC .. index:: pair: built-infunction; staticmethodThemethodwillbepassed ``NULL`` asthefirstparameterratherthananinstanceofthetype. Thisisusedtocreate*staticmethods*, similartowhatiscreatedwhenusingthe :func:`staticmethod` built-infunction.
One other constant controls whether a method is loaded in place of another definition with the same method name.
.. c:macro:: METH_COEXISTThemethodwillbeloadedinplaceofexistingdefinitions. Without*METH_COEXIST*, thedefaultistoskiprepeateddefinitions. Sinceslotwrappersareloadedbeforethemethodtable, theexistenceofa*sq_contains*slot, forexample, wouldgenerateawrappedmethodnamed :meth:`~object.__contains__` andprecludetheloadingofacorrespondingPyCFunctionwiththesamename. Withtheflagdefined, thePyCFunctionwillbeloadedinplaceofthewrapperobjectandwillco-existwiththeslot. ThisishelpfulbecausecallstoPyCFunctionsareoptimizedmorethanwrapperobjectcalls.
.. c:function:: PyObject*PyCMethod_New(PyMethodDef*ml, PyObject*self, PyObject*module, PyTypeObject*cls) Turn*ml*intoaPython :term:`callable` object. Thecallermustensurethat*ml*outlivesthe :term:`callable`. Typically, *ml*isdefinedasastaticvariable. The*self*parameterwillbepassedasthe*self*argumenttotheCfunctionin ``ml->ml_meth`` wheninvoked. *self*canbe ``NULL``. The :term:`callable` object's ``__module__`` attributecanbesetfromthegiven*module*argument. *module*shouldbeaPythonstring, whichwillbeusedasnameofthemodulethefunctionis defined in. Ifunavailable, itcanbesetto :const:`None` or ``NULL``. .. seealso:: :attr:`function.__module__` The*cls*parameterwillbepassedasthe*defining_class*argumenttotheCfunction. Mustbesetif :c:macro:`METH_METHOD` isseton ``ml->ml_flags``. .. versionadded:: 3.9
.. c:function:: PyObject*PyCFunction_NewEx(PyMethodDef*ml, PyObject*self, PyObject*module) Equivalentto ``PyCMethod_New(ml, self, module, NULL)``.
.. c:function:: PyObject*PyCFunction_New(PyMethodDef*ml, PyObject*self) Equivalentto ``PyCMethod_New(ml, self, NULL, NULL)``.
.. c:type:: PyMemberDefStructurewhichdescribesanattributeofatypewhichcorrespondstoaCstructmember. Whendefiningaclass, puta NULL-terminatedarrayofthesestructuresinthe :c:member:`~PyTypeObject.tp_members` slot. Itsfieldsare, inorder: .. c:member:: constchar*nameNameofthemember. ANULLvaluemarkstheendofa ``PyMemberDef[]`` array. Thestringshouldbestatic, nocopyismadeofit. .. c:member:: inttypeThetypeofthememberintheCstruct. See :ref:`PyMemberDef-types` forthepossiblevalues. .. c:member:: Py_ssize_toffsetTheoffsetinbytesthatthememberislocatedonthetype’sobjectstruct. .. c:member:: intflagsZeroormoreofthe :ref:`PyMemberDef-flags`, combinedusingbitwiseOR. .. c:member:: constchar*docThedocstring, orNULL. Thestringshouldbestatic, nocopyismadeofit. Typically, itis defined using :c:macro:`PyDoc_STR`. Bydefault (when :c:member:`~PyMemberDef.flags` is ``0``), membersallowbothreadandwriteaccess. Usethe :c:macro:`Py_READONLY` flagforread-onlyaccess. Certaintypes, like :c:macro:`Py_T_STRING`, imply :c:macro:`Py_READONLY`. Only :c:macro:`Py_T_OBJECT_EX` (andlegacy :c:macro:`T_OBJECT`) memberscanbedeleted. .. _pymemberdef-offsets: Forheap-allocatedtypes (createdusing :c:func:`PyType_FromSpec` orsimilar), ``PyMemberDef`` maycontainadefinitionforthespecialmember ``"__vectorcalloffset__"``, correspondingto :c:member:`~PyTypeObject.tp_vectorcall_offset` intypeobjects. Thismembermustbedefinedwith ``Py_T_PYSSIZET``, andeither ``Py_READONLY`` or ``Py_READONLY | Py_RELATIVE_OFFSET``. Forexample:: staticPyMemberDefspam_type_members[] = { {"__vectorcalloffset__", Py_T_PYSSIZET, offsetof(Spam_object, vectorcall), Py_READONLY}, {NULL} /* Sentinel */ }; (Youmayneedto ``#include<stddef.h>`` for :c:func:`!offsetof`.) Thelegacyoffsets :c:member:`~PyTypeObject.tp_dictoffset` and :c:member:`~PyTypeObject.tp_weaklistoffset` canbe defined similarlyusing ``"__dictoffset__"`` and ``"__weaklistoffset__"`` members, butextensionsarestronglyencouragedtouse :c:macro:`Py_TPFLAGS_MANAGED_DICT` and :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` instead. .. versionchanged:: 3.12 ``PyMemberDef`` isalwaysavailable. Previously, itrequiredincluding ``"structmember.h"``. .. versionchanged:: 3.14 :c:macro:`Py_RELATIVE_OFFSET` isnowallowedfor ``"__vectorcalloffset__"``, ``"__dictoffset__"`` and ``"__weaklistoffset__"``.
.. c:function:: PyObject*PyMember_GetOne(constchar*obj_addr, structPyMemberDef*m) Getanattributebelongingtotheobjectataddress*obj_addr*. Theattributeisdescribedby ``PyMemberDef`` *m*. Returns ``NULL`` onerror. .. versionchanged:: 3.12 ``PyMember_GetOne`` isalwaysavailable. Previously, itrequiredincluding ``"structmember.h"``.
.. c:function:: intPyMember_SetOne(char*obj_addr, structPyMemberDef*m, PyObject*o) Setanattributebelongingtotheobjectataddress*obj_addr*toobject*o*. Theattributetosetisdescribedby ``PyMemberDef`` *m*. Returns ``0`` ifsuccessfulandanegativevalueonfailure. .. versionchanged:: 3.12 ``PyMember_SetOne`` isalwaysavailable. Previously, itrequiredincluding ``"structmember.h"``.
The following flags can be used with :c:member:`PyMemberDef.flags`:
.. c:macro:: Py_READONLYNotwritable.
.. c:macro:: Py_AUDIT_READEmitan ``object.__getattr__`` :ref:`auditevent<audit-events>` beforereading.
.. c:macro:: Py_RELATIVE_OFFSETIndicatesthatthe :c:member:`~PyMemberDef.offset` ofthis ``PyMemberDef`` entryindicatesanoffsetfromthesubclass-specificdata, ratherthanfrom ``PyObject``. Canonlybeusedaspartof :c:member:`Py_tp_members<PyTypeObject.tp_members>` :c:type:`slot<PyType_Slot>` whencreatingaclassusingnegative :c:member:`~PyType_Spec.basicsize`. Itismandatoryinthatcase. Thisflagisonlyusedin :c:type:`PyType_Slot`. Whensetting :c:member:`~PyTypeObject.tp_members` duringclasscreation, Pythonclearsitandsets :c:member:`PyMemberDef.offset` totheoffsetfromthe ``PyObject`` struct.
.. index:: single: READ_RESTRICTED (Cmacro) single: WRITE_RESTRICTED (Cmacro) single: RESTRICTED (Cmacro)
.. versionchanged:: 3.10The :c:macro:`!RESTRICTED`, :c:macro:`!READ_RESTRICTED` and :c:macro:`!WRITE_RESTRICTED` macrosavailablewith ``#include"structmember.h"`` aredeprecated. :c:macro:`!READ_RESTRICTED` and :c:macro:`!RESTRICTED` areequivalentto :c:macro:`Py_AUDIT_READ`; :c:macro:`!WRITE_RESTRICTED` doesnothing.
.. index:: single: READONLY (Cmacro)
.. versionchanged:: 3.12The :c:macro:`!READONLY` macrowasrenamedto :c:macro:`Py_READONLY`. The :c:macro:`!PY_AUDIT_READ` macrowasrenamedwiththe ``Py_`` prefix. Thenewnamesarenowalwaysavailable. Previously, theserequired ``#include"structmember.h"``. Theheaderisstillavailableanditprovidestheoldnames.
:c:member:`PyMemberDef.type` can be one of the following macros corresponding to various C types. When the member is accessed in Python, it will be converted to the equivalent Python type. When it is set from Python, it will be converted back to the C type. If that is not possible, an exception such as :exc:`TypeError` or :exc:`ValueError` is raised.
Unless marked (D), attributes defined this way cannot be deleted using e.g. :keyword:`del` or :py:func:`delattr`.
(*): Zero-terminated, UTF8-encoded C string. With :c:macro:`!Py_T_STRING` the C representation is a pointer; with :c:macro:`!Py_T_STRING_INPLACE` the string is stored directly in the structure.
(**): String of length 1. Only ASCII is accepted.
(RO): Implies :c:macro:`Py_READONLY`.
(D): Can be deleted, in which case the pointer is set to
NULL
. Reading aNULL
pointer raises :py:exc:`AttributeError`.
.. index:: single: T_BYTE (Cmacro) single: T_SHORT (Cmacro) single: T_INT (Cmacro) single: T_LONG (Cmacro) single: T_LONGLONG (Cmacro) single: T_UBYTE (Cmacro) single: T_USHORT (Cmacro) single: T_UINT (Cmacro) single: T_ULONG (Cmacro) single: T_ULONGULONG (Cmacro) single: T_PYSSIZET (Cmacro) single: T_FLOAT (Cmacro) single: T_DOUBLE (Cmacro) single: T_BOOL (Cmacro) single: T_CHAR (Cmacro) single: T_STRING (Cmacro) single: T_STRING_INPLACE (Cmacro) single: T_OBJECT_EX (Cmacro) single: structmember.h
.. versionadded:: 3.12Inpreviousversions, themacroswereonlyavailablewith ``#include"structmember.h"`` andwerenamedwithoutthe ``Py_`` prefix (e.g. as ``T_INT``). Theheaderisstillavailableandcontainstheoldnames, alongwiththefollowingdeprecatedtypes: .. c:macro:: T_OBJECTLike ``Py_T_OBJECT_EX``, but ``NULL`` isconvertedto ``None``. ThisresultsinsurprisingbehaviorinPython: deletingtheattributeeffectivelysetsitto ``None``. .. c:macro:: T_NONEAlways ``None``. Mustbeusedwith :c:macro:`Py_READONLY`.
.. c:type:: PyGetSetDefStructuretodefineproperty-likeaccessforatype. Seealsodescriptionofthe :c:member:`PyTypeObject.tp_getset` slot. .. c:member:: constchar*nameattributename .. c:member:: gettergetCfunctiontogettheattribute. .. c:member:: settersetOptionalCfunctiontosetordeletetheattribute. If ``NULL``, theattributeisread-only. .. c:member:: constchar*docoptionaldocstring .. c:member:: void*closureOptionaluserdatapointer, providingadditionaldataforgetterandsetter.
.. c:type:: PyObject*(*getter)(PyObject*, void*) The ``get`` functiontakesone :c:expr:`PyObject*` parameter (theinstance) andauserdatapointer (theassociated ``closure``): Itshouldreturnanewreferenceonsuccessor ``NULL`` withasetexceptiononfailure.
.. c:type:: int (*setter)(PyObject*, PyObject*, void*) ``set`` functionstaketwo :c:expr:`PyObject*` parameters (theinstanceandthevaluetobeset) andauserdatapointer (theassociated ``closure``): Incasetheattributeshouldbedeletedthesecondparameteris ``NULL``. Shouldreturn ``0`` onsuccessor ``-1`` withasetexceptiononfailure.