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 = 20Here:
aandbare names.10and20are 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 = 5Python does the following:
- Creates an object
5in memory. - Creates a name
x. - Maps
xto5in 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 Type | Created When | Destroyed When | Example |
|---|---|---|---|
| Built-in Namespace | Python interpreter starts | Interpreter ends | len(), print(), type(), id() |
| Global Namespace | When a module (file) is loaded | Program ends or module deleted | Variables, functions at the top level of a script |
| Enclosing Namespace | When a nested (inner) function is defined | Inner function finishes | Variables from outer (non-global) function |
| Local Namespace | When a function is called | Function returns | Variables 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:
| Order | Namespace | Description |
|---|---|---|
| L | Local | Inside the current function |
| E | Enclosing | Inside outer function(s) |
| G | Global | At the top level of the module |
| B | Built-in | Default 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 functionnonlocalβ 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 Type | Created When | Destroyed When | Accessible In | Example |
|---|---|---|---|---|
| Built-in | Python starts | Interpreter ends | Everywhere | len(), print() |
| Global | Module/script loads | Program ends | Inside module/functions | x = 10 |
| Enclosing | Outer function runs | Outer function ends | Inner functions | Nested functions |
| Local | Function is called | Function ends | Inside the function | Function 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.
