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