Hackforge Academy

Category: python

Understanding Decorators

Published on 27 Oct 2026

Explanation

A decorator accepts a callable and returns a callable, often adding behavior without changing the original function body.

Code:

def announce(func):
    def wrapper():
        print('Starting')
        func()
        print('Finished')
    return wrapper
@announce
def greet(): print('Hello')
greet()

Explanation

A reusable wrapper accepts *args and **kwargs and forwards them to the wrapped function.

Code:

def log_call(func):
    def wrapper(*args, **kwargs):
        print('Calling', func.__name__)
        return func(*args, **kwargs)
    return wrapper
@log_call
def add(a, b): return a + b
print(add(2, 3))

Explanation

functools.wraps preserves useful metadata such as the wrapped function's name and documentation.

Code:

from functools import wraps
def logged(func):
    @wraps(func)
    def wrapper(*args, **kwargs): return func(*args, **kwargs)
    return wrapper
@logged
def greet(name): return f'Hello {name}'
print(greet.__name__)

Explanation

perf_counter() measures elapsed time. A finally block reports timing even when the wrapped function raises.

Code:

from functools import wraps
from time import perf_counter
def timed(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = perf_counter()
        try: return func(*args, **kwargs)
        finally: print(perf_counter() - start)
    return wrapper
@timed
def work(): return sum(range(10000))
work()

Explanation

A parameterized decorator uses an outer function to accept configuration and return the actual decorator.

Code:

from functools import wraps
def repeat(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = None
            for _ in range(times): result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator
@repeat(2)
def greet(): print('Hello')
greet()

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community