Salih
Salih

Reputation: 381

Unable to understand the python decorator function

Please note, I don't know what exactly to give subject to this question.

I'm going through a tutorial for creating decorators. The doubt is in the third line. I do not fully understand it.

I know that count is not a function. Because, I changed wrapper.count to wrapper.cnt and the code worked. But when i changed the wrapper.count to wrap.count, then it errors out.

That means we're referencing the wrapper function from within wrapper function itself. Fine, but what is the associated .count really ?

Please explain. Below is the code.

def counter(func):
  def wrapper(*args, **kwargs):
    wrapper.count += 1
    # Call the function being decorated and return the result
    func()
    return wrapper.count
  wrapper.count = 0
  # Return the new decorated function
  return wrapper

# Decorate foo() with the counter() decorator
@counter
def foo():
  print('calling foo()')

foo()
foo()

print('foo() was called {} times.'.format(foo.count))

Upvotes: 1

Views: 258

Answers (2)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9766

Python treat functions as objects, which means that you can assign values to functions dynamically.

def hello():
    print(hello.some_variable)

hello.some_variable = 'Hello!'
hello()  # Prints 'Hello!'

hello.some_variable = 'Goodbye!'
hello()  # Prints 'Goodbye!'

So what's happening is that the decorator is assigning the variable count to the wrapped function (in this case foo). Then it access and increments this variable from foo, which you then print.

Upvotes: 1

Samwise
Samwise

Reputation: 71562

wrapper.count = 0

wrapper.count is an int. It starts with the value 0 and increments each time you say wrapper.count += 1.

Upvotes: 0

Related Questions