Created
May 23, 2020 05:58
-
-
Save worldofchris/9ab3622edae091984c9ce02fc73d8def to your computer and use it in GitHub Desktop.
Python example decorator
This file contains hidden or 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
""" | |
Quick reminder of how decorators work | |
""" | |
from functools import wraps | |
def goat_inspect(f): | |
""" | |
^^^ this is the name of our decorator - interface | |
""" | |
@wraps(f) | |
def wrapper(*args, **kwds): | |
""" | |
This is the impl, a wrapper that wraps a function 'f' | |
""" | |
print('Will it be a goat?') | |
f('goat', *args, **kwds) | |
print('Was it a goat?') | |
return wrapper | |
@goat_inspect | |
def iam(expected, actual): | |
""" | |
Decorated function. Takes two params one from the caller | |
one injected by the wrapper | |
""" | |
print(f'I am not a {expected}, I am a {actual}') | |
# Now we can call our decorated function: | |
iam('hen') | |
""" | |
Here's what we should see: | |
Will it be a goat? | |
I am not a goat, I am a hen | |
Was it a goat? | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment