Skip to content

Instantly share code, notes, and snippets.

@Rustam-Z
Created August 9, 2021 10:37
Show Gist options
  • Save Rustam-Z/44fd3b6a806cc33a1fe0fdc483f58a31 to your computer and use it in GitHub Desktop.
Save Rustam-Z/44fd3b6a806cc33a1fe0fdc483f58a31 to your computer and use it in GitHub Desktop.
Counting how many times function was called
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return func(*args, **kwargs)
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))
"""
calling foo()
calling foo()
foo() was called 2 times.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment