Skip to content

Instantly share code, notes, and snippets.

@allenaven
Created November 9, 2017 07:24
Show Gist options
  • Save allenaven/2cc9a23ef7c0fa9e56fa1ca2a3049e74 to your computer and use it in GitHub Desktop.
Save allenaven/2cc9a23ef7c0fa9e56fa1ca2a3049e74 to your computer and use it in GitHub Desktop.
Python function decorators are great at retaining state information for use during the function call
#!/usr/bin/env python
# Function decorators are great at retaining state information for use
# during the function call
class tracer:
def __init__(self, func):
self.calls = 0
self.func = func
def __call__(self, *args, **kwargs):
self.calls += 1
print('call {} to {}'.format(self.calls, self.func.__name__))
return self.func(*args, **kwargs)
@tracer
def spam(a, b, c):
print(a + b + c)
@tracer
def ham(d, e, f):
print(d + e + f)
spam(1, 2, 3)
ham('orange', 'purple', 'mauve')
spam(4,5,6)
ham('yes ', 'no ', 'maybe')
## RETURNS:
>>> call 1 to spam
>>> 6
>>> call 1 to ham
>>> orangepurplemauve
>>> call 2 to spam
>>> 15
>>> call 2 to ham
>>> yes no maybe
@allenaven
Copy link
Author

allenaven commented Nov 9, 2017

Closely based on material in Lutz Learning Python Chapter 39: Decorators

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment