Main Content

Nesting decorators

Archive - Originally posted on "The Horse's Mouth" - 2016-11-02 06:45:18 - Graham Ellis

Python's decorators allow you to wrap a function within another. You might want to do this to report on or log some of your functions, to set timers, or to add other behaviousr to a whole group of functions. Decorators also allow you to modify the calling sequence to your methods (but be careful!); the built in staticmethod and classmethod decorators doing exacrly this by allowing static / class calls in addition to or in replacement of object calls.

Multiple decorators can be applied to a method - example from yesterday's course [here]. Here's the decorator definitionan and application.

 def reporter(f):
         def wrapped(*kd,**kwd):
                 try:
                         counter[f.__name__] += 1
                 except:
                         counter[f.__name__] = 1
                 f(*kd,**kwd)
         return wrapped
 
 def timestamp(f):
         def wrapped(*kd,**kwd):
                 now = strftime("%Y-%m-%d %H:%M:%S", gmtime())
                 print (now)
                 f(*kd,**kwd)
         return wrapped
 
 counter = {}
 
 @reporter
 @timestamp
 def brush(mostly="floor",*what,**kwds):
         # etc


Note the generic function calls and definition:
         def wrapped(*kd,**kwd):
and
                 f(*kd,**kwd)
which between them allow any parameter pattern to be passed though. But beware - you need to take special action for valuses like the documentaton string!