> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Closure

A closure in Python is a dynamically generated function object that retains access to variables from its lexical scope even after the enclosing function has finished execution. It essentially binds a function to an environment consisting of one or more free variables.

For a closure to exist in Python, three specific criteria must be met:

1. **Nested Function:** A function must be defined inside another function.
2. **Free Variable Reference:** The inner function must reference a variable declared in the outer function's local scope.
3. **Return the Function:** The outer function must return the inner function object, not the result of calling it.

## Syntax and Mechanics

When the outer function is called, it creates a new instance of the inner function, binds the current state of the referenced local variables to it, and returns this newly created function object.

```python theme={"dark"}
def outer_function(x):
    # 'x' is a local variable to outer_function
    
    def inner_function(y):
        # 'x' is a free variable within inner_function
        return x + y
        
    # Return the function object itself
    return inner_function


# The outer function executes and returns the closure
closure_instance = outer_function(10)


# The outer function's scope is now gone, but the closure retains 'x = 10'
result = closure_instance(5)  # Evaluates to 15
```

## Internal Representation

Python implements closures using cell objects. When a nested function references a variable from an enclosing scope, Python creates a cell object to store the value. Both the outer function's local variable and the inner function's free variable point to this same cell object.

You can inspect a closure's internal state using the `__code__` and `__closure__` dunder attributes.

* `__code__.co_freevars`: A tuple containing the names of the free variables.
* `__closure__`: A tuple of cell objects containing the actual bound values.

```python theme={"dark"}

# Inspecting the free variable names
print(closure_instance.__code__.co_freevars)

# Output: ('x',)


# Inspecting the value stored in the closure's cell object
print(closure_instance.__closure__[0].cell_contents)

# Output: 10
```

## State Mutation and the `nonlocal` Keyword

By default, free variables captured in a closure are read-only. If you attempt to reassign a free variable inside the inner function, Python will treat it as a new local variable declaration, shadowing the outer variable and potentially raising an `UnboundLocalError`.

To mutate the state of a captured free variable, you must explicitly declare it using the `nonlocal` keyword. This instructs the Python interpreter to bind the assignment to the variable in the nearest enclosing lexical scope.

```python theme={"dark"}
def outer_mutating_function():
    state = 0
    
    def inner_mutating_function():
        nonlocal state  # Explicitly bind to the outer scope's 'state'
        state += 1
        return state
        
    return inner_mutating_function

counter = outer_mutating_function()
counter()  # Returns 1
counter()  # Returns 2
```

## Late Binding

Python closures exhibit late binding behavior. The values of variables used in the closure are looked up at the time the inner function is *called*, not at the time it is *defined*. If the free variable changes before the closure is invoked, the closure will use the updated value.

```python theme={"dark"}
def create_multipliers():
    multipliers = []
    for i in range(3):
        # 'i' is a free variable. Its final value will be 2.
        multipliers.append(lambda x: x * i)
    return multipliers

m0, m1, m2 = create_multipliers()


# All closures reference the same 'i', which is 2 when the loop finishes.
print(m0(10))  # Output: 20
print(m1(10))  # Output: 20
print(m2(10))  # Output: 20
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
