Python Documentation

Decorators

Decorators in Python

Decorators in Python are an advanced feature that allows you to modify or enhance functions or classes without directly changing their source code. They are a form of metaprogramming, as they are part of the program that attempts to modify another part of the program during compilation.

Basic Concept

A decorator is a callable that takes another function as an argument and extends the behavior of that function without explicitly modifying it. In Python, decorators are denoted by the @ symbol followed by the decorator name, positioned above the function definition.

Simple Decorator Example

def uppercase_decorator(func):
def wrapper():
ㅤㅤresult = func()
ㅤㅤreturn result.upper()
return wrapper

@uppercase_decorator
def greet():
return "hello, world!"

print(greet()) # Output: HELLO, WORLD!
def bold(func):
def wrapper():
ㅤㅤreturn "" + func() + ""
return wrapper

def italic(func):
def wrapper():
ㅤㅤreturn "" + func() + ""
return wrapper

@bold
@italic
def greet():
return "Hello, World!"

print(greet()) # Output: Hello, World!

Decorators with Arguments

Decorators can also accept arguments, allowing for more flexible behavior:

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(3)
def greet(name):
print(f"Hello, {name}!")

greet("Alice")
# Output:
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!

Decorators are a powerful feature in Python that allow for clean and reusable code. They are widely used in frameworks like Flask and Django for routing, authentication, and more.