function decorators

Terry Reedy tjreedy at
Wed Sep 29 02:57:16 CEST 2010

On 9/28/2010 6:02 PM, Nick Donohue wrote:
> 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)

As others noted, this is an bad example of a decorator. Please forget 
it. Let us move on...

def func_name(*args): pass

is syntactic sugar for (which is to say, is almost and for practical 
purposes is exactly equivalent to)

def func_name(*args): pass
func_name = deco(func_name)

Indeed, Python did well without them until they were added. But there 
are 2 advantages of the decorator syntax:

1. Without it, one write (and read!) func_name 3 times instead of 1. One 
of the use cases that motivated decorators was a situation where someone 
was required to wrap numerous functions with stylized names about 30 
chars long, like 'get_hopscotch_version_a_code_123x76'

2. Understanding the code may require that one know that it will never 
see the light of day as is. If the body is several lines, the wrapping 
call may be hard to see. To put it another way, the wrapping calls often 
belong near the doc string since they are part of a high-level overview 
of the function.

Terry Jan Reedy

More information about the Python-list mailing list