spacepaste

  1.  
  2. def time_this(original_function):
  3. print("decorating")
  4. def new_function(*args, **kwargs):
  5. import datetime
  6. before = datetime.datetime.now
  7. x = original_function(*args, **kwargs)
  8. after = datetime.datetime.now
  9. print("Elapsed time {0}".format(after-before))
  10. return x
  11. return new_function
  12. def time_all_class_methods(Cls):
  13. class NewCls(object):
  14. def __init__(self,*args,**kwargs):
  15. self.oInstance = Cls(*args,**kwargs)
  16. def __getattribute__(self,s):
  17. try:
  18. x = super(NewCls,self).__getattribute__(s)
  19. except AttributeError:
  20. pass
  21. else:
  22. return x
  23. x = self.oInstance.__getattribute__(s)
  24. if type(x) == type(self.__init__): # it is an instance method
  25. return time_this(x) # this is equivalent of just decorating the method with time_this
  26. else:
  27. return x
  28. return NewCls
  29. #@time_all_class_methods
  30. class Foo(object):
  31. def a(self):
  32. print "entering a"
  33. import time
  34. time.sleep(3)
  35. print "exiting a"
  36. Foo = time_all_class_methods(Foo)
  37. oF = Foo
  38. oF.a()
  39. ================
  40. Error Message::
  41. File "/home/psychognite/wingProjects/limboCls.py", line 37, in <module>
  42. oF.a()
  43. AttributeError: 'NoneType' object has no attribute 'a'
  44.