This document is for an old version of Python that is no longer supported. You should upgrade and read the Python 当前稳定版本的文档.

# 弱引用对象

Python 支持 “弱引用” 作为一类对象。具体来说，有两种直接实现弱引用的对象。第一种就是简单的引用对象，第二种尽可能地作用为一个原对象的代理。

int `PyWeakref_Check`(ob)

  如果 “ob” 是一个引用或者一个代理对象，则返回 true。

  2.2 新版功能.

int `PyWeakref_CheckRef`(ob)

  如果 “ob” 是一个引用，则返回 true。

  2.2 新版功能.

int `PyWeakref_CheckProxy`(ob)

  如果 “ob” 是一个代理对象，则返回 true。

  2.2 新版功能.

PyObject* `PyWeakref_NewRef`(PyObject *ob, PyObject *callback)
  Return value: New reference.

  Return a weak reference object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing reference object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be `None` or NULL. If ob is not a weakly-referencable object, or if callback is not callable, `None`, or NULL, this will return NULL and raise `TypeError`.

  2.2 新版功能.

PyObject* `PyWeakref_NewProxy`(PyObject *ob, PyObject *callback)
  Return value: New reference.

  Return a weak reference proxy object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be `None` or NULL. If ob is not a weakly-referencable object, or if callback is not callable, `None`, or NULL, this will return NULL and raise `TypeError`.

  2.2 新版功能.

PyObject* `PyWeakref_GetObject`(PyObject *ref)
  Return value: Borrowed reference.

  返回弱引用对象 ref 的被引用对象。如果被引用对象不再存在，则返回 `Py_None`。

  2.2 新版功能.

  警告

  该函数返回被引用对象的一个**借来的引用**。这意味着除非你很清楚在你使用期间这个对象不可能被销毁，否则你应该始终对该对象调用 `Py_INCREF()`。

PyObject* `PyWeakref_GET_OBJECT`(PyObject *ref)
  Return value: Borrowed reference.

  类似 `PyWeakref_GetObject()`，但实现为一个不做类型检查的宏。

  2.2 新版功能.