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

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • Python Input Function: A Beginner’s Guide with Examples

    The input() function in Python is used to take user input from the keyboard. It allows your program to interact with the user by prompting them to enter data, which can then be used in your code. By default, the input() function returns the user’s input as a string. Syntax of input() python Copy input(prompt) Key Points About input() Basic Examples of input() Example…

  • How to create Class

    🟥 Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: 📐 Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

  • 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…

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

Leave a Reply

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