What is a Python decorator?

Asked by Carol Martinez27 days ago
36 views
Explanation and examples.
0
1 answers

1 Answer

A **Python decorator** is a special type of function that allows you to modify or enhance the behavior of another function or method without permanently changing its code. Decorators are often used to add functionality such as logging, access control, memoization, or timing to existing functions in a clean and readable way. In Python, a decorator is applied to a function by placing it above the function definition with the `@decorator_name` syntax. Essentially, a decorator takes a function as input, wraps it with additional code, and returns a new function that replaces the original one. ### Basic example of a decorator ```python def my_decorator(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() ``` **Output:** ``` Before the function runs Hello! After the function runs ``` In this example, `my_decorator` is a function that takes `say_hello` as an argument and returns a new function `wrapper` that adds behavior before and after the original `say_hello` function runs. The `@my_decorator` syntax is equivalent to writing `say_hello = my_decorator(say_hello)`. ### Why use decorators? - **Code reuse**: Apply the same behavior to many functions without duplicating code. - **Separation of concerns**: Keep your core function logic clean while enhancing functionality externally. - **Readability**: The `@decorator` syntax makes it clear what additional behavior is applied. Decorators can also take arguments and be applied to functions with parameters by using `*args` and `**kwargs` in the wrapper function. They are a powerful feature widely used in Python frameworks and libraries.
0
0
by James Wilson15 days ago