blob: dc2a1aaeeab74eedf6a677da1b5c44a088714bb0 [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001class Delegator:
2
David Scherer7aced172000-08-15 01:13:23 +00003 def __init__(self, delegate=None):
4 self.delegate = delegate
Terry Jan Reedyacd5f812013-06-30 18:37:05 -04005 self.__cache = set()
Terry Jan Reedy33a8fb92016-05-15 22:06:49 -04006 # Cache is used to only remove added attributes
7 # when changing the delegate.
David Scherer7aced172000-08-15 01:13:23 +00008
9 def __getattr__(self, name):
10 attr = getattr(self.delegate, name) # May raise AttributeError
11 setattr(self, name, attr)
Terry Jan Reedyacd5f812013-06-30 18:37:05 -040012 self.__cache.add(name)
David Scherer7aced172000-08-15 01:13:23 +000013 return attr
14
15 def resetcache(self):
Terry Jan Reedy33a8fb92016-05-15 22:06:49 -040016 "Removes added attributes while leaving original attributes."
17 # Function is really about resetting delagator dict
18 # to original state. Cache is just a means
Kurt B. Kaisere0712772007-08-23 05:25:55 +000019 for key in self.__cache:
David Scherer7aced172000-08-15 01:13:23 +000020 try:
21 delattr(self, key)
22 except AttributeError:
23 pass
24 self.__cache.clear()
25
David Scherer7aced172000-08-15 01:13:23 +000026 def setdelegate(self, delegate):
Terry Jan Reedy33a8fb92016-05-15 22:06:49 -040027 "Reset attributes and change delegate."
David Scherer7aced172000-08-15 01:13:23 +000028 self.resetcache()
29 self.delegate = delegate
Terry Jan Reedy33a8fb92016-05-15 22:06:49 -040030
31if __name__ == '__main__':
32 from unittest import main
33 main('idlelib.idle_test.test_delegator', verbosity=2)