[Tutor] decorators

Steven D'Aprano steve at pearwood.info
Fri Jun 24 18:18:50 CEST 2011


Prasad, Ramit wrote:
> Excellent explanation Steven; I understood the mechanical basics but this has made the reason behind it a lot clearer. 
> 
> If test_argument is only being passed the function how does it have access to the arguments? 

It doesn't. There are three functions involved. The first is the 
decorator, test_argument. It only receives one argument, the function func.

The second is func itself, the original function before it is wrapped.

The third is the inner function of the decorator, which wraps func. Only 
the last two functions, func and the wrapped func, ever see the function 
arguments.

An example may make it more clear:

def decorator(f):
     # Wrap function f.
     print("decorator is called with argument %s" % f)
     print("creating inner function...")
     def inner(x):
         print("wrapper function called with argument %s" % x)
         return f(x+100)
     print("now returning the wrapped function")
     return inner

@decorator
def func(x):
     print("original function called with argument %s" % x)

func(1)
func(2)
func(3)


When I execute that code, I get this output printed:

decorator is called with argument <function func at 0x922a16c>
creating inner function...
now returning the wrapped function
wrapper function called with argument 1
original function called with argument 101
wrapper function called with argument 2
original function called with argument 102
wrapper function called with argument 3
original function called with argument 103


-- 
Steven


More information about the Tutor mailing list