delegator.py 1.0 KB

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