jpayne@68: class Delegator: jpayne@68: jpayne@68: def __init__(self, delegate=None): jpayne@68: self.delegate = delegate jpayne@68: self.__cache = set() jpayne@68: # Cache is used to only remove added attributes jpayne@68: # when changing the delegate. jpayne@68: jpayne@68: def __getattr__(self, name): jpayne@68: attr = getattr(self.delegate, name) # May raise AttributeError jpayne@68: setattr(self, name, attr) jpayne@68: self.__cache.add(name) jpayne@68: return attr jpayne@68: jpayne@68: def resetcache(self): jpayne@68: "Removes added attributes while leaving original attributes." jpayne@68: # Function is really about resetting delegator dict jpayne@68: # to original state. Cache is just a means jpayne@68: for key in self.__cache: jpayne@68: try: jpayne@68: delattr(self, key) jpayne@68: except AttributeError: jpayne@68: pass jpayne@68: self.__cache.clear() jpayne@68: jpayne@68: def setdelegate(self, delegate): jpayne@68: "Reset attributes and change delegate." jpayne@68: self.resetcache() jpayne@68: self.delegate = delegate jpayne@68: jpayne@68: if __name__ == '__main__': jpayne@68: from unittest import main jpayne@68: main('idlelib.idle_test.test_delegator', verbosity=2)