David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 1 | class Delegator: |
| 2 | |
David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 3 | def __init__(self, delegate=None): |
| 4 | self.delegate = delegate |
Terry Jan Reedy | acd5f81 | 2013-06-30 18:37:05 -0400 | [diff] [blame] | 5 | self.__cache = set() |
Terry Jan Reedy | 33a8fb9 | 2016-05-15 22:06:49 -0400 | [diff] [blame] | 6 | # Cache is used to only remove added attributes |
| 7 | # when changing the delegate. |
David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 8 | |
| 9 | def __getattr__(self, name): |
| 10 | attr = getattr(self.delegate, name) # May raise AttributeError |
| 11 | setattr(self, name, attr) |
Terry Jan Reedy | acd5f81 | 2013-06-30 18:37:05 -0400 | [diff] [blame] | 12 | self.__cache.add(name) |
David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 13 | return attr |
| 14 | |
| 15 | def resetcache(self): |
Terry Jan Reedy | 33a8fb9 | 2016-05-15 22:06:49 -0400 | [diff] [blame] | 16 | "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. Kaiser | e071277 | 2007-08-23 05:25:55 +0000 | [diff] [blame] | 19 | for key in self.__cache: |
David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 20 | try: |
| 21 | delattr(self, key) |
| 22 | except AttributeError: |
| 23 | pass |
| 24 | self.__cache.clear() |
| 25 | |
David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 26 | def setdelegate(self, delegate): |
Terry Jan Reedy | 33a8fb9 | 2016-05-15 22:06:49 -0400 | [diff] [blame] | 27 | "Reset attributes and change delegate." |
David Scherer | 7aced17 | 2000-08-15 01:13:23 +0000 | [diff] [blame] | 28 | self.resetcache() |
| 29 | self.delegate = delegate |
Terry Jan Reedy | 33a8fb9 | 2016-05-15 22:06:49 -0400 | [diff] [blame] | 30 | |
| 31 | if __name__ == '__main__': |
| 32 | from unittest import main |
| 33 | main('idlelib.idle_test.test_delegator', verbosity=2) |