Decorators in Python — Python Technical Interview Questions & Answers

Decorators in Python

Decorators in Python

  • A decorator wraps a function to add behaviour without rewriting its core. @my_decorator above a def is sugar for f = deco(f). Uses: log calls, time a function, check login, cache. Under the hood it is a function that takes a function and returns a new one.
  • Don’t start with functools.wraps on day one unless they ask. Explain f = deco(f), then one use: timing print. Keep the wrapped function’s job the same.
  • Decorators in Python — output: HI ASHA. @shout wraps greet and uppercases the result.

Technical Interview Tip: f = deco(f) mental model.

Code Examples for Decorators in Python

Example

# Decorator
def shout(fn):
    def wrap(x):
        return fn(x).upper()
    return wrap

@shout
def greet(name):
    return "hi " + name

print(greet("Asha"))

Decorators in Python — output: HI ASHA. @shout wraps greet and uppercases the result.

How to Explain Decorators in Python to an Interviewer

Explain Decorators as if you are teaching a junior — definition, then one tiny script.

@decorator wraps a function. f = deco(f).

What does the example print, and why?

Decorators in Python — output: HI ASHA

What mistake do freshers make with Decorators?

log / time / auth.