Python Menu

Namespaces in Python


Scope of variables

In Python, variables are associated with two types of scopes. All the variables defined in a module contain the global scope unless or until it is defined within a function.

All the variables defined inside a function contain a local scope that is limited to this function itself. We cannot access a local variable globally.

If two variables are defined with the same name with the two different scopes, i.e., local and global, then the priority will always be given to the local variable.


Example:
name = "Java"  
def disp_name(name):  
    print("Hi",name) #prints the name that is local to this function only.  
name = input("Enter the name :")  
disp_name(name)
Output:
Enter the name: Python
Hi Python

Namespaces in Python

A namespace is basically a system to make sure that all the names in a program are unique and can be used without any conflict.

A namespace is a system to have a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary.

Let’s go through an example, a directory-file system structure in computers. Needless to say, that one can have multiple directories having a file with the same name inside of every directory.

Real-time example, the role of a namespace is like a surname. One might not find a single “Kumar” in the class there might be multiple “Kumar” but when you particularly ask for “N Kumar” or “S Kumar” (with a surname), there will be only one (time being don’t think of both first name and surname are same for multiple students).

Types of namespaces

  • Local Namespace: This namespace includes local names inside a function. This namespace is created when a function is called, and it only lasts until the function returns.
  • Global Namespace: This namespace includes names from various imported modules that you are using in a project. It is created when the module is included in the project, and it lasts until the script ends.
  • Built-in Namespace: This namespace includes built-in functions and built-in exception names. Like print (), input (), list () and etc.
Types of namespaces
Fig:Types of namespaces

Example:
print("Namespace Example")
#built-in namespace
a=10		#global namespace
def func1():
	b=20	#local namespace
	print(a+b)
func1()
Output:
30

In above code, print () is built-in namespace, ‘a’ is in the global namespace in python and ‘b’ is in the local namespace of func1.

Python supports “global” keyword to update global namespaces in local.

Example:
count = 5
def func1(): 
    global count	#To update global namespace
    count = count + 1
    print(count) 
func1()
Output:
6
Example:
a=10 #global namespace
def func1():
	b=20	#non-local namespace
	def func2():
		nonlocal b 
		c=30	#local namesapce
		global a
		a=a+c
		b=b+c
	func2()
	print(a,b)
func1()
Output:
40 50

To func2, ‘c’ is local, ‘b’ is nonlocal, and ‘a’ is global. By nonlocal, we mean it isn’t global, but isn’t local either. Of course, here, you can write ‘c’, and read both ‘b’ and ‘a’.

To update ‘b’ (non-local namespace), we need to use “nonlocal” keyword and to update ‘a’(global namespace), we need to “global” keyword.

globals() and locals()

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed locally from that function.

If globals() is called from within a function, it will return all the names that can be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.


Example:
xy="Madhu"
def sum(a,b):
	c=0
	c=a+b
	print(c)
	print(globals())
	print(locals())
sum(2,3)
Output:
5

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_f
rozen_importlib_external.SourceFileLoader object at 0x006BDBD0>, '__spec__': Non
e, '__annotations__': {}, '__builtins__': , '__fil
e__': 'module1.py', '__cached__': None, 'xy': 'Madhu', 'sum': }

{'a': 2, 'b': 3, 'c': 5}

reload()

For reasons of efficiency, a module is only loaded once per interpreter session. That is fine for function and class definitions, which typically make up the bulk of a module’s contents. But a module can contain executable statements as well, usually for initialization. Be aware that these statements will only be executed the first time a module is imported.

In python the reload () reloads a previously imported module.

Syntax:
import importlib
importlib.reload(module)

mod.py
a = [100, 200, 300]
print('a =', a)
reldemo.py
import mod
import importlib
importlib.reload(mod)
Output:
a = [100, 200, 300]

Next Topic :Packages in Python