A decorator in Python is a function that takes another function and extends or modifies its behavior without changing the original function’s code. Decorators are heavily used for logging, authentication, caching, performance measurement, and many other cross-cutting concerns.
wrapper).@decorator_name syntax is just a shorthand for: func = decorator_name(func).*args and **kwargs in the wrapper.A basic decorator pattern looks like this:
def my_decorator(func):
def wrapper(*args, **kwargs):
# Do something before
result = func(*args, **kwargs)
# Do something after
return result
return wrapper
@my_decorator
def my_function():
print("Running my_function()")
When Python sees @my_decorator above my_function, it effectively executes: my_function = my_decorator(my_function). The original my_function is replaced by the wrapper returned from the decorator.
# Define a simple function
def greet():
return "Hello!"
# Pass a function into another function
def call_function(func):
print(func())
# Call the higher-order function
call_function(greet)
# Define a simple decorator
def decorator(func):
def wrapper():
# Code to run before the original function
print("Before the function is called.")
func()
# Code to run after the original function
print("After the function is called.")
return wrapper
# Apply the decorator using @ syntax
@decorator
def say_hello():
print("Hello, World!")
# Call the decorated function
say_hello()
# Decorator that works with any arguments
def decorator(func):
def wrapper(*args, **kwargs):
# Code to run before the original function
print("Before the function call")
result = func(*args, **kwargs)
# Code to run after the original function
print("After the function call")
return result
return wrapper
# Decorate a function that adds two numbers
@decorator
def add(a, b):
return a + b
# Call the decorated function and print the result
print(add(5, 3))
def uppercase(func):
def wrapper():
return func().upper()
return wrapper
def exclaim(func):
def wrapper():
return func() + "!!!"
return wrapper
@exclaim
@uppercase
def message():
return "hello"
print(message()) # Output: HELLO!!!
call_function(greet) prints Hello! because greet is passed as a function and then called inside call_function.say_hello() prints the "before" message, then Hello, World!, then the "after" message. The decorator controls what happens around the original function.add(5, 3) prints the “before/after” messages and returns 8. Using *args and **kwargs keeps the decorator flexible.message() first passes through uppercase, becoming "HELLO", then through exclaim, resulting in "HELLO!!!".@decorator_name syntax for better readability and cleaner code.wrapper function from your decorator.*args and **kwargs in wrappers so your decorator works with any function signature.True."Result: ").