Organize Code

Namespace

Python

 

Defining Namespace

Python 2.7
# myproject/Greeting.py
  
def greet():
    print('Hi!')

Namespaces are used to avoid conflicting definitions and introduce more flexibility and organization in the codebase.

There are no special keywords for defining Namespaces in Python, But Python has its own way of handling and organizing conflicting names.

Each module creates its own global namespace.

 

Namespace Hierarchy: Read

Python 2.7
a = 11
def outer():
  a = 12
  def inner():
    print(a)  # 12
  inner()
  print(a)  # 12
outer()
print(a)  # 11

Namespaces in python are created and handled differently compare to other Programming Languages.

In Python Namespaces and Scopes have a close relation.

There 3 types of namespaces in Python:

  • Built-in: highest level namespace
  • Global: module-level namespace
  • Local: function or class level namespace

On each function call, a local namespace is created.

When a name (variable or function) is tried to be read, Python engine:

  1. checks the local namespaces in order.
  2. checks global namespace.
  3. at last checks the built-in namespace.
 

Namespace Hierarchy: Write

Python 2.7
a = 11
def outer():
  a = 12
  def inner():
    a = 13
    print(a)  # 13
  inner()
  print(a)  # 12  
outer()
print(a)  # 11

On the other hand, if you try to set a name (set a variable or define function) it will always create it in the last Local Namespace unless you specified that name using the global keyword.

 

Namespace Hierarchy: Write global

Python 2.7
a = 11
def outer():
  a = 12
  def inner():
    global a
    a = 13
    print(a)  # 13
  inner()
  print(a)  # 12  
outer()
print(a)  # 13

By specifying your names with the global keyword, you can write to them on the Global module Namespace, rather than local Namespace.