How does python decorator work on this code

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m trying to understand python decorator. I thought somehow I understood decorator until I wrote this code.

def func():
     def wrapper(x):
        return x()
     return wrapper 

@func()
def b():
    return sum

a = b([1,2,5])
print a # Result: 8 How?

e = b # pass b function to variable e
f = e([3,4,8]) # called function b stored in variable e
print f # Result: 15
# I understand how 15 is derived here

Answers

You used func as a decorator factory , which produces a decorator that called the original b() to produce the decoration result. Here s what happens:

    • @func() executes func() first , then uses the return value as the decorator. func() returns wrapper, so wrapper is used as the decorator.
    • wrapper(b) sets x = b, and returns x(). So the result of the decorator is b(), which is sum. Python sets b = sum
    • You called b([1, 2, 5]) where b = sum. So sum([1, 2, 5]) is returned.

The important part here is that you used func not as a decorator, but as a decorator factory (calling it produces the actual decorator), which adds a layer of indirection.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/38606403/how-does-python-decorator-work-on-this-code

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils