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.fullmatch() Method

    Python re.fullmatch() Method Explained The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t. Syntax python re.fullmatch(pattern, string, flags=0) import re # Target string string = “The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by…

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

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

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

Leave a Reply

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