Python Modules

In Python programming, a module is same as a code library.

Basically, it is a file containing a set of functions that we want to include in our application.

This is quite similar to the concept of package in Java.

There are two types of modules in Python: in-built and user-defined.

In the next section, we will create a user-defined module first and then we will try to use it.

Create and Use a user-defined module:

The following example shows how to create a module named test_module (with an attribute and a method) in Python. This module must be saved in a file with .py extension. See the code below: 

# test_module.py

# a dictionary attribute
student_dict = {
101: "Sandip Das",
102: "Andy Smith",
103: "Hasan Ali"
}

# a method
def cube(n):
return n * n * n

Now we can use the newly created module by using the import statement:

# testing.py
import
test_module

# accessing the dictionary attribute
my_dict = test_module.student_dict
print(my_dict) # print the entire dictionary
print("Value:", my_dict[102]) # value corresponding to the key 102

# accessing the method
x = test_module.cube(7)
print("\nCUBE:", x)

Output:

{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}
Value: Andy Smith

CUBE: 343

 

Experiment with modules:

Several experiments can be done with Python modules. These are shown below:

# experiment.py

from test_module import student_dict # Choosing to import only parts from a module
import test_module as tm # Renaming a module
import platform
# A built-in module in Python

print(student_dict)

x = tm.cube(5)
print("CUBE:", x)

os = platform.system()
print(os)

Output:

{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}
CUBE: 125
Linux