oter

Decorators are functions that modify other functions from "summary" of Fluent Python by Luciano Ramalho

Decorators are a powerful but often mystifying tool in Python programming. At heart, a decorator is just a callable that takes another function as argument (the decorated function) and returns a new function. In other words, a decorator rebinds the decorated function's name to the result of the decorator's execution. The simplest decorator that can be defined in Python is just a function that returns a function. Decorators are used in Python to modify or extend the behavior of callable objects (functions, methods, or classes) without permanently modifying the callable itself. When a decorator is applied to a function, the original function is replaced by the new function returned by the decorator. This means that the decorated function will now exhibit different behavior when called. Decorators are very versatile and can be used for a wide range of tasks, such as logging, enforcing access control and authentication, instrumentation, rate limiting, caching, and more. By wrapping a function with a decorator, you can easily add new functionality to the function without modifying its code. This makes decorators a powerful tool for keeping your code modular and easy to maintain. One important thing to note is that decorators are executed at import time, which means they are run when the module is imported, not when the decorated function is called. This is an important distinction to keep in mind when working with decorators, as it can affect the behavior of your code. Decorators can also be stacked, meaning that you can apply multiple decorators to a single function. When multiple decorators are applied to a function, they are executed in the order they are listed in the source code.
  1. Decorators are a fundamental concept in Python programming that allow you to modify the behavior of functions in a flexible and reusable way. By understanding how decorators work and how to apply them effectively, you can write cleaner, more maintainable code that is easier to extend and modify in the future.
  2. Open in app
    The road to your goals is in your pocket! Download the Oter App to continue reading your Microbooks from anywhere, anytime.
oter

Fluent Python

Luciano Ramalho

Open in app
Now you can listen to your microbooks on-the-go. Download the Oter App on your mobile device and continue making progress towards your goals, no matter where you are.