[Tutor] Decorators and function arguments.
noufal at airtelbroadband.in
Wed Sep 19 18:57:40 CEST 2007
I have a question regarding the use of some decorators.
In my program, I have functions like this
These functions are for various stages of the program. Now, I need
to profile these functions (find out how long they take) and record
this information in some kind of log. So I write a decorator like this
start_time = time.time()
ret = apply(fn, args)
end_time = time.time()
running_time = end_time - start_time
print "Stage %s took %f seconds to run"%(stagename,running_time)
And the functions above get this as a decorator like so
@profile("Processing command line")
So far so good. Now the problem. With the "run_command" function, I need
the profiling function to print out the name of the command as well as
the stage. So instead of printing
"Stage running command took 0.30 seconds to run"
I need something like
"Stage running command (du -sh) took 2.0 seconds to run"
How I've accomplished this right now is to pass an extra optional named
parameter to all the functions called "desc". The definition of wrapper
inside the decorator is then changed to
description = dargs.get("desc","")
print "Stage %s (%s) took %f seconds to \
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? I need some functions in my program to be timed and the timings to
be recorded into a separate database. This program acts as a wrapper for
various other programs and I need information on how much time they're
taking to do their work.
Thanks in advance,
More information about the Tutor