LearnFrenzy
Sign in Take a free test

Python Programming · Topic 21 of 25

Decorators Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Decorators · Study material

A decorator wraps a function to add behaviour – logging, timing, caching, access checks, retries – without changing the function's own code. You have already used decorators: @property, @classmethod, @lru_cache, @dataclass. Web frameworks use them to map URLs (@app.route("/")), test frameworks to mark tests. Decorators are a favourite interview topic because they combine functions as objects, closures and *args/**kwargs. This topic builds them step by step, then gives you 50 practice questions run on Python 3.

On this page

  • What a decorator is and what @ really does
  • Wrappers that pass arguments and return values
  • functools.wraps
  • When decorators run
  • Decorators with arguments and stacking order
  • Stateful, class-based and registration decorators

A decorator is a function that returns a function

Because functions are objects, one function can take another as an argument and return a new one. A decorator does exactly that: it receives the original function, defines a wrapper that does something before and/or after calling it, and returns the wrapper. Writing @shout above def welcome is simply shorthand for welcome = shout(welcome).

def shout(func):                          # a decorator takes a function …
    def wrapper(*args, **kwargs):         # … defines a new function around it …
        result = func(*args, **kwargs)    # … calls the original …
        return result.upper() + "!"       # … and changes the result
    return wrapper                        # … and returns the new function

def greet(name):
    return f"hello, {name}"

loud_greet = shout(greet)                 # decorating by hand
print(loud_greet("Asha"))

@shout                                    # the @ syntax means: welcome = shout(welcome)
def welcome(place):
    return f"welcome to {place}"

print(welcome("LearnFrenzy"))

Output

HELLO, ASHA!
WELCOME TO LEARNFRENZY!

Write wrappers with *args, **kwargs and return

A wrapper should accept *args, **kwargs so it works for any function signature, pass them on with func(*args, **kwargs), and return the result – otherwise the decorated function suddenly returns None.

functools.wraps

The wrapper replaces the original function, so by default the decorated function reports the wrapper's name and loses its docstring – confusing in tracebacks, help() and tests. Decorate the wrapper with @functools.wraps(func) to copy the name, docstring and other metadata (and keep the original in __wrapped__).

from functools import wraps

