Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.