Skip to content

Instantly share code, notes, and snippets.

@andriykohut
Created February 27, 2018 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriykohut/b2e7a4077b511a1a7968104242fb73a0 to your computer and use it in GitHub Desktop.
Save andriykohut/b2e7a4077b511a1a7968104242fb73a0 to your computer and use it in GitHub Desktop.
Class-based decorator with state
from functools import update_wrapper
class call_count:
def __init__(self, name):
self.__name = name
self.__count = 0
def __call__(self, fn, *args, **kwargs):
def wrapper(*args, **kwargs):
self.__count += 1
result = fn(*args, **kwargs)
print(f'[{self.__name}] {fn.__name__} called {self.__count} times')
return result
update_wrapper(self, wrapper)
return wrapper
@property
def call_count(self):
return self.__count
@call_count('counter 1')
def add(a, b):
return a + b
if __name__ == '__main__':
assert add(1, 2) == 3
assert add(3, 4) == 7
counter2 = call_count('counter2')
@counter2
def add2(a, b):
return a + b
add2(1, 1), add2(1, 1), add2(1, 1)
assert counter2.call_count == 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment