Created
November 9, 2017 07:24
-
-
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
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
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Closely based on material in Lutz Learning Python Chapter 39: Decorators