Sobes.tech
Junior — Middle

Can you list the main namespaces in Python and explain their purpose?

sobes.tech AI

Answer from AI

In Python, there are three main namespaces that define the scope of objects:

  1. Local namespace — contains names defined inside the current function or method. These names are only accessible within that function.

  2. Enclosing namespace — the namespace of outer functions if a function is nested inside another. It allows nested functions to access variables from the outer function.

  3. Global namespace — contains names defined at the module level (file). Accessible throughout the module.

  4. Built-in namespace — contains names of Python's built-in functions and exceptions, such as print(), len(), Exception.

Python searches for a name in LEGB order: Local, Enclosing, Global, Built-in.

Example:

x = 'global'

def outer():
    x = 'enclosing'
    def inner():
        x = 'local'
        print(x)  # prints 'local'
    inner()
    print(x)  # prints 'enclosing'

outer()
print(x)  # prints 'global'