Sobes.tech
Middle+

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).

  1. 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)
    
  2. Enclosing (Окружающее/Нелокальное): Created for nested functions. Contains names from the enclosing (parent) function, not local to the inner function. Uses the nonlocal keyword.

    def outer_function():
        y = 20
        def inner_function():
            nonlocal y # Access variable from enclosing scope
            print(y)
        inner_function()
    
  3. 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)
    
  4. 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
How does namespace placement occur in Python? — Python - sobes.tech