Namespaces

A namespace is a collection of currently defined symbolic names along with information about the object that each name references. Python itself maintains a namespace in the form of a Python dictionary. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves. Each key-value pair maps a name to its corresponding object.

Real-time example, the role of a namespace is like a surname. One might not find a single “Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both first name and surname are same for multiple students).
On similar lines, the Python interpreter understands what exact method or variable one is trying to point to in the code, depending upon the namespaces. So, the division of the word itself gives a little more information. Its Name (which means name, a unique identifier) + Space(which talks something related to scope)

Types of Namespaces

When Python interpreter runs solely without any user-defined modules, methods, classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. There are four types of namespaces in a Python Program.

  1. Built-In
  2. Global
  3. Enclosing
  4. Local

Each of these Namespaces have different lifetimes. When a programmer creates a module it creates a global namespace automatically. When a local function is created it creates local namespace, The built-in namespace encompasses the global namespace and the global namespace encompasses the local namespace.

Photo from Geeksforgeeks

Example

# a is in the global namespace 
a = 5
def some_func():

	# b is in the local namespace 
	b = 6
	def some_inner_func():

		# c is in the nested local 
		# namespace
		c = 7

Same object name can be present in multiple namespaces as isolation between the same name is maintained by their namespaces.

The Built-In Namespaces

The built-in namespaces contain the names of all of Python’s built-in objects. These are available at all times when Python is running. You can list the objects in the built-in namespaces with the following command:

>>> 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', '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']

The Python interpreter creates the built-in namespaces when it starts up. This namespace remains in existence until the interpreter terminates.

Scope of Objects in Python :

Suppose you refer to the name x in your code, and x exists in several namespaces. How does Python know which one you mean? Scope is a region where a Python Object is available. This is determined by interpreter at runtime on the basis of where name is defined and where it is used.

# Python program to show
# a scope of object

def funcgeekycodes():
	print("Inside funcgeekycodes")
	def inner_funcgeekycodes():
		var = 10
		print("Inside inner function, value of var:",var)
	inner_funcgeekycodes()
	print("Try printing var from outer function: ",var)
funcgeekycodes()

Inside funcgeekycodes
Inside inner function, value of var: 10
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-f19605bc1140> in <module>
      9     inner_funcgeekycodes()
     10     print("Try printing var from outer function: ",var)
---> 11 funcgeekycodes()

<ipython-input-3-f19605bc1140> in funcgeekycodes()
      8         print("Inside inner function, value of var:",var)
      9     inner_funcgeekycodes()
---> 10     print("Try printing var from outer function: ",var)
     11 funcgeekycodes()

NameError: name 'var' is not defined

Read More about Python here

One thought on “Namespace and Scope in Python”

Leave a Reply