| 1 | """ |
| 2 | Caches that can freeze when the annotator needs it. |
| 3 | """ |
| 4 | |
| 5 | # |
| 6 | # _freeze_() protocol: |
| 7 | # user-defined classes can define a method _freeze_(), which |
| 8 | # is called when a prebuilt instance is found. If the method |
| 9 | # returns True, the instance is considered immutable and becomes |
| 10 | # a SomePBC(). Otherwise it's just SomeInstance(). The method |
| 11 | # should force away any laziness that remains in the instance. |
| 12 | # |
| 13 | # Cache class: |
| 14 | # a cache meant to map a finite number of keys to values. |
| 15 | # It is normally extended lazily, until it contains all possible |
| 16 | # keys. The _annspecialcase_ attribute of the getorbuild() method |
| 17 | # forces the annotator to decode the argument's annotations, |
| 18 | # which must be constants or SomePBCs, actually call the |
| 19 | # method with all possible combinations, and gather the results. |
| 20 | # The idea is to completely fill the cache at annotation-time, |
| 21 | # using the information collected by the annotator itself about |
| 22 | # what the keys can actually be. |
| 23 | # |
| 24 | # Cache must be subclassed, and a _build() method provided. |
| 25 | # Be sure to call the parent __init__() if you override it. |
| 26 | # |
| 27 | |
| 28 | try: |
| 29 | from threading import RLock |
| 30 | lock = RLock() # multithreading protection |
| 31 | except ImportError: |
| 32 | lock = None |
| 33 | |
| 34 | |
| 35 | class Cache(object): |
| 36 | def __init__(self): |
| 37 | self.content = {} |
| 38 | self._building = {} |
| 39 | |
| 40 | def getorbuild(self, key): |
| 41 | if lock: lock.acquire() |
| 42 | try: |
| 43 | try: |
| 44 | return self.content[key] |
| 45 | except KeyError: |
| 46 | if key in self._building: |
| 47 | raise RuntimeError("%s recursive building of %r" % |
| 48 | (self, key)) |
| 49 | self._building[key] = True |
| 50 | try: |
| 51 | result = self._build(key) |
| 52 | self.content[key] = result |
| 53 | finally: |
| 54 | del self._building[key] |
| 55 | self._ready(result) |
| 56 | return result |
| 57 | finally: |
| 58 | if lock: lock.release() |
| 59 | getorbuild._annspecialcase_ = "specialize:memo" |
| 60 | |
| 61 | def __repr__(self): |
| 62 | return "<Cache %r (%i items)>" % (self.__class__.__name__, len(self.content)) |
| 63 | |
| 64 | def _ready(self, result): |
| 65 | pass |
| 66 | |
| 67 | def _freeze_(self): |
| 68 | # needs to be SomePBC, but otherwise we can't really freeze the |
| 69 | # cache because more getorbuild() calls might be discovered later |
| 70 | # during annotation. |
| 71 | return True |