Python Modules

In python, module is a file that will contain a set of objects such as functions, variables, classes, etc., to use in your applications.

 

Any file that contains a python code with a .py extension, we will call it a module. For example, the samplemodule.py file is a module, and you can use it in any python script by importing a module with samplemodule name using an import statement.

 

In python, the modules are useful to reduce the code redundancy by keeping the common functionalities such as functions, variables, etc., in one place and use it in any interpreter session or python script.

Create a Module

In python, you can create a module by writing the following code in the samplemodule.py file.

 

def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
users = ["Suresh", "Rohini", "Trishika"]

If you observe the above code, we created a module (samplemodule) with a combination of functions and variables.

Import Module

In python, you can import the module by using the import keyword. To use the module (samplemodule) that we created in any python script or interpreter, you need to use an import statement like as shown below.

 

import samplemodule

Following is the example of using the module (samplemodule) that we created in python script.

 

import samplemodule

a = samplemodule.add(10, 40)
b = samplemodule.subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)
for user in samplemodule.users:
    print(user)

If you observe the above code, we imported the module (samplemodule) and accessing the functions and variables.

 

The above python module example will return the result as shown below.

 

Sum: 50
Subtract: 50
Suresh
Rohini
Trishika

If the defined module is not found, it will throw the ModuleNotFoundError exception.

Search Module Path

In the above example, we are able to import the newly created modules without specifying any module path because by default the python interpreter will search in the following directory paths to locate the modules.

 

  • First, it will search the current working directory path for the specified module.
  • If not found, it will search the directories that are in the PYTHONPATH environment variable.
  • If still not found, it will search the default installation directory.

Whenever the interpreter starts, the sys module will get all the location paths and keep them in the list like as shown below.

 

import sys

print(sys.path)

The above python module example will return the result as shown below.

 

['D:\\Python Examples', 'C:\\Program Files\\Python38\\Lib\\idlelib', 'C:\\Program Files\\Python38\\python38.zip', 'C:\\Program Files\\Python38\\DLLs', 'C:\\Program Files\\Python38\\lib', 'C:\\Program Files\\Python38', 'C:\\Program Files\\Python38\\lib\\site-packages']

Rename Imported Module

If you want, you can rename the imported module using as keyword. The as keyword will help us to create an alias name for the imported module.

 

Following is the example of renaming the imported module using as keyword in python.

 

import samplemodule as sm

a = sm.add(10, 40)
b = sm.subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)
for user in sm.users:
    print(user)

In the above example, we created alias name (sm) for the imported module (samplemodule) using as keyword and accessing the module resources using the alias name.

 

The above python module example will return the result as shown below.

 

Sum: 50
Subtract: 50
Suresh
Rohini
Trishika

Import Specific Items from Module

When you import the module using an import statement, it will import all the module resources. If you want to import only the specific objects of a module, you can achieve it by using from keyword with the import statement.

 

When you use from keyword to import specific module resources, you don’t need to use the module name to refer to the module elements.

 

Following is the example of importing specific objects from a module using from keyword with the import statement.

 

from samplemodule import add

a = add(10, 40)
b = subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)

In the above example, we imported only add function from samplemodule using from and import keywords but, we are trying to access both add and subtract functions.

 

The above python module example will return the result as shown below.

 

Traceback (most recent call last):
  File "D:\pythonmodule.py", line 4, in <module>
    b = subtract(100, 50)
NameError: name 'subtract' is not defined

Using from keyword, we imported only add function but, we tried to access the subtract function also that’s why we got an exception.

 

Following is the example of importing multiple parts from the module using from…import statement.

 

from samplemodule import add, subtract

a = add(10, 40)
b = subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)

The above python module example will return the result as shown below.

 

Sum: 50
Subtract: 50

Use dir() Function

If you want to see the list of available function/variable names in the module, you can use the built-in dir() function.

 

import samplemodule as sm

x = dir(sm)
print(x)

The above python module example will return the result as shown below.

 

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'subtract', 'users']

Reload the Module

Generally, the python interpreter will load the module only once per session. After loading, if you make any changes to the defined module, those will not reflect in the current session until we close and restart the interpreter.

 

To get the latest module changes without closing the current interpreter session, you need to use the reload() function from the imp module to reload the defined modules.

 

import imp

imp.reload(samplemodule)

Built-in Modules

By default, python has provided a set of built-in modules such as math, os, sys, etc., to use in any python script file. The built-in modules will load automatically whenever the interpreter starts, and these modules are available as a part of python libraries.

 

To know more about built-in modules, refer to built-in modules in python.