I avoided decorators for so long. First, I pretended they didn't exist. Then, I treated them like a magic spell—I'd use some of the common ones and simply copy how they're used in the documentation. And each time I tried to learn how they work, I'd give up pretty quickly.But eventually, I got there. And once I finally understood how decorators work, my reaction was, "Is that it?" As with many complex topics, the magic goes away once you get it, and what's left makes perfect sense.So, let me take you on a journey similar to the one I took to demystify decorators.I split this decorator quest into seven parts. This article covers Parts 1 and 2. These are the most important parts to understand decorators. Take your time. I'll publish Parts 3 to 7 in a separate article soon.Decorators are powerful for adding reusable functionality to functions without the need to define a new function. You’ll see them often in Python, and you may even need to write your own one at some point.Part 1 introduces one of the main characters in this story—closures. We'll get to decorators in Part 2 later in this article.Let's say you want to keep track of all the arguments you pass to all the calls to print() throughout your code. And no, you don't want to have to do this manually. You want your code to automatically keep a record of any argument you use when you call print().Start by defining a new function to replace the built-in print(). Although you could name this new function print, I'll add a trailing underscore in this example to keep the code focused on what really matters. First, here's a version that won't work as intended—the code runs without errors but doesn't achieve the result you need:All code blocks are available in text format at the end of this article • #1 • The code images used in this article are created using Snappify. [Affiliate link]The new print_() function calls the built-in print(), but it also appends the argument to a list named data. Look for the trailing unders...
First seen: 2025-04-20 23:29
Last seen: 2025-04-23 15:46