[Tutor] Decorators and function arguments.

Noufal Ibrahim noufal at airtelbroadband.in
Wed Sep 19 18:57:40 CEST 2007

Hello everyone,
    I have a question regarding the use of some decorators.

    In my program, I have functions like this

def process_command_line(...):

def run_command(...):

def update_db(...):

    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

def profile(stagename):
    def decorator(fn):
      def _wrapper(*args):
        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)
        return ret
      return _wrapper
    return decorator

And the functions above get this as a decorator like so

@profile("Processing command line")
def process_command_line(...):

@profile("Running command")
def run_command(...):

@profile("Updating database")
def update_db(...):

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
def _wrapper(*args,**dargs):
    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 mailing list