Posted By

magicrebirth on 12/22/09


Tagged

class python


Versions (?)

Python: monkeyPatch methods


 / Published in: Python
 

  1. """
  2. These are internal helpers. Do not rely on their presence.
  3.  
  4. http://mail.python.org/pipermail/python-dev/2008-January/076194.html
  5. """
  6.  
  7.  
  8. def monkeypatch_method(cls):
  9. """
  10. A decorator to add a single method to an existing class::
  11.  
  12. @monkeypatch_method(<someclass>)
  13. def <newmethod>(self, [...]):
  14. pass
  15. """
  16.  
  17. def decorator(func):
  18. setattr(cls, func.__name__, func)
  19. return func
  20. return decorator
  21.  
  22.  
  23. def monkeypatch_property(cls):
  24. """
  25. A decorator to add a single method as a property to an existing class::
  26.  
  27. @monkeypatch_property(<someclass>)
  28. def <newmethod>(self, [...]):
  29. pass
  30. """
  31.  
  32. def decorator(func):
  33. setattr(cls, func.__name__, property(func))
  34. return func
  35. return decorator
  36.  
  37.  
  38. def monkeypatch_class(name, bases, namespace):
  39. """
  40. A metaclass to add a number of methods (or other attributes) to an
  41. existing class, using a convenient class notation::
  42.  
  43. class <newclass>(<someclass>):
  44. __metaclass__ = monkeypatch_class
  45. def <method1>(...): ...
  46. def <method2>(...): ...
  47. ...
  48. """
  49.  
  50. assert len(bases) == 1, "Exactly one base class required"
  51. base = bases[0]
  52. for name, value in namespace.iteritems():
  53. if name != "__metaclass__":
  54. setattr(base, name, value)
  55. return base

Report this snippet  

You need to login to post a comment.