MCS-201 · Unit 15

Python Advanced Concepts

Section 1 of 5

Block 4 · Unit 15Python Advanced Concepts12 min · Section 1 of 5

15.1Decorators

Covers IGNOU MCS-201 §15.0, 15.2

Sometimes you want to add the same extra behaviour, such as logging, timing or checking permissions, to many functions without editing each one. Decorators do exactly this. They rely on two facts from Unit 11: functions can be passed as arguments, and functions can return other functions.

Three kinds of functions, revised

Built-in functionUser-defined functionLambda function
Created byPython itselfdef name(...):lambda params: expression
NameFixed, e.g. lenChosen by youNone (anonymous)
BodyHidden (written in C)Any statementsOne expression
Examplelen("IGNOU-SOCIS") gives 11def add_two(a, b): return a + blambda a, b: a + b
Typical useCommon tasksReusable logic of any sizeShort functions passed to map, filter, sorted

What a decorator is

The pattern has three parts:

  1. The outer function receives the original function.
  2. Inside it, a wrapper function adds the extra behaviour and calls the original.
  3. The outer function returns the wrapper (it does not call it).

@decorator placed above def f(): is syntactic sugar (a shorter way of writing the same thing) for f = decorator(f).

A general-purpose decorator

The simple wrapper above only works for functions with no parameters and throws away their return value. A reusable decorator accepts any arguments with *args, **kwargs, returns the original result, and uses functools.wraps so the decorated function keeps its own name and docstring.

Python’s standard library uses decorators widely: @classmethod, @staticmethod (Unit 13), @functools.lru_cache (Unit 10) and @property are all decorators.

Key takeaways

  • Built-in, user-defined and lambda functions differ in origin, naming and body.
  • A decorator receives a function and returns a wrapper function.
  • @d above def f is shorthand for f = d(f).
  • Use *args, **kwargs, return the result, and apply functools.wraps in real decorators.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What is @my_decorator above def f(): equivalent to?

Show answer

Answer: B. f = my_decorator(f)

The decorator receives the function object and its return value replaces the name f.

Question 2 · multiple choice

What should the outer function of a decorator return?

Show answer

Answer: C. The wrapper function itself

The wrapper is returned so that later calls go through it; calling it inside the decorator would run it only once, at decoration time.

Question 3 · multiple choice

What does this program print?

Python · quiz_deco.py
def twice(func):
    def wrapper():
        func()
        func()
    return wrapper

@twice
def hi():
    print("hi")

hi()
Show answer

Answer: B. hi, hi (two lines)

hi now refers to wrapper, which calls the original function two times.

Question 4 · multiple choice

Why do general decorators use *args, **kwargs in the wrapper?

Show answer

Answer: D. So the wrapper can accept and pass on any arguments the decorated function needs

One decorator can then be applied to functions with different parameter lists.

Question 5 · multiple choice

What does this program print?

Python · quiz_stack_deco.py
def bold(f):
    def w():
        return "<b>" + f() + "</b>"
    return w

def italic(f):
    def w():
        return "<i>" + f() + "</i>"
    return w

@bold
@italic
def text():
    return "MCA"

print(text())
Show answer

Answer: C. MCA

The decorator nearest the function (italic) is applied first, then bold wraps the result.

Question 6 · short answer

Write a decorator check_positive that prints “Invalid input” and returns None if the first argument is negative, and otherwise calls the function. Apply it to a square-root function.

Show worked answer

def check_positive(func): with an inner def wrapper(x, *args, **kwargs): that does if x < 0: print("Invalid input"); return None and otherwise return func(x, *args, **kwargs), and then return wrapper. Apply: @check_positive above def root(x): return x ** 0.5. Then root(16) returns 4.0 and root(-4) prints “Invalid input” and returns None. The square-root code itself was not changed.

↑ ↓ move↵ openTab switch type