Add attribute to decorated function
Fri May 06 2022 12:41:11 GMT+0000 (Coordinated Universal Time)
Saved by
@ClemensBerteld
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
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))
content_copyCOPY
Comments