Last active
January 7, 2023 18:06
-
-
Save wbolster/29d7eb96d25b6da0d75203299d487000 to your computer and use it in GitHub Desktop.
python joke code abusing the @ operator to ‘extend’ decorator syntax
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
""" | |
This is joke^Wenterprise code ab^H^Husing the ‘@’ operator to simulate | |
applying multiple decorators on a single line of code. | |
""" | |
# © 2022 wouter bolsterlee, licensed under SPDX BSD-3-Clause | |
import functools | |
# helper class and the magic ‘@stacked’ decorator itself | |
class _Stacked: | |
def __init__(self, decorators): | |
self.decorators = decorators | |
def __matmul__(self, other): | |
return type(self)(self.decorators + [other]) | |
def __call__(self, f): | |
for d in reversed(self.decorators): | |
f = d(f) | |
return f | |
stacked = _Stacked([]) | |
# two example decorators that simply print what they're doing | |
def decorator1(f): | |
print(f"🚧 setting up decorator 1 for {f.__name__}()") | |
@functools.wraps(f) | |
def decorator(*args, **kwargs): | |
print("🚀 decorator 1 runs") | |
return f(*args, **kwargs) | |
return decorator | |
def decorator2(f): | |
print(f"🚧 setting up decorator 2 for {f.__name__}()") | |
@functools.wraps(f) | |
def decorator(*args, **kwargs): | |
print("🌌 decorator 2 runs") | |
return f(*args, **kwargs) | |
return decorator | |
# lo and behold | |
@stacked @decorator1 @decorator2 | |
def f(s): | |
print(f"{s} profit!") | |
@stacked @decorator1 @decorator2 | |
def g(s): | |
print(f"{s} more profit!") | |
print("😬 ready to run?") | |
f("🤑") | |
g("💰") | |
# output: | |
# | |
# 🚧 setting up decorator 2 for f() | |
# 🚧 setting up decorator 1 for f() | |
# 🚧 setting up decorator 2 for g() | |
# 🚧 setting up decorator 1 for g() | |
# 😬 ready to run? | |
# 🚀 decorator 1 runs | |
# 🌌 decorator 2 runs | |
# 🤑 profit! | |
# 🚀 decorator 1 runs | |
# 🌌 decorator 2 runs | |
# 💰 more profit! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👏🏻