# Scope & Closures — Python

Source: https://www.geekswithgeeks.com/en/python/py-closures-scope

> local, global, nonlocal — and functions that remember their environment.

## LEGB scope rule

Python looks up names using the **LEGB** rule: Local, Enclosing, Global, Built-in — in that order.

## global & nonlocal

`global` and `nonlocal` let an inner function modify a variable from an outer scope instead of shadowing it.

```python
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
print(counter())  # 1
print(counter())  # 2
```

## What is a closure?

`make_counter` above is a **closure** — `increment` "closes over" `count` and keeps its own private copy alive between calls.
