Python Decorators and Closures – Modifying Functions Dynamically and Managing State
Quick Answer: First-class functions let us pass functions around like variables. A closure remembers outer variables, and a decorator wraps a function to add extra behavior without changing its code.
Imagine Priya runs a busy grocery shop in Bengaluru and needs to log every billing transaction.
She wants to measure how long each checkout calculation takes and automatically log time stamps without modifying her core billing code.
How would you add this logging feature across fifty different billing functions without rewriting all of them?
1. Why Do We Need First-Class Functions, Closures, and Decorators?
The problem without decorators
We could manually add timing code inside every single billing function in the application.
Example 1: Manual timing code inside functions
This approach works for one function, but repeating timing logic everywhere creates messy code.
import time
def calculate_bill ():
start = time.time ()
time.sleep (1 ) # simulating billing work
print("Bill calculated")
end = time.time ()
print(v := $"Time taken: {end - start}s")
Expected output
Bill calculated Time taken: 1.001s
This code works, but it has severe limitations.
- Code duplication: writing timer logic in every single function.
- Maintenance nightmare: changing the timer format requires editing dozens of functions.
- Violation of the Single Responsibility Principle: mixing core business logic with logging.
The solution: functions, closures, and decorators
First-class function = a function that can be passed around, stored in variables, and returned like any other data type.
Closure = a nested function that remembers variables from its outer scope even after the outer function has finished running.
Decorator = a function that takes another function as input, adds extra behavior, and returns a new wrapped function.
Figure 1: Decorators wrap functions to execute code before and after the main call.
2. Functions as First-Class Citizens and Closures
In Python, functions are objects. We can assign them to variables, pass them as arguments, and define functions inside other functions.
Example 2: A closure remembering state
This code demonstrates a closure keeping track of a running total of customer bills.
def bill_counter ():
count = 0
def add_bill (amount):
nonlocal count
count += amount
return count
return add_bill
tracker = bill_counter ()
print(tracker(500 ))
print(tracker(300 ))
Expected output
500 800
Notice how the inner function add_bill remembers the count variable even after bill_counter() has returned.
3. Writing and Using Python Decorators
We can use the @ syntax sugar to apply a decorator cleanly above any function.
Example 3: Creating a timing decorator
This code measures execution time transparently using a decorator.
import time
from functools import wraps
def time_logger (func):
@wraps (func)
def wrapper (*args, **kwargs):
start = time.time ()
result = func(*args, **kwargs)
end = time.time ()
print($"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@time_logger
def process_checkout (item):
time.sleep (0.5 )
print($"Processed {item}")
process_checkout ("Rice Bag")
Expected output
Processed Rice Bag process_checkout took 0.5012 seconds
The @wraps decorator preserves the original function name and docstring.
Using *args and **kwargs ensures our decorator works with any function signature.
| Standard Function | Decorated Function |
|---|---|
| Executes core business logic only | Executes cross-cutting concerns (logging, timing, auth) |
| Requires manual repetitive code in each function | Reuses wrapper logic across multiple functions cleanly |
| Harder to modify dynamically | Easily toggled on or off using @decorator syntax |
The important terms to remember
- First-class function = functions treated as normal objects.
- Closure = an inner function that retains outer scope variables.
- Decorator = a wrapper function that enhances another function.
@wraps= a helper tool to preserve function metadata.
Design tip: Always use functools.wraps inside your decorators so debugging tools can see original function names.
4. Common Mistakes to Avoid
1. Forgetting to return the inner wrapper function
Returning a decorator without calling or returning the inner function causes a TypeError when calling the decorated function.
Better approach: Always return the inner wrapper function reference without parentheses inside the outer decorator.
5. Interview Questions & Answers
Question 1: What is a closure in Python and when is it used?
What the interviewer expects: A clear definition explaining free variables and lexical scoping.
Strong answer: "A closure is a nested function that remembers and has access to variables in its enclosing scope even after the outer function has finished executing. We use closures to maintain state without relying on global variables or full object-oriented classes."
What interviewers expect at different levels
- Junior developer: Understands basic syntax and uses existing decorators like
@staticmethod. - Senior developer: Writes custom decorators with arguments and preserves metadata using
functools.wraps. - Technical architect: Implements aspect-oriented programming patterns using decorators for cross-cutting concerns.
6. Practice Exercises
Beginner: Authorization check decorator
Write a decorator named require_admin that checks if a user dictionary has is_admin == True before running a function.
Expected result: Prints permission denied if the user is not an admin.
Intermediate: Function call counter closure
Create a closure that counts how many times a particular billing function has been invoked.
Hint: Use the nonlocal keyword to update a counter variable in the enclosing scope.
7. Frequently Asked Questions (FAQ)
Can decorators take arguments?
Yes. To pass arguments to a decorator, you need a third outer function that accepts the decorator arguments.
Can we apply multiple decorators to one function?
Yes. Multiple decorators stack from bottom to top, where the decorator closest to the function runs first.
8. Next Steps
Now that you have mastered decorators and closures, you are ready to learn about concurrency, threading, and asyncio in the next article.