spacepaste

  1.  
  2. # method wrapper 1
  3. class Foo:
  4. _methods = {...}
  5. def __getattr__(self, name):
  6. if name in _methods:
  7. return getattr(self._wrapped, name)
  8. raise AttributeError(name)
  9. # method wrapper 2
  10. class Foo:
  11. pass
  12. def add_wrapper(cls, method):
  13. def wrapper(self, *args, **kwargs):
  14. return getattr(self._wrapped, method)(*args, **kwargs)
  15. setattr(cls, method, wrapper)
  16. for method in methods:
  17. add_wrapper(Foo, method)
  18. # method wrapper 3
  19. class Foo:
  20. pass
  21. def add_wrapper(cls, method):
  22. code = text.dedent("""
  23. def wrapper(self, *args, **kwargs):
  24. return self._wrapped.{}(*args, **kwargs)
  25. """)
  26. ns = {}
  27. exec(code, ns)
  28. setattr(cls, method, ns["wrapper"])
  29. for method in methods:
  30. add_wrapper(Foo, methods)
  31.