1 | n/a | class Delegator: |
---|
2 | n/a | |
---|
3 | n/a | def __init__(self, delegate=None): |
---|
4 | n/a | self.delegate = delegate |
---|
5 | n/a | self.__cache = set() |
---|
6 | n/a | # Cache is used to only remove added attributes |
---|
7 | n/a | # when changing the delegate. |
---|
8 | n/a | |
---|
9 | n/a | def __getattr__(self, name): |
---|
10 | n/a | attr = getattr(self.delegate, name) # May raise AttributeError |
---|
11 | n/a | setattr(self, name, attr) |
---|
12 | n/a | self.__cache.add(name) |
---|
13 | n/a | return attr |
---|
14 | n/a | |
---|
15 | n/a | def resetcache(self): |
---|
16 | n/a | "Removes added attributes while leaving original attributes." |
---|
17 | n/a | # Function is really about resetting delagator dict |
---|
18 | n/a | # to original state. Cache is just a means |
---|
19 | n/a | for key in self.__cache: |
---|
20 | n/a | try: |
---|
21 | n/a | delattr(self, key) |
---|
22 | n/a | except AttributeError: |
---|
23 | n/a | pass |
---|
24 | n/a | self.__cache.clear() |
---|
25 | n/a | |
---|
26 | n/a | def setdelegate(self, delegate): |
---|
27 | n/a | "Reset attributes and change delegate." |
---|
28 | n/a | self.resetcache() |
---|
29 | n/a | self.delegate = delegate |
---|
30 | n/a | |
---|
31 | n/a | if __name__ == '__main__': |
---|
32 | n/a | from unittest import main |
---|
33 | n/a | main('idlelib.idle_test.test_delegator', verbosity=2) |
---|