Advertisement
johnmahugu

python - run once decorator

Jul 2nd, 2015
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. def func_once(func):
  2.     "A decorator that runs a function only once."
  3.     def decorated(*args, **kwargs):
  4.         try:
  5.             return decorated._once_result
  6.         except AttributeError:
  7.             decorated._once_result = func(*args, **kwargs)
  8.             return decorated._once_result
  9.     return decorated
  10.  
  11. def method_once(method):
  12.     "A decorator that runs a method only once."
  13.     attrname = "_%s_once_result" % id(method)
  14.     def decorated(self, *args, **kwargs):
  15.         try:
  16.             return getattr(self, attrname)
  17.         except AttributeError:
  18.             setattr(self, attrname, method(self, *args, **kwargs))
  19.             return getattr(self, attrname)
  20.     return decorated
  21.  
  22. # Example, will only parse the document once
  23. @func_once
  24. def get_document():
  25.     import xml.dom.minidom
  26.     return xml.dom.minidom.parse("document.xml")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement