Zsolt Haraszti | dafefe1 | 2016-11-14 21:29:58 -0800 | [diff] [blame] | 1 | # |
| 2 | # Copyright 2016 the original author or authors. |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | # limitations under the License. |
| 15 | # |
| 16 | from _weakref import ref |
| 17 | from weakref import KeyedRef |
| 18 | from collections import OrderedDict |
| 19 | |
| 20 | |
| 21 | class OrderedWeakValueDict(OrderedDict): |
| 22 | """ |
| 23 | Modified OrderedDict to use weak references as values. Entries disappear |
| 24 | automatically if the referred value has no more strong reference pointing |
| 25 | ot it. |
| 26 | |
| 27 | Warning, this is not a complete implementation, only what is needed for |
| 28 | now. See test_ordered_wealvalue_dict.py to see what is tested behavior. |
| 29 | """ |
| 30 | def __init__(self, *args, **kw): |
| 31 | def remove(wr, selfref=ref(self)): |
| 32 | self = selfref() |
| 33 | if self is not None: |
| 34 | super(OrderedWeakValueDict, self).__delitem__(wr.key) |
| 35 | self._remove = remove |
| 36 | super(OrderedWeakValueDict, self).__init__(*args, **kw) |
| 37 | |
| 38 | def __setitem__(self, key, value): |
| 39 | super(OrderedWeakValueDict, self).__setitem__( |
| 40 | key, KeyedRef(value, self._remove, key)) |
| 41 | |
| 42 | def __getitem__(self, key): |
| 43 | o = super(OrderedWeakValueDict, self).__getitem__(key)() |
| 44 | if o is None: |
| 45 | raise KeyError, key |
| 46 | else: |
| 47 | return o |
| 48 | |