| 1 |
from collections import defaultdict |
| 2 |
from weakref import ref |
| 3 |
|
| 4 |
__all__ = ["Trackable"] |
| 5 |
|
| 6 |
|
| 7 |
class InstanceTrackerSet(set): |
| 8 |
""" |
| 9 |
A `set` of `weakref.ref` to all existing objects of a certain class. |
| 10 |
|
| 11 |
Should not normally be directly used. |
| 12 |
""" |
| 13 |
|
| 14 |
def add(self, value): |
| 15 |
""" |
| 16 |
Adds a `weakref.ref` to the ``value`` |
| 17 |
""" |
| 18 |
# The second argument to ref is a callback that is called with the |
| 19 |
# ref as argument when the object has been deleted, here we just |
| 20 |
# remove it from the set in that case |
| 21 |
wr = ref(value, self.remove) |
| 22 |
set.add(self, wr) |
| 23 |
|
| 24 |
def remove(self, value): |
| 25 |
""" |
| 26 |
Removes the ``value`` (which should be a weakref) if it is in the set |
| 27 |
|
| 28 |
Sometimes the value will have been removed from the set by `clear`, |
| 29 |
so we ignore `KeyError` in this case. |
| 30 |
""" |
| 31 |
try: |
| 32 |
set.remove(self, value) |
| 33 |
except KeyError: |
| 34 |
pass |
| 35 |
|
| 36 |
|
| 37 |
class InstanceFollower: |
| 38 |
""" |
| 39 |
Keep track of all instances of classes derived from `Trackable` |
| 40 |
|
| 41 |
The variable ``__instancesets__`` is a dictionary with keys which are class |
| 42 |
objects, and values which are `InstanceTrackerSet`, so |
| 43 |
``__instanceset__[cls]`` is a set tracking all of the instances of class |
| 44 |
``cls`` (or a subclass). |
| 45 |
""" |
| 46 |
|
| 47 |
instance_sets = defaultdict(InstanceTrackerSet) |
| 48 |
|
| 49 |
def add(self, value): |
| 50 |
for cls in value.__class__.__mro__: # MRO is the Method Resolution Order which contains all the superclasses of a class |
| 51 |
self.instance_sets[cls].add(value) |
| 52 |
|
| 53 |
def get(self, cls): |
| 54 |
return self.instance_sets[cls] |
| 55 |
|
| 56 |
|
| 57 |
class Trackable: |
| 58 |
""" |
| 59 |
Classes derived from this will have their instances tracked. |
| 60 |
|
| 61 |
The `classmethod` `__instances__()` will return an `InstanceTrackerSet` |
| 62 |
of the instances of that class, and its subclasses. |
| 63 |
""" |
| 64 |
|
| 65 |
__instancefollower__ = ( |
| 66 |
InstanceFollower() |
| 67 |
) # static property of all objects of class derived from Trackable |
| 68 |
|
| 69 |
def __new__(typ, *args, **kw): |
| 70 |
obj = object.__new__(typ) |
| 71 |
obj.__instancefollower__.add(obj) |
| 72 |
return obj |
| 73 |
|
| 74 |
@classmethod |
| 75 |
def __instances__(cls): |
| 76 |
return cls.__instancefollower__.get(cls) |