Closures in Python

·

3 min read

Closures are an essential concept in Python programming, providing a powerful way to manage and manipulate functions.

Closures in Python are functions that capture variables from their enclosing scope, allowing those variables to be used even after the enclosing scope has finished executing.

Think of a closure like a function with a memory – it can hold onto information from where it was born.

Nested function in Python

An enclosing function is a function that contains another function, known as the inner function. The inner function has access to variables defined in the enclosing function's scope.

def outer_function(x):
    # inner function
    def inner_function():
        print(x)
    # call inner function
    inner_function()
# call outer function  
outer_function(5)

In this example, outer_function is the outer function, and inner_function is the inner function defined within it. The inner_function has access to the variable x from the enclosing scope of outer_function.

Creating Closures in Python

To create closures in Python, you need a function inside another function. This inner function can access and "remember" variables from the outer function's environment.

When the outer function returns the inner function, you've created a closure.

Closures keep these variables alive even after the outer function has finished running.

def outer_function(x):
    # inner function
    def inner_function(y):
       return x+y
    return inner_function
# call the outer function
closure = outer_function(10)
# call the inner function
print(closure(5)) # Output: 15

In this example, outer_function takes an argument x and defines an inner function inner_function that takes an argument y and returns the sum of x and y. The outer_function returns the inner_function, which is assigned to the variable closure. The closure variable is a closure that remembers the value of x as 10. When we call closure(5), it returns the sum of x and y, which is 15.

Requirements of Python closure function

We must meet the following requirements to create a closure function.

To create a closure function, we need to fulfill the following conditions.

1. Define a nested function
2. Return the Nested function
3. The nested function needs to be able to access a variable outside of its scope.

Encapsulation of Data using Closures

Closures allow for data encapsulation within functions, preventing outside access and manipulation. This promotes data integrity and security.

def create_student(name, age):
    info = {'name': name, 'age': age}

    def get_name():
        return info['name']

    def get_age():
        return info['age']

    def update_name(new_name):
        info['name'] = new_name

    def update_age(new_age):
        info['age'] = new_age

    return get_name, get_age, update_name, update_age
get_name, get_age, update_name, update_age = create_student("Alice", 25)
print(get_name())  # Output: Alice
print(get_age())   # Output: 25
update_name("Bob")
update_age(30)
print(get_name())  # Output: Bob
print(get_age())   # Output: 30

In this example, create_student a closure encapsulates the data, a dictionary containing the student's name and age. The inner functions get_name, get_age, update_name, and update_age have access to the info dictionary from the enclosing scope of create_student. This encapsulation ensures that the student's information is accessed and modified through defined functions, maintaining data integrity and providing a clear interface for interacting with the data.

Closures in Python offer the ability to encapsulate data within functions, safeguarding it from external manipulation. This feature enhances data integrity and enhances security. In the given example, the closure create_student encapsulates the info dictionary, which contains the student's name and age.

The inner functions within the closure have access to this dictionary, ensuring that data is accessed and modified through defined functions, thereby preserving data integrity and providing a well-defined data interaction interface.

In conclusion. Closures are a powerful concept in Python programming that allows for the creation of functions that retain the context in which they were defined. They enable data encapsulation within functions, promoting data integrity and security.

To create a closure in Python, we define a nested function inside another function and return the inner function. We must meet certain requirements, like allowing the nested function to access a variable outside of its scope. Overall, closures offer a flexible and secure way to create functions in Python.

Did you find this article valuable?

Support Subhro Kr by becoming a sponsor. Any amount is appreciated!