Junior — Middle
How is variable lookup performed in different scopes in Python?
sobes.tech AI
Answer from AI
In Python, variable lookup follows the LEGB rule, which indicates the scope in the following order:
- L (Local) — the local scope of a function or method.
- E (Enclosing) — the scope of enclosing (outer) functions.
- G (Global) — the global scope of the current module.
- B (Built-in) — Python's built-in names.
When the interpreter encounters a variable name, it first searches in the local scope, if not found — it moves to enclosing functions, then to the global scope, and finally to built-in names. If the variable is not found anywhere, a NameError occurs.
Example:
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print(x) # Will print 'local'
inner()
print(x) # Will print 'enclosing'
outer()
print(x) # Will print 'global'