Created
August 9, 2021 10:37
-
-
Save Rustam-Z/44fd3b6a806cc33a1fe0fdc483f58a31 to your computer and use it in GitHub Desktop.
Counting how many times function was called
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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