> ## 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 Nested Function

A nested function (or inner function) is a function defined entirely within the body of another function. Because Python treats functions as first-class objects, a nested function is dynamically created and bound to a new local variable in the enclosing function's scope each time the outer function is executed.

```python theme={"dark"}
def outer_function(x):
    # Enclosing scope
    
    def inner_function(y):
        # Local scope of inner_function
        return x + y
        
    # inner_function is invoked or returned here
    return inner_function(5)
```

## Lexical Scoping and the LEGB Rule

Nested functions rely on Python's lexical scoping, governed by the LEGB (Local, Enclosing, Global, Built-in) rule for name resolution. When a variable is referenced inside the nested function, Python first checks the nested function's **Local** scope. If the variable is not found, it searches the **Enclosing** scope (the local scope of the outer function).

Because of this, the nested function has read-only access to the variables and arguments of its enclosing function by default.

```python theme={"dark"}
def outer():
    enclosing_var = "visible to inner"
    
    def inner():
        # Reads from the enclosing scope
        print(enclosing_var) 
        
    inner()
```

## Variable Shadowing and the `nonlocal` Keyword

If you attempt to assign a value to an enclosing scope variable inside the nested function, Python will default to creating a new local variable within the nested function, shadowing the outer variable.

To rebind or modify a variable defined in the enclosing scope, you must explicitly declare the variable using the `nonlocal` keyword. This instructs the interpreter to bind the identifier to the nearest enclosing scope (excluding the global scope).

```python theme={"dark"}
def outer():
    state = 0
    
    def inner():
        nonlocal state  # Binds to 'state' in outer()
        state += 1      # Modifies the enclosing variable
        return state
        
    inner()
    return state  # Returns 1
```

## Closures and Late Binding

If the outer function returns the nested function object rather than executing it, the nested function retains a reference to the enclosing scope's environment. This combination of the function and its captured lexical environment is known as a **closure**.

The nested function binds to the variables in the enclosing scope by reference, not by value. This means the nested function will evaluate the enclosing variables at the time the nested function is *executed*, not at the time it is *defined* (late binding).

```python theme={"dark"}
def outer(base):
    def inner(multiplier):
        return base * multiplier
    return inner


# 'outer' returns the 'inner' function object.

# The returned function retains access to 'base'.
closure_instance = outer(10)
result = closure_instance(5)  # Evaluates to 50
```

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