Python Namespace and Variable scope

In this Python article, we will discuss what are namespaces in python, how it works and how the scope of a variable is related to namespace with some examples.

1. What is namespace in Python?

In python, namespace is considered a way that has an individual name for any object in Python. It is also a way to organize symbolic links to the objects.

The previous tutorials in this series have emphasized the importance of objects in Python. Objects are everywhere in Python and each data type is represented by an object, so whenever we assign a value to a variable, it creates an object into the memory.

An assignment statement creates a symbolic name that we can use as a reference to that object. The statement x = 'codingeek' creates a symbolic name x that refers to the string object 'codingeek'.

This symbolic links can be made to an object or a method. Lets discuss an example of symbolic linking to aa method.

def output():

a = output


namespace maps user-defined names to respective objects.

Now, a question may arise that how python manages namespace?

The answer is that python keeps a record of all namespaces in the python dictionary. All namespaces can have coexistence in any given instance, each keeping itself isolated.

In total, namespace is combination of two words :

  • Name (unique identifier)
  • Space (scope related information)

Space varies according to the scope where the method or variable is being accessed.

When the python interpreter runs, all the built-in names are grouped in a single namespace and the namespace lives through the time till the interpreter runs.

2. Python Variable Scope

Possibilities for a variable scope or namespaces are

  1. Built-In
  2. Global
  3. Enclosing and Local
Namespaces in Python
Namespaces in Python

2.1. Built-in namespace

There are some functions like print() is present all the time, this function and other such functions are built-in namespace. All of these methods are always available when Python is running. We can list python built-in objects by using the command dir(__builtins__).

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 
'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning',
 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 
'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError',
 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 
'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 
'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 
'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 
'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning',
 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__',
 '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__',
 '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray',
 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright',
 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec',
 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range',
 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod',
 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

This namespace is created by the Python interpreter and its stays till the Python interpreter is running.

2.2. Global namespace in Python

All the variables that are created at the level of the main program are part of the global namespace. Whenever the main program starts or it enters the body Python interpreter creates the Global namespace and it remains in existence until the interpreter terminates.

identifier = 50  #global namespace
def local_func():
  print(identifier) # access from global namespace

Python does not only creates the global namespace for the main function but it also creates a global namespace for every module that our program loads using the import statement

2.3. Local & enclosing namespace in Python

When we invoke a function in Python a local namespace is created. All the variables that are defined within the scope of a function are part of the local namespace. For example.

def local_func():
  identifier = 25  #local namespace

In Python, we can also define a function within a function. Then an inner function accesses the variables that are defined in the enclosing function then we say that a variable is accessed from the enclosing namespace. For example.

def local_func():
  identifier = 25  #local namespace
  def inner_local_func():
    print(identifier) # access from enclosing namespace

In a program, the scope does not require any prefix to access a namespace.

Suppose a reference is made inside any function, the object will be searched in the local namespace followed by the global namespace and at last in the built-in namespace.

Let’s take an example to understand the working of namespace with all the scopes.

identifier1 = 50  #global namespace

def local_func():
  identifier2 = 25  #local namespace
  def inner_local_func():
    identifier3 = 0  #nested local namespace

In this example, variable 'identifier1' is in the global namespace and variable ‘identifier2' is in the local namespace of local_func() and ‘identifier3‘ being the nested local namespace of inner_local_func()

a = 50

def local_func():
  a = 25
  def inner_local_func():
    a = 0
    print("Inner function -> a = ",a)
  print("Local function -> a = ",a)

print('Global scope -> a =', a)
Inner function -> a =  0
Local function -> a =  25
Global scope -> a = 50

We can also make all references and assignment to the global variable using global variable by using global keyword and when we use global keyword it refers to the global object always and no new references are created in local or enclosed namespaces.

a = 50

def local_func():
  global a
  a = 25
  def inner_local_func():
    global a
    a = 0
    print("Inner function -> a = ",a)
  print("Local function -> a = ",a)

print('Global scope -> a =', a)
Inner function -> a =  0
Local function -> a =  0
Global scope -> a = 0

3. Conclusion

At last to be precise. In this article we learned about

  • What is a namespace?
  • What are the possible variable scopes?
  • Examples of how global and local variables work

Complete code samples are present on Github project.

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x