decorator question

Frank Niessink frank at niessink.com
Sun Jan 8 16:02:32 EST 2006


Schüle Daniel wrote:
> 
> (1) fails to compile
> is it possible to pass parameters to a decorator function?

Yes, I think this does what you want:

import time, sys

def timelogger(logfile=sys.stdout):
     def actual_timelogger(function):
         def wrapper(*a,**kw):
             logfile.write("started at %s" % time.ctime())
             t0 = time.time()
             function(*a, **kw)
             t1 = time.time()
             logfile.write("ended at %s" % time.ctime())
             logfile.write("diff = %f %s" % (t1-t0, "sec"))
         return wrapper
     return actual_timelogger

@timelogger(logfile=file("hierher", "a"))    ### <<<<<< (1)
def loops(a,b,c):
     sum = 0
     for i in range(a):
         for j in range(b):
             for k in range(c):
                 sum += 1


loops(100,100,100)


Cheers, Frank



More information about the Python-list mailing list