wasAsked.

What are decorators in Python?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · Python

Community answers

Posted by wasAsked editorial collection

A decorator is a function that takes another function (or class) and returns a modified version of it, adding behaviour without changing the original function's code. Python provides the @decorator syntax to apply them. Functions are first-class objects Decorators work because Python functions can be passed as arguments, returned from other functions and defined inside functions (closures). A simple decorator import functools import time def timer(func): @functools.wraps(func) # preserves the original name, docstring and metadata def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f"{func.__name__} took {elapsed:.3f}s") return result return wrapper @timer def generate_report(month): time.sleep(1) return f"Report for {month}" generate_report("November") # prints the timing and returns the report The @timer line is equivalent to: generate_report = timer(generate_report) Decorators with arguments Add one more level of nesting: def retry(times=3, exceptions=(Exception,)): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return func(*args, **kwargs) except exceptions: if attempt == times: raise return wrapper return decorator @retry(times=5, exceptions=(ConnectionError,)) def call_payment_api(): ... Stacking decorators @timer @retry(times=3) def sync_orders(): ... Decorators apply from the bottom up: retry wraps the function first, then timer wraps the result. Built-in and common decorators - @staticmethod and @classmethod: define methods that do not receive the instance (or receive the class). - @property: turns a method into a read-only attribute (with optional setter). - @functools.lru_cache / @functools.cache: memoisation of function results. - @dataclass: generates __init__, __repr__, __eq__ and more for classes. - @contextlib.contextmanager: creates context managers from generator functions. - @abstractmethod: marks methods that subclasses must implement. - Framework decorators: Flask's @app.route, FastAPI's @app.get, Django's @login_required, pytest's @pytest.fixture and @pytest.mark.parametrize. Class decorators A decorator can also receive and modify a class, for example registering it in a plugin registry or adding methods. Async functions For async functions, the wrapper must also be async and await the original: def log_calls(func): @functools.wraps(func) async def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") return await func(*args, **kwargs) return wrapper Common uses - Logging, timing and metrics. - Authentication and authorization checks in web frameworks. - Caching and memoisation. - Retries and rate limiting. - Input validation, transaction management, registering routes or event handlers. Best practices - Always use functools.wraps to keep function metadata (important for debugging, documentation and frameworks that inspect functions). - Keep decorators focused on one concern and avoid hiding complex logic. - Be careful with decorators that change function signatures or return types; use typing.ParamSpec to type them properly. Interview summary: "A decorator is a callable that wraps a function or class to add behaviour — logging, caching, retries, auth — without modifying its code. @decorator is shorthand for func = decorator(func). Decorators rely on first-class functions and closures, and functools.wraps preserves the original metadata."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics