How does namespace placement occur in Python?
sobes.tech AI
Answer from AI
Namespaces in Python are organized hierarchically and managed by the LEGB rule (Local, Enclosing, Global, Built-in).
-
Local (Локальное): The innermost namespace. Created when a function is called, containing names defined inside that function (variables, local functions). Exists only during function execution.
def my_function(): x = 10 # Local variable print(x) -
Enclosing (Окружающее/Нелокальное): Created for nested functions. Contains names from the enclosing (parent) function, not local to the inner function. Uses the
nonlocalkeyword.def outer_function(): y = 20 def inner_function(): nonlocal y # Access variable from enclosing scope print(y) inner_function() -
Global (Глобальное): Namespace at the module level. Contains names defined in the module (functions, classes, variables). Accessible from anywhere in the module. Created upon module import.
z = 30 # Global variable in module def another_function(): global z # Access global variable print(z) -
Built-in (Встроенное): The outermost namespace. Contains Python's built-in functions and exceptions (
print,len,Exception, etc.). Accessible from anywhere.
Python searches for a name starting from the local namespace, then enclosing, then global, and finally built-in. If not found, a NameError is raised.
Namespaces are represented as dictionaries, with names as keys and objects as values.
print(locals()) # Local namespace of current function
print(globals()) # Global namespace of current module