2000-08-14 22:13:23 -03:00
|
|
|
class Delegator:
|
|
|
|
|
|
|
|
def __init__(self, delegate=None):
|
|
|
|
self.delegate = delegate
|
2013-06-30 19:37:05 -03:00
|
|
|
self.__cache = set()
|
2016-05-15 23:06:49 -03:00
|
|
|
# Cache is used to only remove added attributes
|
|
|
|
# when changing the delegate.
|
2000-08-14 22:13:23 -03:00
|
|
|
|
|
|
|
def __getattr__(self, name):
|
|
|
|
attr = getattr(self.delegate, name) # May raise AttributeError
|
|
|
|
setattr(self, name, attr)
|
2013-06-30 19:37:05 -03:00
|
|
|
self.__cache.add(name)
|
2000-08-14 22:13:23 -03:00
|
|
|
return attr
|
|
|
|
|
|
|
|
def resetcache(self):
|
2016-05-15 23:06:49 -03:00
|
|
|
"Removes added attributes while leaving original attributes."
|
2019-06-03 01:21:15 -03:00
|
|
|
# Function is really about resetting delegator dict
|
2016-05-15 23:06:49 -03:00
|
|
|
# to original state. Cache is just a means
|
2007-08-23 02:25:55 -03:00
|
|
|
for key in self.__cache:
|
2000-08-14 22:13:23 -03:00
|
|
|
try:
|
|
|
|
delattr(self, key)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
self.__cache.clear()
|
|
|
|
|
|
|
|
def setdelegate(self, delegate):
|
2016-05-15 23:06:49 -03:00
|
|
|
"Reset attributes and change delegate."
|
2000-08-14 22:13:23 -03:00
|
|
|
self.resetcache()
|
|
|
|
self.delegate = delegate
|
2016-05-15 23:06:49 -03:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
from unittest import main
|
|
|
|
main('idlelib.idle_test.test_delegator', verbosity=2)
|