Namespace in Python

Definition of Namespace

The scopes that distinguishes a particular objects by name

Mapping between names and actual objects

If the namespaces belong to are different, it becomes possible to have the same name point to different objects

Generally in Python, configuration of main module is as follows.

def main():
  pass 

if __name__ == '__main__':
  main()
  # do something ... 

Actually, Python is script language. So there is no main function that execute automatically.

If we once run the module, all non-indented code (Lv 0 code) is executed, and function and classes are defined only and not executed.

Therefore, as in the example above, it may be difficult to find reason to define the main function and execute it with the if statement below.

However, there is a reason why most codes follow the above format.


Types of Namespace

Python's namespace can be classified into three categories

Global namespace

Exists for each module, and names of global variables, functions or classes are included here.

a = 3
print(globals())

>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1046110f0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/namespace.py', '__cached__': None, 'a': 3}

Local namespace

Exists for each function or method, and names of local variables in functions are included here.

a = 3

def func():
  a = 100
  b = 'python'
  print
  def printer():
    print('hello')

func()
print(globals())

>> outer_func namespace {'v': 'world', 'a': 100, 'b': 'python'}
>> inner_func namespace {}

Built-in namespace

Names of basic built-in function and basic exceptions belongs here. Includes all scopes of code written in Python.


Characteristics of Namespace

Python’s namespace has the following characteristics.

  1. All namespaces are implemented by shape of dictionary.

  2. All names consists of strings themselves, each of which points to an actual object in the scope of its own namespace.

  3. Since the mapping between the name and the actual object is mutable. Therefore, new name can be added during runtime.

  4. But, built-in namespaces cannot be deleted or added arbitrarily.


Last updated