Closures and Nested Functions

Loading

1. What Are Nested Functions?

A nested function is a function defined inside another function. It is useful for encapsulation and keeping helper functions hidden.

Example: Nested Function

def outer_function():
print("Outer function")

def inner_function():
print("Inner function")

inner_function() # Calling the nested function

outer_function()

Output:

Outer function
Inner function

The inner_function() is only accessible inside outer_function().


2. What Are Closures?

A closure is a function that remembers the variables from its enclosing scope even after the scope has finished executing.

Closures allow functions to have “persistent” state.

Example: Closure in Python

def outer_function(message):
def inner_function():
print(f"Message: {message}") # Accessing outer variable
return inner_function # Returning function without executing it

closure_func = outer_function("Hello, Closure!")
closure_func() # Calling the returned function

Output:

Message: Hello, Closure!

inner_function() remembers message, even though outer_function() has finished execution.


3. Checking Closure Variables

You can check the variables captured by a closure using __closure__:

def outer(x):
def inner():
return x
return inner

closure_example = outer(10)
print(closure_example.__closure__[0].cell_contents) # Output: 10

The __closure__ attribute stores enclosed variables.


4. Why Use Closures?

1. Data Encapsulation (Similar to Private Variables in OOP)

Closures help encapsulate variables inside functions.

def counter():
count = 0 # Private variable

def increment():
nonlocal count # Modify outer variable
count += 1
return count

return increment

counter_func = counter()
print(counter_func()) # Output: 1
print(counter_func()) # Output: 2

2. Function Factories

Closures can generate specialized functions.

def multiplier(n):
def multiply(x):
return x * n
return multiply

double = multiplier(2) # Creates a function that multiplies by 2
triple = multiplier(3) # Creates a function that multiplies by 3

print(double(5)) # Output: 10
print(triple(5)) # Output: 15

3. Avoiding Global Variables

Closures allow stateful functions without using global variables.

def greeting_creator(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet

hello_greet = greeting_creator("Hello")
print(hello_greet("Alice")) # Output: Hello, Alice!

5. Key Differences: Nested Functions vs. Closures

FeatureNested FunctionClosure
DefinitionFunction inside another functionNested function that “remembers” outer variables
ScopeOnly accessible inside outer functionCan be returned & used later
EncapsulationYes, but temporaryYes, persists after execution
Use CaseHelper functionsMaintaining state, function factories

Leave a Reply

Your email address will not be published. Required fields are marked *