循環垃圾回收的支援¶
Python's support for detecting and collecting garbage which involves circularreferences requires support from object types which are "containers" for otherobjects which may also be containers. Types which do not store references toother objects, or which only store references to atomic types (such as numbersor strings), do not need to provide any explicit support for garbagecollection.
To create a container type, thetp_flags
field of the type object mustinclude thePy_TPFLAGS_HAVE_GC
and provide an implementation of thetp_traverse
handler. If instances of the type are mutable, atp_clear
implementation must also be provided.
Py_TPFLAGS_HAVE_GC
Objects with a type with this flag set must conform with the rulesdocumented here. For convenience these objects will be referred to ascontainer objects.
Constructors for container types must conform to two rules:
The memory for the object must be allocated using
PyObject_GC_New
orPyObject_GC_NewVar
.Once all the fields which may contain references to other containers areinitialized, it must call
PyObject_GC_Track()
.
Similarly, the deallocator for the object must conform to a similar pair ofrules:
Before fields which refer to other containers are invalidated,
PyObject_GC_UnTrack()
must be called.The object's memory must be deallocated using
PyObject_GC_Del()
.警告
If a type adds the Py_TPFLAGS_HAVE_GC, then itmust implement at leasta
tp_traverse
handler or explicitly use onefrom its subclass or subclasses.When calling
PyType_Ready()
or some of the APIs that indirectlycall it likePyType_FromSpecWithBases()
orPyType_FromSpec()
the interpreter will automatically populate thetp_flags
,tp_traverse
andtp_clear
fields if the type inherits from aclass that implements the garbage collector protocol and the child classdoesnot include thePy_TPFLAGS_HAVE_GC
flag.
- PyObject_GC_New(TYPE,typeobj)¶
Analogous to
PyObject_New
but for container objects with thePy_TPFLAGS_HAVE_GC
flag set.
- PyObject_GC_NewVar(TYPE,typeobj,size)¶
Analogous to
PyObject_NewVar
but for container objects with thePy_TPFLAGS_HAVE_GC
flag set.
- PyObject*PyUnstable_Object_GC_NewWithExtraData(PyTypeObject*type,size_textra_size)¶
- 這是不穩定 API,它可能在小版本發布中沒有任何警告地被變更。
Analogous to
PyObject_GC_New
but allocatesextra_sizebytes at the end of the object (at offsettp_basicsize
).The allocated memory is initialized to zeros,except for thePythonobjectheader
.The extra data will be deallocated with the object, but otherwise it isnot managed by Python.
警告
The function is marked as unstable because the final mechanismfor reserving extra data after an instance is not yet decided.For allocating a variable number of fields, prefer using
PyVarObject
andtp_itemsize
instead.在 3.12 版被加入.
- PyObject_GC_Resize(TYPE,op,newsize)¶
Resize an object allocated by
PyObject_NewVar
.Returns the resized object of typeTYPE*
(refers to any C type)orNULL
on failure.op must be of typePyVarObject*and must not be tracked by the collector yet.newsize must be of type
Py_ssize_t
.
- voidPyObject_GC_Track(PyObject*op)¶
- 為穩定 ABI 的一部分.
Adds the objectop to the set of container objects tracked by thecollector. The collector can run at unexpected times so objects must bevalid while being tracked. This should be called once all the fieldsfollowed by the
tp_traverse
handler become valid, usually near theend of the constructor.
- intPyObject_IS_GC(PyObject*obj)¶
Returns non-zero if the object implements the garbage collector protocol,otherwise returns 0.
The object cannot be tracked by the garbage collector if this function returns 0.
- intPyObject_GC_IsTracked(PyObject*op)¶
- 為穩定 ABI 的一部分 自 3.9 版本開始.
Returns 1 if the object type ofop implements the GC protocol andop is beingcurrently tracked by the garbage collector and 0 otherwise.
This is analogous to the Python function
gc.is_tracked()
.在 3.9 版被加入.
- intPyObject_GC_IsFinalized(PyObject*op)¶
- 為穩定 ABI 的一部分 自 3.9 版本開始.
Returns 1 if the object type ofop implements the GC protocol andop has beenalready finalized by the garbage collector and 0 otherwise.
This is analogous to the Python function
gc.is_finalized()
.在 3.9 版被加入.
- voidPyObject_GC_Del(void*op)¶
- 為穩定 ABI 的一部分.
Releases memory allocated to an object using
PyObject_GC_New
orPyObject_GC_NewVar
.
- voidPyObject_GC_UnTrack(void*op)¶
- 為穩定 ABI 的一部分.
Remove the objectop from the set of container objects tracked by thecollector. Note that
PyObject_GC_Track()
can be called again onthis object to add it back to the set of tracked objects. The deallocator(tp_dealloc
handler) should call this for the object before any ofthe fields used by thetp_traverse
handler become invalid.
在 3.8 版的變更:The_PyObject_GC_TRACK()
and_PyObject_GC_UNTRACK()
macroshave been removed from the public C API.
Thetp_traverse
handler accepts a function parameter of this type:
- typedefint(*visitproc)(PyObject*object,void*arg)¶
- 為穩定 ABI 的一部分.
Type of the visitor function passed to the
tp_traverse
handler.The function should be called with an object to traverse asobject andthe third parameter to thetp_traverse
handler asarg. ThePython core uses several visitor functions to implement cyclic garbagedetection; it's not expected that users will need to write their ownvisitor functions.
Thetp_traverse
handler must have the following type:
- typedefint(*traverseproc)(PyObject*self,visitprocvisit,void*arg)¶
- 為穩定 ABI 的一部分.
Traversal function for a container object. Implementations must call thevisit function for each object directly contained byself, with theparameters tovisit being the contained object and thearg value passedto the handler. Thevisit function must not be called with a
NULL
object argument. Ifvisit returns a non-zero value that value should bereturned immediately.
To simplify writingtp_traverse
handlers, aPy_VISIT()
macro isprovided. In order to use this macro, thetp_traverse
implementationmust name its arguments exactlyvisit andarg:
- Py_VISIT(o)¶
If thePyObject*o is not
NULL
, call thevisit callback, with argumentsoandarg. Ifvisit returns a non-zero value, then return it.Using this macro,tp_traverse
handlerslook like:staticintmy_traverse(Noddy*self,visitprocvisit,void*arg){Py_VISIT(self->foo);Py_VISIT(self->bar);return0;}
Thetp_clear
handler must be of theinquiry
type, orNULL
if the object is immutable.
- typedefint(*inquiry)(PyObject*self)¶
- 為穩定 ABI 的一部分.
Drop references that may have created reference cycles. Immutable objectsdo not have to define this method since they can never directly createreference cycles. Note that the object must still be valid after callingthis method (don't just call
Py_DECREF()
on a reference). Thecollector will call this method if it detects that this object is involvedin a reference cycle.
Controlling the Garbage Collector State¶
The C-API provides the following functions for controllinggarbage collection runs.
- Py_ssize_tPyGC_Collect(void)¶
- 為穩定 ABI 的一部分.
Perform a full garbage collection, if the garbage collector is enabled.(Note that
gc.collect()
runs it unconditionally.)Returns the number of collected + unreachable objects which cannotbe collected.If the garbage collector is disabled or already collecting,returns
0
immediately.Errors during garbage collection are passed tosys.unraisablehook
.This function does not raise exceptions.
- intPyGC_Enable(void)¶
- 為穩定 ABI 的一部分 自 3.10 版本開始.
Enable the garbage collector: similar to
gc.enable()
.Returns the previous state, 0 for disabled and 1 for enabled.在 3.10 版被加入.
- intPyGC_Disable(void)¶
- 為穩定 ABI 的一部分 自 3.10 版本開始.
Disable the garbage collector: similar to
gc.disable()
.Returns the previous state, 0 for disabled and 1 for enabled.在 3.10 版被加入.
- intPyGC_IsEnabled(void)¶
- 為穩定 ABI 的一部分 自 3.10 版本開始.
Query the state of the garbage collector: similar to
gc.isenabled()
.Returns the current state, 0 for disabled and 1 for enabled.在 3.10 版被加入.
Querying Garbage Collector State¶
The C-API provides the following interface for querying information aboutthe garbage collector.
- voidPyUnstable_GC_VisitObjects(gcvisitobjects_tcallback,void*arg)¶
- 這是不穩定 API,它可能在小版本發布中沒有任何警告地被變更。
Run suppliedcallback on all live GC-capable objects.arg is passed through toall invocations ofcallback.
警告
If new objects are (de)allocated by the callback it is undefined if theywill be visited.
Garbage collection is disabled during operation. Explicitly running a collectionin the callback may lead to undefined behaviour e.g. visiting the same objectsmultiple times or not at all.
在 3.12 版被加入.
- typedefint(*gcvisitobjects_t)(PyObject*object,void*arg)¶
Type of the visitor function to be passed to
PyUnstable_GC_VisitObjects()
.arg is the same as thearg passed toPyUnstable_GC_VisitObjects
.Return1
to continue iteration, return0
to stop iteration. Other returnvalues are reserved for now so behavior on returning anything else is undefined.在 3.12 版被加入.