Python / Core Python Fundamentals Interview Questions
What is a decorator in Python and how do you write one?
A decorator is a function that takes another function as input, wraps it with extra behaviour, and returns the wrapped version. The @decorator syntax is shorthand for func = decorator(func). Decorators exploit the fact that Python functions are first-class objects.
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs) # call the original
end = time.perf_counter()
print(f'{func.__name__} took {end-start:.4f}s')
return result
return wrapper
@timer
def compute(n):
return sum(range(n))
compute(1_000_000)
# compute took 0.0312sThe problem with the naive version above is that wrapper.__name__ is 'wrapper', not 'compute', which confuses debuggers and documentation tools. Always apply functools.wraps(func) to the inner wrapper to preserve the original function's metadata:
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
...
return wrapperDecorators can be stacked — @dec1 over @dec2 applies dec2 first, then dec1. Common built-in decorators: @staticmethod, @classmethod, @property, @functools.lru_cache (memoisation). In frameworks, @app.route in Flask and @pytest.fixture are decorator-based APIs.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
