Skip to content

Instantly share code, notes, and snippets.

@Neanderthal
Created December 16, 2019 16:17
Show Gist options
  • Select an option

  • Save Neanderthal/f2a2107c7c14cd21e5fadd4ffab94132 to your computer and use it in GitHub Desktop.

Select an option

Save Neanderthal/f2a2107c7c14cd21e5fadd4ffab94132 to your computer and use it in GitHub Desktop.
class decorator for timing
#https://www.codementor.io/@sheena/advanced-use-python-decorators-class-function-du107nxsv
def time_all_class_methods(Cls):
class NewCls(object):
def __init__(self,*args,**kwargs):
self.oInstance = Cls(*args,**kwargs)
def __getattribute__(self,s):
"""
this is called whenever any attribute of a NewCls object is accessed. This function first tries to
get the attribute off NewCls. If it fails then it tries to fetch the attribute from self.oInstance (an
instance of the decorated class). If it manages to fetch the attribute from self.oInstance, and
the attribute is an instance method then `time_this` is applied.
"""
try:
x = super(NewCls,self).__getattribute__(s)
except AttributeError:
pass
else:
return x
x = self.oInstance.__getattribute__(s)
if type(x) == type(self.__init__): # it is an instance method
return time_this(x) # this is equivalent of just decorating the method with time_this
else:
return x
return NewCls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment