Skip to content

Instantly share code, notes, and snippets.

@sprzedwojski
Created March 14, 2019 08:32
Show Gist options
  • Save sprzedwojski/e493672ae92ca2de5ce216cd13ea856e to your computer and use it in GitHub Desktop.
Save sprzedwojski/e493672ae92ca2de5ce216cd13ea856e to your computer and use it in GitHub Desktop.
A 15min primer on decorators in Python
# DECORATORS
# https://realpython.com/primer-on-python-decorators/
# Calling higher-order functions.
# A function that takes another function and extends its behaviour (without modifying it).
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before")
res = func(*args, **kwargs)
print("After")
return res
return wrapper
# Verbose way
def say_whee():
print("Whee!")
say_whee = my_decorator(say_whee)
say_whee()
# Syntactic sugar
@my_decorator
def say_whee2(name):
print(f"Whee2 {name}!")
return f"Hi {name}!"
result = say_whee2("Bum")
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment