function decorators

Nick Donohue ndonohue at gmail.com
Wed Sep 29 00:02:14 CEST 2010


I came across this code just now:

def time_me(function):
  def wrap(*arg):
    start = time.time()
    r = function(*arg)
    end = time.time()
    print "%s (%0.3f ms)" %(function.func_name, (end-start)*1000)
  return wrap

@time_me
def some_function(somearg)

some_function(arg)

I've been looking online about what I think is going on, and from what
I can tell this code is using function decorators.

I guess what I'm asking is if someone could tell me what exactly is
going on in this code - how is it different from passing:
time_me(some_function(123))? I've tried it this way and it works.

why would I use these? wouldn't it be more flexible to not write the
decorator before the function definition, so I could choose to wrap it
or not?

thanks



More information about the Python-list mailing list