All categories
    PythonAdvanced

    Decorators

    Python decorators explained: wrap functions, add behavior, build decorators with arguments, and preserve metadata with functools.wraps.

    01Simple decorator

    main.py
    def shout(func):
        def wrapper():
            return func().upper()
        return wrapper
    
    @shout
    def greet():
        return "hello"
    
    print(greet())
    Output
    HELLO

    02Decorator with arguments

    main.py
    def repeat(n):
        def decorator(func):
            def wrapper():
                for _ in range(n):
                    func()
            return wrapper
        return decorator
    
    @repeat(3)
    def hi():
        print("hi")
    
    hi()
    Output
    hi
    hi
    hi

    03Preserve metadata with wraps

    main.py
    from functools import wraps
    
    def logged(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print("Calling", func.__name__)
            return func(*args, **kwargs)
        return wrapper
    
    @logged
    def add(a, b):
        return a + b
    
    print(add(2, 3))
    Output
    Calling add
    5