[Tutor] Decorators and function arguments.
Kent Johnson
kent37 at tds.net
Wed Sep 19 19:22:34 CEST 2007
Noufal Ibrahim wrote:
> My question is whether this is a valid use for a decorator and whether
> this kind of usage is pythonic. If not, are there any better ways to do
> this?
It seems like a bit of a hack to me. I guess you change the way you call
run_command to include desc?
You could add another parameter to profile() which says whether to
include parameters (or how many parameters) in the output. Something like
def profile(stagename, params=0):
def decorator(fn):
def _wrapper(*args):
start_time = time.time()
ret = apply(fn, args)
end_time = time.time()
running_time = end_time - start_time
if params:
paramStr = ' (' + ', '.join(map(repr, args[:params])) + ')'
else:
paramStr = ''
print "Stage %s%s took %f seconds to run"%(stagename,paramStr,
running_time)
return ret
return _wrapper
return decorator
Then you would say
@profile("Running command", params=1)
def run_command(...):
Kent
More information about the Tutor
mailing list