Master Python Variable Scope: The LENGB Guide Explained
This article explains Python’s static variable scope, introducing the LENGB model (Local, Enclosing, nonlocal, Global, Built‑in) and demonstrates how Python resolves names through examples that illustrate common pitfalls such as NameError and the correct use of global and nonlocal keywords.
Variable Scope in Python (LENGB Model)
In a Python program, declaring, modifying, and looking up variable names all happen within a namespace, which is also called the variable’s scope.
Python’s scope is static: the place where a variable is assigned in the source code determines the region where it can be accessed.
LENGB Acronym
L = Local (local scope) E = Enclosing (enclosing scope) N = nonlocal (affects only nested scopes inside functions) G = Global (global scope) B = Built‑in (built‑in scope)
Name Resolution Order
When Python looks up a name, it searches in the following order: local variables → enclosing (outer) variables → global variables in the current module → built‑in variables.
Local Scope Example
<code>L = Local # local scope label</code>A variable defined inside a def block is local by default unless declared global . Attempting to print a local variable outside its function raises NameError because the name cannot be found in the outer scopes.
Global Scope Example
Variables defined at the module level are global. Using the global keyword inside a function allows the function to modify the module‑level variable.
nonlocal Example
The nonlocal keyword is used inside nested functions (closures) to modify a variable in the enclosing function’s scope. Without nonlocal , assignments create a new local variable, leaving the outer variable unchanged.
Other Notes
Control structures such as if , for , while , and try/except do not introduce a new scope. Variables defined inside these blocks become part of the surrounding (often global) scope, which differs from languages like C or Java where such blocks can create separate scopes.
- END -
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.