T

TechIdea

Ecosystem

Python Interview Questions

Learn Python structures, decorators, memory management, and practical application logic.

Advanced

How do Decorators work in Python?

A decorator is a function that takes another function and extends its behavior without modifying it explicitly. It allows you to wrap a function with additional logic, like checking if a user is logged in before letting them access a route.

Deep Dive

Because Python functions are first-class citizens (they can be passed as arguments), a decorator takes a function as an argument, defines a wrapper function inside it that executes the additional code (before or after the original function), and then returns the wrapper. We use the `@decorator_name` syntax above a function as syntactic sugar for `func = decorator_name(func)`.

Real World Example: In Flask or FastAPI, you use `@app.route('/home')` to attach routing logic to a function. Or you might use `@login_required` to check authentication before a user can view a dashboard function.
💡 Interview Tip:If asked to write one on a whiteboard, don't forget to use `functools.wraps` inside your decorator to preserve the original function's metadata (like its name and docstring).

Growth Newsletter

Get practical AI tools, SEO tips, and growth guides weekly.

Join creators, students, and businesses scaling with TechIdea.