Closure Functions in Python

Closure Functions in Python

A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope.

Simple Example

python

def outer_function(x):
    # This is the enclosing scope
    
    def inner_function(y):
        # inner_function can access 'x' from outer_function's scope
        return x + y
    
    return inner_function  # Return the inner function itself

# Create closures
add_five = outer_function(5)
add_ten = outer_function(10)

# Use the closures
print(add_five(3))   # Output: 8 (5 + 3)
print(add_five(7))   # Output: 12 (5 + 7)
print(add_ten(3))    # Output: 13 (10 + 3)

Key Characteristics of Closures

  1. Nested Function: A function defined inside another function
  2. Access to Enclosing Scope: The inner function can access variables from the outer function
  3. Returning the Function: The outer function returns the inner function

Practical Example: Counter

python

def make_counter():
    count = 0  # This variable is "remembered" by the closure
    
    def counter():
        nonlocal count  # Allows modifying the variable from outer scope
        count += 1
        return count
    
    return counter

# Create counter instances
counter1 = make_counter()
counter2 = make_counter()

print(counter1())  # Output: 1
print(counter1())  # Output: 2
print(counter2())  # Output: 1 (separate instance)
print(counter1())  # Output: 3

Another Example: Custom Greeting

python

def create_greeting(greeting_word):
    def greet(name):
        return f"{greeting_word}, {name}!"
    return greet

say_hello = create_greeting("Hello")
say_hi = create_greeting("Hi")

print(say_hello("Alice"))  # Output: Hello, Alice!
print(say_hi("Bob"))       # Output: Hi, Bob!

Why Use Closures?

  • Data Encapsulation: Hide implementation details while maintaining state
  • Function Factories: Create specialized functions from a template
  • Callback Functions: Useful in event-driven programming
  • Decorators: Closures are the foundation of Python decorators

Closures are powerful because they allow functions to “remember” their context, making them more flexible and reusable.

Similar Posts

  • For loop 13 and 14th class

    The range() Function in Python The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times. Basic Syntax There are three ways to use range(): 1. range(stop) – One Parameter Form Generates numbers from 0 up to (but not including) the stop value. python for i in range(5):…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • Function Returns Multiple Values in Python

    Function Returns Multiple Values in Python In Python, functions can return multiple values by separating them with commas. These values are returned as a tuple, but they can be unpacked into individual variables. Basic Syntax python def function_name(): return value1, value2, value3 # Calling and unpacking var1, var2, var3 = function_name() Simple Examples Example 1:…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • Functions Returning Functions

    Understanding Functions Returning Functions In Python, functions can return other functions, which is a powerful feature of functional programming. Basic Example python def outer(): def inner(): print(“Welcome!”) return inner # Return the inner function (without calling it) # Calling outer() returns the inner function f = outer() # f now refers to the inner function…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

Leave a Reply

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