Created
March 14, 2019 08:32
-
-
Save sprzedwojski/e493672ae92ca2de5ce216cd13ea856e to your computer and use it in GitHub Desktop.
A 15min primer on decorators in Python
This file contains 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
# 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