Codenobar
Codenobar

Reputation: 41

decorating decorators in python

I am unable to understand how decorating decorators works in Python (2.7.2). I have following piece of code:

def verbose(function):
    print 'i am verbose and func is ' + function.__name__
    def wrapper2(func):
        print 'func is ' + repr(func)
        result = function(func)
        return result
    return wrapper2

@verbose
def more(function):
    print 'i am more and func is ' + function.__name__
    def wrapper1(*args, **kwargs):
        print 'args' + repr(args)
        result = function(*args)
        return result
    return wrapper1

@more
def hello(*args):
    print(sum(args))

when I run:

>>> hello(1,2,3)

this is what I get:

i am verbose and func is more
func is <function hello at 0x1015338c0>
i am more and func is hello    
args(1, 2, 3)
6

I am unable to visualize the sequence of calls that generates this output. I think the following call will still generate the same output and I am keen to understand how decorated decorators work in this specific example.

>>> verbose(more)(hello)(1,2,3)
i am verbose and func is more
func is <function hello at 0x101533d70>
i am more and func is hello
args(1, 2, 3)
6

Upvotes: 3

Views: 1345

Answers (1)

BrenBarn
BrenBarn

Reputation: 251618

Your reduction to verbose(more)(hello)(1,2,3) is correct. However, those calls happen at different times. Remember that this:

@deco
def func():
    # whatever

is the same as this:

def func():
    # whatever
func = deco(func)

So when you define more, verbose is called. When you define hello, more (the decorated version) is called. Your code is equivalent to:

def verbose(function):
    print 'i am verbose and func is ' + function.__name__
    def wrapper2(func):
        print 'func is ' + repr(func)
        result = function(func)
        return result
    return wrapper2

def more(function):
    print 'i am more and func is ' + function.__name__
    def wrapper1(*args, **kwargs):
        print 'args' + repr(args)
        result = function(*args)
        return result
    return wrapper1
more = verbose(more)

def hello(*args):
    print(sum(args))
hello = more(hello)

That should make it clear which function calls are happening when. Note that neither more nor verbose are called when you call hello(1, 2, 3). The decorators are called when the decorated function is defined not when it is called. At call time, what is called is the return value of the decorator (i.e., the functions wrapper1 and wrapper2 in your example).

Upvotes: 1

Related Questions