1 # Copyright 2015, Tresys Technology, LLC 2 # 3 # This file is part of SETools. 4 # 5 # SETools is free software: you can redistribute it and/or modify 6 # it under the terms of the GNU Lesser General Public License as 7 # published by the Free Software Foundation, either version 2.1 of 8 # the License, or (at your option) any later version. 9 # 10 # SETools is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU Lesser General Public License for more details. 14 # 15 # You should have received a copy of the GNU Lesser General Public 16 # License along with SETools. If not, see 17 # <http://www.gnu.org/licenses/>. 18 # 19 from weakref import WeakKeyDictionary 20 21 22 class DiffResultDescriptor(object): 23 24 """Descriptor for managing diff results.""" 25 26 # @properties could be used instead, but there are so 27 # many result attributes, this will keep the code cleaner. 28 29 def __init__(self, diff_function): 30 self.diff_function = diff_function 31 32 # use weak references so instances can be 33 # garbage collected, rather than unnecessarily 34 # kept around due to this descriptor. 35 self.instances = WeakKeyDictionary() 36 37 def __get__(self, obj, objtype=None): 38 if obj is None: 39 return self 40 41 if self.instances.setdefault(obj, None) is None: 42 diff = getattr(obj, self.diff_function) 43 diff() 44 45 return self.instances[obj] 46 47 def __set__(self, obj, value): 48 self.instances[obj] = value 49