Nearby lessons

117 of 159

Python - Namespaces

📌 What You Will Learn
  • Understand what a namespace is
  • Know how Python maps names to objects
  • Identify the four types of namespaces
  • Understand when namespaces are created and destroyed
  • See how the same name can exist in different namespaces

What is a Namespace?

A Namespace is a mapping from names to objects.

It is a container that holds all the names available in a particular part of a program, together with the objects those names refer to.

Internally, Python implements a namespace as a dictionary, where the key is the name and the value is the object.

Name to Object Mapping

When we write a program, every variable name points to an object in memory.

🐍Code Cell
1x = 10
2y = "Hello"
Output
No output captured.

Explanation

Here, x is mapped to the integer object 10, and y is mapped to the string object "Hello".

The namespace keeps track of these mappings so that whenever x is used, Python knows exactly which object it refers to.

Name Object
x 10
y "Hello"

Types of Namespaces

Python maintains four types of namespaces. Each namespace is created in a different situation and holds different names.

Type Where It Exists Example Names
Built-in Namespace Available everywhere print(), len(), Exception
Global Namespace Module level Variables defined at the top of a module
Local Namespace Inside a function Function parameters and local variables
Enclosing Namespace Outer function of a nested function Variables of the outer function

Built-in Namespace

The Built-in Namespace is created when the Python interpreter starts.

It contains all the built-in functions and built-in exception names such as print(), len(), max(), ValueError, and Exception.

This namespace is available throughout the entire program, in every module and every function.

🐍Code Cell
1print(len("Python"))
Output
6

Explanation

Here, print and len are not defined anywhere in our code. They are found in the built-in namespace automatically.

Global Namespace

The Global Namespace is created when a module is loaded.

It contains all the names defined at the top level of the module: variables, functions, and classes.

The global namespace lives as long as the module is running.

🐍Code Cell
1x = 10
2y = 20
3 
4 
5def add():
6 z = x + y
7 print("The Sum:", z)
8 
9 
10print(x)
11print(y)
12add()
Output
10
20
The Sum: 30

Explanation

Here, x, y, and add are all names stored in the global namespace of the module.

They can be accessed from anywhere in the module, including inside the add() function.

Local Namespace

The Local Namespace is created when a function is called.

It contains the function parameters and all variables created inside the function.

This namespace is destroyed as soon as the function returns, which is why local variables cannot be accessed from outside the function.

🐍Code Cell
1def fun():
2 a = 10
3 b = 20
4 print("Inside fun:", a, b)
5 
6 
7fun()
8print(a)
Output
Inside fun: 10 20
NameError: name 'a' is not defined

Explanation

The variables a and b belong to the local namespace of fun().

Inside the function they can be accessed normally. But after the function returns, its local namespace is destroyed, so a is no longer available outside and a NameError is raised.

Enclosing Namespace

The Enclosing Namespace appears when we define a function inside another function.

The outer function's namespace is called the enclosing namespace of the inner function.

The inner function can access the names from the enclosing namespace even though they are not defined inside the inner function.

🐍Code Cell
1def outer():
2 x = 100
3 
4 def inner():
5 print("Accessing enclosing x:", x)
6 
7 inner()
8 
9 
10outer()
Output
Accessing enclosing x: 100

Explanation

The variable x is defined in the enclosing namespace of outer().

The nested function inner() does not define x itself, so Python looks into the enclosing namespace and finds it there.

Same Name in Different Namespaces

Different namespaces can contain the same name without any conflict, because each namespace is separate.

A variable x at module level and a variable x inside a function are two completely different names.

🐍Code Cell
1x = 50
2 
3 
4def fun():
5 x = 10
6 print("Local x:", x)
7 
8 
9fun()
10 
11print("Global x:", x)
Output
Local x: 10
Global x: 50

Explanation

Both x variables exist at the same time without interfering with each other.

The x inside fun() belongs to the local namespace. The x at module level belongs to the global namespace.

Namespace Lifetime

Namespace Created Destroyed
Built-in When the interpreter starts When the interpreter stops
Global When a module is loaded When the module finishes
Local When a function is called When the function returns
Enclosing When an outer function is called When the outer function returns

Namespaces Are Dictionaries

Python internally stores every namespace as a dictionary.

For modules and functions, we can even inspect the current namespace using the globals() and locals() functions.

🐍Code Cell
1x = 10
2y = 20
3 
4print(globals())
Output
{'__name__': '__main__', '__doc__': None, ..., 'x': 10, 'y': 20}

Explanation

globals() returns the global namespace as a dictionary. It contains the module-level names such as x and y, along with several special names that Python adds automatically.

Advantages of Namespaces

  • Names are kept separate so that variables in one function never conflict with variables in another.
  • Code in different modules can reuse the same names safely.
  • Namespaces are cleaned up automatically when functions and modules finish.
  • Python always knows which object a name refers to by searching the correct namespace.
📝 Key Takeaways
  • A namespace is a mapping from names to objects, implemented internally as a dictionary
  • Python has built-in, global, local, and enclosing namespaces
  • The built-in namespace contains the built-in functions and exceptions
  • The global namespace holds all names defined at module level
  • Each function call creates its own local namespace that is destroyed when the function returns

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10