Last active
November 23, 2017 22:01
-
-
Save ryanwilsonperkin/fa17c0d19fcf0a0b499d4fad04c650e2 to your computer and use it in GitHub Desktop.
Different types of decorators
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
# 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