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

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

Leave a Reply

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