🐍 Python Beginner

What are Python decorators?

Answer

A decorator is a function that takes another function as an argument, adds some behaviour, and returns the modified function. The @decorator syntax is syntactic sugar for func = decorator(func). A decorator using functools.wraps: from functools import wraps; def timer(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time(); result = func(*args, **kwargs); print(time.time() - start); return result; return wrapper. Apply: @timer def my_function(): .... Built-in decorators: @staticmethod, @classmethod, @property. Decorators are widely used for logging, timing, authentication, caching (@functools.lru_cache), and input validation. Multiple decorators stack from bottom to top.