Skip to content

Instantly share code, notes, and snippets.

@worldofchris
Created May 23, 2020 05:58
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 worldofchris/9ab3622edae091984c9ce02fc73d8def to your computer and use it in GitHub Desktop.
Save worldofchris/9ab3622edae091984c9ce02fc73d8def to your computer and use it in GitHub Desktop.
Python example decorator
"""
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