Skip to content

Instantly share code, notes, and snippets.

@ryanwilsonperkin
Last active November 23, 2017 22:01
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 ryanwilsonperkin/fa17c0d19fcf0a0b499d4fad04c650e2 to your computer and use it in GitHub Desktop.
Save ryanwilsonperkin/fa17c0d19fcf0a0b499d4fad04c650e2 to your computer and use it in GitHub Desktop.
Different types of decorators
# Regular decorator
def decorator(f):
def wrapped(*args, **kwargs):
print('Before')
result = f(*args, **kwargs)
print('After')
return result
return wrapped
# Regular decorator usage
@decorator
def f(x): return x ** 2
# Decorator with arguments
def decorator_with_args(before_text, after_text):
def generated_decorator(f):
def wrapped(*args, **kwargs):
print(before_text)
result = f()
print(after_text)
return result
return wrapped
return generated_decorator
# Decorator with arguments usage
@decorator_with_args('Before', 'After')
def g(x): return g ** 2
# Decorator with optional keyword arguments
def decorator_with_kwargs(before_text='foo', after_text='bar', obj=None):
if obj is None:
return functools.partial(decorator_with_kwargs, before_text=before_text, after_text=after_text)
def generated_decorator(f):
def wrapped(*args, **kwargs):
print(before_text)
result = f()
print(after_text)
return result
return wrapped
return generated_decorator
#Decorator with optional keyword arguments usage
@decorator_with_kwargs('Before', 'After')
def h(x): return x**2
# OR
@decorator_with_kwargs()
def i(x): return x**2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment