On this page
weakref.WeakMethod
Prev: weakref.WeakKeyDictionary | Up: weakref | Next: weakref.WeakSet
Rel: weakref.CallableProxyType, weakref.finalize, weakref.getweakrefcount, weakref.getweakrefs
Ref: docs.python.org — weakref.WeakMethod
Tags: #public #python3 #stdlib #weakref
Import
import weakref
from weakref import WeakMethod
Signature & Overview
weakref.WeakMethod(meth, callback=None)
A custom weakref.ref subclass which simulates a weak reference to a bound method, working around the lifetime problem of bound methods.
Usage
import weakref
class Greeter:
def hi(self): return 'hello'
g = Greeter()
wm = weakref.WeakMethod(g.hi)
assert wm()() == 'hello'
del g
assert wm() is None
Gotchas
- Use for bound methods instead of
weakref.ref(g.hi): Plainweakref.ref(g.hi)dies immediately because bound methods are temporary objects.
REPL Inspect
from weakref import WeakMethod
help(WeakMethod)
Linked from
Related notes
- tuts/python3/stdlib_module/weakref/WeakKeyDictionary Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/WeakSet Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/CallableProxyType Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/finalize Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/getweakrefcount Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/getweakrefs Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/proxy shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/ProxyType shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/ref shared tags: #stdlib, #weakref