Different Types of Modules in Python

Modules in Python:

In Python, Modules are pre-written pieces of code that are used to perform common tasks like generating random numbers and performing mathematical operations, etc.

from… import statement:

A module may contain definitions for many variables and functions. When you import a module, you can use any variable or function defined in that module. But if you want to use only selected variables or functions, then you can use from… import statement.
Example:

from math import pi
print("PI =",+pi)

Output:
PI = 3.141592653589793

Name of Module:

Every module has a name. You can find the name of a module by using the _name_ attribute of the module.

print("Hello World")
print("Name of the module is:", _name_)


Output:

Hello World
Name of the module is:_main_

Making your Module:

You can easily create as many modules as you want. every python program is a module is every file that you save as a .py extension is a module.
First, write these lines in a file and save the file as Mymodule.py

def display():
print("Hello")
print("Name of the called module is:", _name_)
str="Welcome to the world of python!


Then, open another file (

main.py

) and write the code given as follows:

import Mymodule
print("Mymodule str=", Mymodule.str)
Mymodule.display()
print("Name of the calling module is:", _name_)

Output :

Mymodule str= Welcome to the world of Python!
Hello
Name of the called module is: Mymodule
Name of the calling module is: _main_

dir() function:

dir() function is a built-in function that lists the identifiers defined in a module. These identifiers may include functions, classes and variables.
Example:

def print_var(a):
print(a)
a=10
print_var(a)
print(dir())

Output:
10
[‘_builtins_’, ‘_doc_’, ‘_file_’, ‘_name_’, ‘_package_’, ‘print_var’, ‘a’]

main module:

Python Module is a file that contains some definitions and statements. When a Python file is executed directly, it is considered the main module of a program. Main modules are given the special name __main__ and provide the basis for a complete Python Program.

The main module may import any number of other modules which may in turn import other modules. However, the main module of a Python program can’t be imported into other modules.

Namespaces:

A namespace is a container that provides a named context for identifiers. Two identifiers with the same name in the same scope will lead to a name clash. In simple terms, Python doesn’t allow the programmer to have two different identifiers with the same name.

However, in some situations, we need to have the same name identifiers. To cater to such a situation, namespaces is the keyword. Namespaces enable programs to avoid potential name clashes by associating each identifier with the namespace from which it originates.
Example:

import module1
import module2
result1=module1.repeat_x(10)
result2=module2.repeat_x(10)