splucena
splucena

Reputation: 159

How does python decorator work on this code?

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

Upvotes: 1

Views: 51

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124928

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.

Upvotes: 2

Related Questions