In Python, a namespace is a fundamental concept that helps avoid name conflicts by organizing identifiers (like variable names, function names, class names, etc.) into separate, distinct areas of memory.

Let’s break it down clearly πŸ‘‡


πŸ”Ή 1. What is a Namespace?

A namespace is a container (like a dictionary) that maps names (identifiers) to objects (values) in memory.

In simple terms:

A namespace is like a β€œname tag” system in Python that ensures every object (variable, function, class, etc.) has a unique name.


🧩 Example:

a = 10
b = 20

Here:

  • a and b are names.
  • 10 and 20 are objects.
  • Python stores them in a namespace (like { 'a': 10, 'b': 20 }).

🧠 Analogy:

Think of a namespace as a phonebook:

  • The name (a, b, sum) is the contact name.
  • The memory address (object reference) is the phone number.

If two people (modules) have contacts with the same name, Python keeps them in different phonebooks (namespaces) to avoid confusion.


πŸ”Ή 2. How Namespaces Work

When you write:

x = 5

Python does the following:

  1. Creates an object 5 in memory.
  2. Creates a name x.
  3. Maps x to 5 in a namespace.

So behind the scenes:

Namespace = { "x": 5 }

πŸ”Ή 3. Types of Namespaces in Python

Python maintains four main types of namespaces based on scope and lifetime:

Namespace TypeCreated WhenDestroyed WhenExample
Built-in NamespacePython interpreter startsInterpreter endslen(), print(), type(), id()
Global NamespaceWhen a module (file) is loadedProgram ends or module deletedVariables, functions at the top level of a script
Enclosing NamespaceWhen a nested (inner) function is definedInner function finishesVariables from outer (non-global) function
Local NamespaceWhen a function is calledFunction returnsVariables inside a function

🧩 Example Demonstrating All Namespaces

# Built-in namespace (contains len, print, etc.)
x = 10  # Global namespace

def outer_func():
    y = 20  # Enclosing namespace

    def inner_func():
        z = 30  # Local namespace
        print("Local:", z)
        print("Enclosing:", y)
        print("Global:", x)
        print("Built-in:", len([1, 2, 3]))  # Built-in function

    inner_func()

outer_func()

Output:

Local: 30
Enclosing: 20
Global: 10
Built-in: 3

βœ… Each variable is found in its respective namespace.


πŸ”Ή 4. Types Explained in Detail

🧩 (1) Built-in Namespace

  • Created when the Python interpreter starts.
  • Contains all built-in functions and exceptions.

Examples:

print(len, type, int, Exception)

βœ… You can access them anywhere without importing anything.


🧩 (2) Global Namespace

  • Created when a Python script or module is executed.
  • Contains names defined at the top level (not inside any function/class).

Example:

a = 10     # Global variable
def show():
    print(a)  # Access global
show()

βœ… Variables like a are part of the global namespace.


🧩 (3) Enclosing Namespace

  • Exists in nested (inner) functions.
  • The outer function’s local variables are available to the inner function, but not vice versa.

Example:

def outer():
    x = "outer variable"  # Enclosing
    def inner():
        print(x)  # Accessible here
    inner()

outer()

βœ… Inner function can access the outer (enclosing) variable.


🧩 (4) Local Namespace

  • Created inside a function whenever it is called.
  • Contains local variables and parameters.
  • Destroyed once the function exits.

Example:

def func():
    a = 100  # Local variable
    print(a)

func()
# print(a)  # ❌ Error: a is not defined (local scope only)

βœ… Each function call creates a new local namespace.


πŸ”Ή 5. The LEGB Rule (Namespace Lookup Order)

When Python looks up a variable name, it follows the LEGB rule:

OrderNamespaceDescription
LLocalInside the current function
EEnclosingInside outer function(s)
GGlobalAt the top level of the module
BBuilt-inDefault Python functions & keywords

🧩 Example:

x = "global"

def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)  # Local wins
    inner()

outer()

Output:

local

βœ… Python checks for x in this order:
β†’ Local β†’ Enclosing β†’ Global β†’ Built-in


🧩 Another Example:

x = "global"

def outer():
    x = "enclosing"
    def inner():
        print(x)  # Enclosing
    inner()

outer()

Output:

enclosing

βœ… Since x wasn’t found locally, Python moves up the chain to enclosing scope.


πŸ”Ή 6. Modifying Variables in Different Namespaces

You can modify variables in different namespaces using the keywords:

  • global β†’ modify global variables inside a function
  • nonlocal β†’ modify enclosing (outer function) variables

βœ… Using global:

x = 10

def change_global():
    global x
    x = 20  # Modify global variable
    print("Inside:", x)

change_global()
print("Outside:", x)

Output:

Inside: 20
Outside: 20

βœ… global allows a function to modify variables defined in the global namespace.


βœ… Using nonlocal:

def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20  # Modify enclosing variable
        print("Inner:", x)
    inner()
    print("Outer:", x)

outer()

Output:

Inner: 20
Outer: 20

βœ… nonlocal allows modifying a variable in the enclosing namespace.


🧾 Summary Table

Namespace TypeCreated WhenDestroyed WhenAccessible InExample
Built-inPython startsInterpreter endsEverywherelen(), print()
GlobalModule/script loadsProgram endsInside module/functionsx = 10
EnclosingOuter function runsOuter function endsInner functionsNested functions
LocalFunction is calledFunction endsInside the functionFunction variables

βœ… In short:

A namespace in Python is a mapping of names to objects.
Python has four types of namespaces β€” Built-in, Global, Enclosing, and Local β€”
and resolves variable names using the LEGB rule (Local β†’ Enclosing β†’ Global β†’ Built-in).


🧩 Final Quick Example:

x = "global"             # Global namespace

def outer():
    x = "enclosing"      # Enclosing namespace
    def inner():
        x = "local"      # Local namespace
        print(x)         # Local β†’ Enclosing β†’ Global β†’ Built-in
    inner()

outer()

Output:

local

βœ… Python first searches Local, then Enclosing, then Global, then Built-in namespaces.


Scroll to Top