Variable Scope and nonlocal Keyword
1. Understanding Python Variable Scope
In Python, scope refers to the region of a program where a variable is recognized. Python follows the LEGB rule for scope resolution:
| Scope Level | Meaning | Example |
|---|---|---|
| L: Local | Inside the current function | Variable in a function |
| E: Enclosing | Inside any enclosing function(s) | Nested function variables |
| G: Global | At the top-level of the script | Declared outside all functions |
| B: Built-in | Python's built-in names | len, sum, etc. |
Python Variable Scope Examples
Variable Lookup Order (LEGB)
If a variable is referenced inside a function, Python checks in the following order:
1. Local
2. Enclosing
3. Global
4. Built-in
2. global Keyword
Use global to modify a global variable inside a function.
3. nonlocal Keyword
The nonlocal keyword is used inside a nested function to modify a variable in the enclosing (non-global) scope.
Examples
4. nonlocal vs global
| Feature | global |
nonlocal |
|---|---|---|
| Scope | Refers to global scope | Refers to nearest enclosing scope |
| Use case | Modify global variable | Modify enclosing function variable |
| Used in | Any function | Nested functions |
5. Summary
| Concept | Description |
|---|---|
| Scope | Region where a variable is accessible |
| LEGB Rule | Lookup order: Local → Enclosing → Global → Built-in |
| global | Refers to and modifies global variable |
| nonlocal | Refers to and modifies enclosing variable in nested function |