all Python 3weakrefterm
weakref.WeakSet
weak collections
A set that holds its objects through weak references: a deleted object drops out on its own. Handy for a registry of live instances or subscribers.
Syntax
s = weakref.WeakSet()
The classic example is tracking created instances of a class: a plain set in a class attribute would keep them forever and leak memory. Elements must support weak references, so numbers and strings cannot go into a WeakSet. As with WeakKeyDictionary, the size can shrink at any moment, so len() is a snapshot, not a guarantee.
Examples
import weakref
class Player:
online = weakref.WeakSet()
def __init__(self):
Player.online.add(self)
a, b = Player(), Player()
print(len(Player.online)) # → 2
del a
print(len(Player.online)) # → 1
See also
Open in the full glossarydocs.python.orgReport an inaccuracy