Decorators in Python
So, you’ve got this function. It’s written, tested, and works perfectly. Life’s good, right? Well… not quite. Because now you’re thinking, “What if we could make this even better?” Maybe we do something magical before it runs or sprinkle some fairy dust on its output.
But here’s the twist:
• We can’t touch the function (remember the O in SOLID? Open for extension, closed for modification—no backsies on that).
• We don’t want the client juggling two separate functions like some circus performer.
• And we absolutely won’t mess with the existing calling code because who loves debugging that mess?
Fear not—decorators to the rescue!
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def addSuffix(func): def wrapper(*args): return func(*args) + ". Nice to meet you." return wrapper def addSalutation(func): def wrapper(*args): return "Hello "+func(*args) return wrapper @addSalutation @addSuffix def sayMyName(name): return name print(sayMyName("Heisenberg")) |