What is python decorator?

Definition

In Python, a decorator is a special kind of function that can be used to modify or enhance the behavior of other functions without changing their source code

Metaprogramming

Decorators are a form of meta programming, where code can be modified dynamically at runtime

A decorator is simply a function that takes another function as an argument, and returns a new function that replaces the original

Usage

Decorators are often used to add logging, caching, authentication, or other cross-cutting concerns to functions.

Sample Code

def my_decorator(func):     def wrapper():         print("Before function call")         func()         print("After function call")     return wrapper

Sample Code

@my_decorator def say_hello():     print("Hello!")

say_hello()

Code Analysis

The @my_decorator syntax is used to apply the decorator to the say_hello function. When say_hello is called, it actually calls wrapper, which first prints "Before function call", then calls the original say_hello function, and finally prints "After function call".

Output

Before function call Hello! After function call