Namespace

In Python, a namespace is a container that holds a collection of identifiers, such as variable and function names, and their corresponding objects. It serves as a mapping between names and objects, ensuring that each name is unique within its scope.

Namespaces help avoid naming conflicts by providing a way to organize and manage the different identifiers in a program.

Python has different namespaces, including the built-in, global, local, and non-local namespaces:

  • A local namespace is created for a function when the function is called and is deleted when the function returns.
  • The global namespace for a module exists for the duration of the program execution.
  • The built-in namespace contains functions and types that are always available in Python, such as len() and str.

Python Namespace Example

Here’s an example to illustrate the concept of namespaces:

Python
# Global namespace
x = "global x"

def function():
    # Local namespace
    x = "local x"
    print(x)

function()  # Output: local x
print(x)  # Output: global x

In this example, the variable x is defined in both the global and local namespaces. When you call function(), Python looks for x in the local namespace first and finds it. As a result, you get "local x". Outside the function, x refers to "global x" in the global namespace.

Tutorial

Namespaces and Scope in Python

In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 7, 2025 • Reviewed by Dan Bader