Junior — Middle
How is variable storage and scope implemented in Python?
sobes.tech AI
Answer from AI
In Python, variables are stored in namespaces, which are dictionaries mapping names to objects. The scopes are determined by the LEGB rule:
- Local — names inside the current function or method.
- Enclosing — names in outer, but not global functions (closures).
- Global — names at the module level.
- Built-in — names of built-in functions and exceptions.
When accessing a variable, Python searches for it sequentially in these scopes. Local variables are stored in the local namespace of the function, global ones in the module namespace.
Example:
x = 10 # global variable
def func():
x = 5 # local variable
print(x) # will print 5
func()
print(x) # will print 10
To modify a global variable inside a function, the global keyword is used.