Junior — Middle
Where in memory does Python store variable definitions?
sobes.tech AI
Answer from AI
In Python, variable definitions are stored in namespaces, which are implemented as dictionaries (dict). Depending on the scope, a variable is stored in one of three main namespaces:
- Local namespace of a function or method — variables defined inside the function are stored in the local dictionary.
- Module's global namespace — variables defined at the module level are stored in the module's dictionary.
- Built-in namespace (builtins) — contains Python's built-in names.
When accessing a variable, Python first looks in the local namespace, then in the global namespace, and finally in the built-in namespace.
Example:
x = 10 # global variable
def func():
y = 5 # local variable
print(x, y)
func() # Output: 10 5
Thus, variable definitions are stored in the corresponding namespace dictionaries in memory, and the objects themselves are stored in the heap.