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.