blob: 9ea739a7c147e8e9ff964494c7c0f9a96c314c80 [file] [log] [blame]
khenaidoob9203542018-09-17 22:56:37 -04001#
2# Copyright 2017 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#
16from _weakref import ref
17from weakref import KeyedRef
18from collections import OrderedDict
19
20
21class 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