File: tracking.py

package info (click to toggle)
brian 2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,872 kB
  • sloc: python: 51,820; cpp: 2,033; makefile: 108; sh: 72
file content (80 lines) | stat: -rw-r--r-- 2,262 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from collections import defaultdict
from weakref import ref

__all__ = ["Trackable"]


class InstanceTrackerSet(set):
    """
    A `set` of `weakref.ref` to all existing objects of a certain class.

    Should not normally be directly used.
    """

    def add(self, value):
        """
        Adds a `weakref.ref` to the ``value``
        """
        # The second argument to ref is a callback that is called with the
        # ref as argument when the object has been deleted, here we just
        # remove it from the set in that case
        wr = ref(value, self.remove)
        set.add(self, wr)

    def remove(self, value):
        """
        Removes the ``value`` (which should be a weakref) if it is in the set

        Sometimes the value will have been removed from the set by `clear`,
        so we ignore `KeyError` in this case.
        """
        try:
            set.remove(self, value)
        except KeyError:
            pass


class InstanceFollower:
    """
    Keep track of all instances of classes derived from `Trackable`

    The variable ``__instancesets__`` is a dictionary with keys which are class
    objects, and values which are `InstanceTrackerSet`, so
    ``__instanceset__[cls]`` is a set tracking all of the instances of class
    ``cls`` (or a subclass).
    """

    instance_sets = defaultdict(InstanceTrackerSet)

    def add(self, value):
        for (
            cls
        ) in (
            value.__class__.__mro__
        ):  # MRO is the Method Resolution Order which contains all the superclasses of a class
            self.instance_sets[cls].add(value)

    def get(self, cls):
        return self.instance_sets[cls]


class Trackable:
    """
    Classes derived from this will have their instances tracked.

    The `classmethod` `__instances__()` will return an `InstanceTrackerSet`
    of the instances of that class, and its subclasses.
    """

    __instancefollower__ = (
        InstanceFollower()
    )  # static property of all objects of class derived from Trackable

    def __new__(typ, *args, **kw):
        obj = object.__new__(typ)
        obj.__instancefollower__.add(obj)
        return obj

    @classmethod
    def __instances__(cls):
        return cls.__instancefollower__.get(cls)