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 function
User-defined function
Lambda function
Created by
Python itself
def name(...):
lambda params: expression
Name
Fixed, e.g. len
Chosen by you
None (anonymous)
Body
Hidden (written in C)
Any statements
One expression
Example
len("IGNOU-SOCIS") gives 11
def add_two(a, b): return a + b
lambda a, b: a + b
Typical use
Common tasks
Reusable logic of any size
Short functions passed to map, filter, sorted
What a decorator is
The pattern has three parts:
The outer function receives the original function.
Inside it, a wrapper function adds the extra behaviour and calls the original.
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 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.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/python-advanced-concepts/decorators/ to read this page.