Python Glossary Русский

Python 3.4+weakrefterm

weakref.WeakMethod

weak references

A weak reference to a bound method that lives as long as its object does. A plain weakref.ref(obj.method) dies immediately.

Syntax

r = weakref.WeakMethod(obj.method); r()

obj.method is a new MethodType object on every access, and nothing else refers to it, so weakref.ref(obj.method)() is None right away. WeakMethod keeps separate weak references to the object and to the function and rebuilds the method when you call r(). The typical use is event subscribers: a handler method must not keep its object alive.

Examples

import weakref
class Button:
    def click(self):
        return 'clicked'
b = Button()
print(weakref.ref(b.click)())  # → None
m = weakref.WeakMethod(b.click)
print(m()())  # → clicked
del b
print(m())  # → None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy