When I started programming with Python, if I am not mistaken, the version was 3.3. Therefore, when I started programming, decorators had been available to the Python community for a long time.
Function decorators came to Python with version 2.2 and Class decorators came to Python with version 2.6.
Personally, I see Python's Decorator feature as a very powerful feature of the language.
Actually, my aim is to make a series of articles about the most difficult to understand topics in Python. I plan to cover these topics, which are a little more than ten, one by one.
In this article, I will try to touch on every part of the Decorators topic as much as I can.
In essence, a decorator is a design pattern in Python that allows you to modify the behavior of a function or a class without changing its core structure. Decorators are a form of metaprogramming, where you're essentially writing code that manipulates other code.
You know Python resolve names using the scope given in order below:
Decorators are sit Enclosing scope, which is closely related to the Closure concept.
Key Idea: A decorator takes a function as input, adds some functionality to it, and returns a modified function.
Analogy: Think of a decorator as a gift wrapper. You have a gift (the original function), and you wrap it with decorative paper (the decorator) to make it look nicer or add extra features (like a bow or a card). The gift inside remains the same, but its presentation or associated actions are enhanced.
Most decorators in Python are implemented using functions, but you can also create decorators using classes.
Function-based decorators are more common and simpler, while class-based decorators offer additional flexibility.
def my_decorator(func): def wrapper(*args, **kwargs): # Do something before calling the decorated function print("Before function call") result = func(*args, **kwargs) # Do something after calling the decorated function print("After function call") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("World")
Explanation:
These use classes instead of functions to define decorators.
class MyDecorator: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): # Do something before calling the decorated function print("Before function call") result = self.func(*args, **kwargs) # Do something after calling the decorated function print("After function call") return result @MyDecorator def say_hello(name): print(f"Hello, {name}!") say_hello("World")
Explanation:
The fundamental concept of decorators is that they are functions that take another function as an argument and extend its behavior without explicitly modifying it.
Here's the simplest form:
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper # Using the decorator with @ syntax @my_decorator def say_hello(): print("Hello!") # When we call say_hello() say_hello() # This is equivalent to: # say_hello = my_decorator(say_hello)
Let's create a decorator that logs the execution time of a function:
def decorator_with_args(func): def wrapper(*args, **kwargs): # Accept any number of arguments print(f"Arguments received: {args}, {kwargs}") return func(*args, **kwargs) # Pass arguments to the original function return wrapper @decorator_with_args def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet("Alice", greeting="Hi") # Prints arguments then "Hi, Alice!"
These are decorators that can accept their own parameters:
def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(times=3) def greet(name): print(f"Hello {name}") return "Done" greet("Bob") # Prints "Hello Bob" three times
def singleton(cls): instances = {} def get_instance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return get_instance @singleton class DatabaseConnection: def __init__(self): print("Initializing database connection") # Creating multiple instances actually returns the same instance db1 = DatabaseConnection() # Prints initialization db2 = DatabaseConnection() # No initialization printed print(db1 is db2) # True
These are specifically designed for class methods:
def debug_method(func): def wrapper(self, *args, **kwargs): print(f"Calling method {func.__name__} of {self.__class__.__name__}") return func(self, *args, **kwargs) return wrapper class MyClass: @debug_method def my_method(self, x, y): return x + y obj = MyClass() print(obj.my_method(5, 3))
Multiple decorators can be applied to a single function:
def bold(func): def wrapper(): return "<b>" + func() + "</b>" return wrapper def italic(func): def wrapper(): return "<i>" + func() + "</i>" return wrapper @bold @italic def greet(): return "Hello!" print(greet()) # Outputs: <b><i>Hello!</i></b>
Explanation:
The functools.wraps decorator, See docs, is a helper function that preserves the metadata of the original function (like its name, docstring, and signature) when you wrap it with a decorator. If you don't use it, you'll lose this important information.
Example:
def my_decorator(func): def wrapper(*args, **kwargs): """Wrapper docstring""" return func(*args, **kwargs) return wrapper @my_decorator def my_function(): """My function docstring""" pass print(my_function.__name__) print(my_function.__doc__)
Output:
wrapper Wrapper docstring
Problem:
Solution: Use functools.wraps):
def my_decorator(func): def wrapper(*args, **kwargs): # Do something before calling the decorated function print("Before function call") result = func(*args, **kwargs) # Do something after calling the decorated function print("After function call") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("World")
Output:
class MyDecorator: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): # Do something before calling the decorated function print("Before function call") result = self.func(*args, **kwargs) # Do something after calling the decorated function print("After function call") return result @MyDecorator def say_hello(name): print(f"Hello, {name}!") say_hello("World")
Decorators can also maintain state between function calls. This is particularly useful for scenarios like caching or counting function calls.
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper # Using the decorator with @ syntax @my_decorator def say_hello(): print("Hello!") # When we call say_hello() say_hello() # This is equivalent to: # say_hello = my_decorator(say_hello)
Output:
def decorator_with_args(func): def wrapper(*args, **kwargs): # Accept any number of arguments print(f"Arguments received: {args}, {kwargs}") return func(*args, **kwargs) # Pass arguments to the original function return wrapper @decorator_with_args def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet("Alice", greeting="Hi") # Prints arguments then "Hi, Alice!"
Explanation:
The wrapper function maintains a counter (calls) that increments each time the decorated function is called.
This is a simple example of how decorators can be used to maintain state.
You can find a curated lists of Python decorators below:
Decorators are a powerful and elegant feature in Python that allows you to enhance functions and classes in a clean and declarative way.
By understanding the principles, best practices, and potential pitfalls, you can effectively leverage decorators to write more modular, maintainable, and expressive code.
They are a valuable tool in any Python programmer's arsenal, especially when working with frameworks or building reusable components.
The above is the detailed content of Python Decorators: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!