Python Namespace

https:/‮i.www/‬giftidea.com

A namespace in Python is a container that stores identifiers (names of variables, functions, modules, classes, etc.) and maps them to objects in memory. Namespaces are used to avoid naming conflicts and to create a hierarchical organization of code.

In Python, there are three types of namespaces:

  1. Built-in Namespace: It contains the built-in functions and modules that are always available in Python. These can be accessed using the built-in function dir(__builtins__).

  2. Global Namespace: It contains the names defined at the top-level of a module or script. These names can be accessed from any part of the program.

  3. Local Namespace: It contains the names defined inside a function or a code block. These names can only be accessed from within the function or block.

When a name is used in a Python program, the interpreter searches for it in the following order: local namespace, then global namespace, and finally built-in namespace. If the name is not found in any of these namespaces, a NameError is raised.

Here is an example of how namespaces work in Python:

# Global namespace
x = 10

def my_function():
    # Local namespace
    y = 20
    print("x in local namespace:", x)
    print("y in local namespace:", y)

my_function()
print("x in global namespace:", x)

Output:

x in local namespace: 10
y in local namespace: 20
x in global namespace: 10

In this example, x is defined in the global namespace and can be accessed from both the my_function and the main part of the program. y is defined in the local namespace of my_function and can only be accessed from within the function. When the function is called, the interpreter first looks for x in the local namespace (and finds it), and then in the global namespace (where it is also defined). When the program prints the value of x after calling the function, it is still accessing the variable in the global namespace.