decorator question

Duncan Booth duncan.booth at invalid.invalid
Mon Jan 9 04:01:12 EST 2006


Bengt Richter wrote:

>>is it possible to pass parameters to a decorator function?
>>
> Yes, but then the function must return the same kind of thing
> a bare decorator-function name would have, which is a function
> able to take a single argument of a function and return a function.
>
> So your decorator won't take f as an argument, just the optional
> logfile, and it will return a function that does the wrapping like the
> original decorator. 

This sounds to me like something that should be done using a decorator. 
e.g. (everything from 'def timelogger' onwards is unchanged from the OP's 
code):

def decoratorwithargs(f):
	def wrapper(*args,**kw):
		def inner(target):
			return f(target, *args, **kw)
		return inner
	return wrapper

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

@timelogger(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

(I think the logfile output could do with some newlines.)



More information about the Python-list mailing list