Python Advance Course
Closures in Python (Advanced)
Closures in Python (Advanced)
A closure is a function that remembers variables from its outer (enclosing) scope, even after the outer function has finished execution.
Closures are the foundation of: - Decorators - Function factories - Advanced functional programming
1. Nested Functions
A nested function is a function defined inside another function.
Example:
def outer():
def inner():
print("Inner function")
inner()
outer()
Output:
Inner function
Real-world analogy: - Outer function = Factory - Inner function = Machine inside factory
Key Point
| Concept | Meaning |
|---|---|
| outer function | creates environment |
| inner function | uses environment |
Common Mistake
def outer():
def inner():
print("Hello")
inner()
Error:
- inner() is not accessible outside outer function
Homework 1
Create a nested function that prints "Python is awesome".
Solution:
def outer():
def inner():
print("Python is awesome")
inner()
outer()
2. Capturing Outer Variables (Closure Concept)
Inner functions can access variables from outer functions.
Example:
def outer():
x = 10
def inner():
print(x)
inner()
outer()
Output:
10
How it works
Outer function creates variable x
Inner function "remembers" x
Even after outer runs, inner can access it
Real World Example
Discount system:
def discount_generator(discount):
def apply(price):
return price - (price * discount)
return apply
discount_10 = discount_generator(0.10)
print(discount_10(1000))
Output:
900.0
Closure Behavior Visualization
outer()
|
+-- x = 10
|
+-- inner() ---- remembers x
Even after outer finishes, inner still has access to x.
Common Mistake
def outer():
x = 10
def inner():
x = x + 1
print(x)
inner()
Error: - Local variable referenced before assignment
Fix:
def outer():
x = 10
def inner():
nonlocal x
x += 1
print(x)
inner()
Homework 2
Create a closure that adds 5 to any number.
Solution:
def outer():
x = 5
def inner(num):
return num + x
return inner
add5 = outer()
print(add5(10))
Output:
15
3. Function Factories
A function factory is a function that returns other functions based on input.
Example 1: Power Factory
def power_factory(n):
def power(x):
return x ** n
return power
square = power_factory(2)
cube = power_factory(3)
print(square(5))
print(cube(2))
Output:
25
8
Example 2: Greeting Factory
def greeting_factory(message):
def greet(name):
return message + " " + name
return greet
hello = greeting_factory("Hello")
hi = greeting_factory("Hi")
print(hello("John"))
print(hi("Alice"))
Output:
Hello John
Hi Alice
Real World Example
| Factory Type | Use Case |
|---|---|
| Discount factory | different discount rules |
| Tax factory | different country taxes |
| Logger factory | different log levels |
Function Factory Flow
Factory Function
|
+--> creates customized function
|
+--> returns function with memory (closure)
Common Mistake
def factory():
def inner(x):
return x * 2
return inner()
f = factory()
print(f(5))
Problem: - inner() is executed immediately
Correct:
return inner
Homework 3
Create a function factory that multiplies numbers by a given factor.
Solution:
def multiplier_factory(factor):
def multiply(x):
return x * factor
return multiply
double = multiplier_factory(2)
triple = multiplier_factory(3)
print(double(10))
print(triple(10))
Summary Table
| Concept | Meaning |
|---|---|
| Nested Function | Function inside function |
| Closure | Function remembering outer variables |
| Function Factory | Function returning customized functions |
Closure Memory Diagram
outer()
|
|-- x = 10
|
|-- inner() remembers x
|
+--> closure created
Real Life Analogy
| Concept | Real Life Example |
|---|---|
| Closure | Mobile app remembering login session |
| Function Factory | ATM generating different transaction options |
| Nested Function | Machine inside factory |
Homework 4 (Challenge)
Create: - A function factory that creates "adder functions" - Each function should add a fixed number
Example: - add10(5) → 15 - add20(5) → 25
Solution:
def adder_factory(n):
def add(x):
return x + n
return add
add10 = adder_factory(10)
add20 = adder_factory(20)
print(add10(5))
print(add20(5))
Next Advanced Topics
- Decorators (built using closures)
- Lambda functions
- Higher-order functions
- functools module
- Partial functions
- Functional programming concepts ```