How to create and use Python decorators

Answered
Jan 05, 2026 362 views 1 answers
14

I see @decorator syntax in Python. How do I create my own decorator?

N
Asked by noor_code
Gold 255 rep

1 Answer

25
import functools
import time

# Basic decorator
def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("Before function")
        result = func(*args, **kwargs)
        print("After function")
        return result
    return wrapper

@my_decorator
def say_hello(name):
    print(f"Hello, {name}")

# Decorator with arguments
def repeat(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet():
    print("Hi!")
H
Answered by hassan_ops 1 week, 2 days ago
Bronze 565 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.