def plain(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

def polite(func):
    @wraps(func)                       # copy __name__, __doc__ etc. from func to wrapper
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@plain
def area(r):
    """Area of a circle."""
    return 3.14 * r * r

@polite
def volume(r):
    """Volume of a sphere."""
    return 4 / 3 * 3.14 * r ** 3

print(area.__name__, area.__doc__)
print(volume.__name__, volume.__doc__)
print(volume.__wrapped__.__name__)     # wraps also keeps a link to the original

Output

wrapper None
volume Volume of a sphere.
volume

When does a decorator run?

The decorator itself runs once, when the def statement executes (usually at import time). The wrapper runs on every call. Code you put in the decorator body outside the wrapper is therefore executed only once.

def announce(func):
    print(f"decorating {func.__name__}")      # runs ONCE, when the def statement runs
    def wrapper(*args):
        print(f"calling {func.__name__}{args}")   # runs on every call
        return func(*args)
    return wrapper

@announce
def add(a, b):
    return a + b

print("--- definitions done ---")
print(add(2, 3))
print(add(10, 20))

Output

decorating add
--- definitions done ---
calling add(2, 3)
5
calling add(10, 20)
30

Decorators with arguments

@repeat(3) first calls repeat(3), which must return a decorator; that decorator is then applied to the function. So a decorator with arguments has three levels: the outer function takes the arguments, the middle one takes the function, and the inner one is the wrapper.

from functools import wraps

def repeat(times):                   # 1. takes the decorator's arguments …
    def decorator(func):             # 2. … returns the real decorator …
        @wraps(func)
        def wrapper(*args, **kwargs):    # 3. … which returns the wrapper
            return [func(*args, **kwargs) for _ in range(times)]
        return wrapper
    return decorator

@repeat(3)                           # repeat(3) is called first, then applied to roll
def roll(sides=6):
    return f"d{sides}"

print(roll(), roll(20))

Output

['d6', 'd6', 'd6'] ['d20', 'd20', 'd20']

Stacking decorators

Several decorators can be stacked. They are applied from the bottom up – the one nearest the def first – so @bold @italic def f means f = bold(italic(f)). At call time the outermost wrapper runs first.

def bold(func):
    def wrapper():
        return "<b>" + func() + "</b>"
    return wrapper

def italic(func):
    def wrapper():
        return "<i>" + func() + "</i>"
    return wrapper

@bold          # applied LAST  (outermost)
@italic        # applied FIRST (closest to the function)
def title():
    return "Python"

@italic
@bold
def subtitle():
    return "Decorators"

print(title())         # bold(italic(title))
print(subtitle())      # italic(bold(subtitle))

Output

<b><i>Python</i></b>
<i><b>Decorators</b></i>

Decorators with state

A decorator can remember things between calls – in the closure (a cache dict) or as an attribute on the wrapper (a call counter). That is how memoisation works; functools.lru_cache is the production-ready version.

from functools import wraps

def count_calls(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1               # state stored as a function attribute
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

def memoize(func):
    cache = {}                           # state kept in the closure
    @wraps(func)
    def wrapper(n):
        if n not in cache:
            cache[n] = func(n)
        return cache[n]
    return wrapper

@count_calls
def ping():
    return "pong"

@memoize
@count_calls
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

ping(); ping(); ping()
print(ping.calls)
print(fib(30), fib.__wrapped__.calls)    # 31 real computations instead of 2.6 million

Output

3
832040 31

Class-based decorators

Any callable can be a decorator. A class whose __init__ receives the function and whose __call__ runs in its place keeps state naturally in attributes. (Decorating methods with a class like this needs extra work; function-based decorators are usually simpler.)

class CallLimit:
    """A decorator written as a class: __init__ receives the function, __call__ replaces it."""
    def __init__(self, func):
        self.func = func
        self.remaining = 2

    def __call__(self, *args, **kwargs):
        if self.remaining == 0:
            return "limit reached"
        self.remaining -= 1
        return self.func(*args, **kwargs)

@CallLimit
def send_otp(phone):
    return f"OTP sent to {phone}"

for _ in range(3):
    print(send_otp("98450xxxxx"))
print(type(send_otp).__name__)

Output

OTP sent to 98450xxxxx
OTP sent to 98450xxxxx
limit reached
CallLimit

Common mistakes

  • Forgetting return wrapper – the decorated name becomes None: TypeError when called.
  • Forgetting return func(...) in the wrapper – results become None.
  • A wrapper without *args, **kwargs – TypeError for functions with arguments.
  • @repeat instead of @repeat(3) (or @log() for a plain decorator) – the levels get mixed up.
  • Not using functools.wraps – wrong __name__ and lost docstring.
  • Wrong stacking order – the outermost decorator is the top one.
  • Assigning to state in a nested function without nonlocal – UnboundLocalError.

Key points to remember

  • @deco above def f means f = deco(f).
  • A wrapper takes *args, **kwargs and returns func's result.
  • Use @functools.wraps(func) on every wrapper.
  • The decorator runs at definition time; the wrapper at call time.
  • Decorators with arguments need three levels of functions.
  • Stacked decorators apply bottom-up and run top-down.
  • @property, @classmethod, @staticmethod, @lru_cache are decorators too.

Frequently asked questions

What is a closure, and why do decorators need it?

A closure is an inner function that remembers variables of the enclosing function. The wrapper remembers func (and any decorator arguments) after the decorator has returned.

Can a decorator be applied to a class?

Yes: a class decorator receives the class and returns it (modified) or a replacement – @dataclass is one.

Do decorators slow code down?

Each call goes through one extra function call, which is negligible except in very tight loops.

Where can I learn more?

Read Python Decorators and Scope, Lambda and Recursion in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links