What Are Namespaces In Python?

What Are Namespaces In Python?

Published on October 09 2023

In this tutorial, we will learn about Python namespaces and how they are important to the language. You will also understand different types of namespace like local, global, and built-in namespace with enclosing as well. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • In simple words, A namespace is a collection of names and the details of the objects referenced by the names.
  • namespace ensures that object names in a program are unique and can be used without any conflict.
  • Python implements these namespaces as dictionaries with ‘name as key’ mapped to its respective ‘object as value’.

Types

  • Local namespace
    • is at the local or inner function.
    • consists of local names inside a function. It is temporarily created for a function call and gets cleared once the function returns. 
  • Global namespace
    • for all the objects created at the level of the main program.
    • consists of names from various imported modules/packages that are being used in the ongoing project. It is created once the package is imported into the script and survives till the execution of the script. 
  • Built-in namespace
    • includes built-in functions of core Python and built-in names for various types of exceptions. 
  • Enclosing namespaces
    • are at the higher level or outer function.

To know about it, please refer to the official documentation website - official website.