Skip to content

Modules in Python

Modules in Python

Modules in Python is a .py file containing Python definitions, statements, classes, variables, etc. Now we will learn how to use any module.

There are two types of module in Python .They are as follows –

  • Built-in module in Python (eg math, random, sys, requests, etc.)
  • User-defined module in Python .

Here we will discuss about user-defined module.

For that reason , first we will save the following code as module1.py and module2.py in the folder where we are working now .

#module1.py
def add(a,b):
    return a+b

def factorial(a):
    fact=1
    for i in range(1,a+1):
        fact*=i
    return fact

In module1 we have declared two function add and factorial . add() function takes two argument and returns their sum whereas factorial() function takes one argument and return its factorial .

#module2.py
def greet(name):
    print(f"hello {name}")

def product(a,b):
    return a*b

def add(a,b):
    return a-b

In module2 we have declared three function greet , product and add . greet() function takes a name as argument and greet that name , product() function takes two argument and returns their product whereas add() function takes two argument and returns their subtraction .

How to import Modules in Python ?

There are multiple ways to import a module in Python . All the ways are –

  • The import statement
  • The from – import statement

Now we will discuss about all these ways in details with examples –

The import statement in Python

To use another .py file in a .py file we need to use the import statement. In this case we have to specify module_name with dot(.) operator to use any name.

Syntax

import module_name

Example 1: Importing a module in Python

# importing module1
import module1

# calling the add function from module1
a=module1.add(2,5)
print(a)

# calling the factorial function from module1
b=module1.factorial(5)
print(b)
7
120

In the above code, add() function is first called from module1 which returns 7. Then the factorial() function is called from module1 which returns 120.

We can also import multiples modules together.

Syntax

import module1, module2

Example 2: Importing multiple modules in Python

#importing module1 and module2
import module1, module2

# calling the add function from module1
a=module1.add(2,5)
print(a)

# calling the greet function from module2
module2.greet("Sourav")
7
hello Sourav

In the above code, add() function is first called from module1 which returns 7. Then the greet() function was called from module2 which returned "Hello Sourav".

The from – import statement in Python

Importing specific names using from – import statement in Python

Using from - import statement we can import one or more specific names from any module. In this case, once the module is imported, we do not have to specify the module-name to use any name.

Syntax
from module_name import name1, name2,...
Example 1:
# importing product and add function from module1
from module2 import product ,add

# calling product function
a=product(2,5)
print(a)

# calling add function
b=add(2,6)
print(b)
10
-4

In the above code, first product() and add() function have been imported from module2. Then the two functions were called which returned 10 and -4 respectively.

Importing all names using from – import statement in Python

Using from – import statement we can import all the names of any module . In this case also, once the module is imported, we do not have to specify the module-name to use any name.

Syntax

from module_name import *

Example 1:

# importing all names from module1
from module1 import *

# calling add function
a=add(2,5)
print(a)

# calling factorial function
b=factorial(4)
print(b)
7
24

In the above code, first the whole module has been imported. Then the add() function is called which returns 7. Then the factorial() function is called which returns 24.

Since in this case , module_name does not have to be specified when calling a function, if we import two modules that each have a function with the same name, then we may encounter problems while calling the function. If we are sure that we will use only one module then we will not have any problem, otherwise module should be imported by import module statement.

Example 2:

# importing all names from module1
from module1 import *

# importing all names from module2
from module2 import *

# calling add function
a=add(2,5)
print(a)
-3

In the above code first module1 is imported then module2 is imported. Then the add() function is called. Notice that the add() function of module2 has been called. So it is inconvenient to work if two modules have function of the same name. Note that if there is a function with the same name in more than one module, the function of the module that has been imported at the end of all will be active.

Aliasing of Modules in Python

Aliasing is the act of importing a module under another name or importing a function of a module under another name. We can do it using as keyword . This helps us to rename a module in Python .

Syntax

import module_name as md

or

from module_name import name1 as n1

Example 1:

# importing module1 as md1
import module1 as md1

# calling add function using md1
a=md1.add(2,5)
print(a)
7

In the above code module1 has been imported as md1. Therefore, instead of module1.add, md1.add has been used to call the add() function which has returned 7.

Example 2:

#importing add function as sub
from module1 import add as sub
a=sub(2,5)
print(a)
7

In the above code, the add() function of module1 is imported as sub. Therefore, add() function has been called by writing sub in place of add which has returned 7.

How to know what names are in a Module?

The dir() function is used to find out what names are in a module. It returns all the names in a module in the form of a list.

Syntax of dir() function

dir(module_name)

Example 1:

# How to know what names are in a Module

# importing the modules
import module1
import module2

#printing all the names from module1
print("Names in module1 :",end=" ")
print(dir(module1))

#printing all the names from module2
print("Names in module2 :",end=" ")
print(dir(module2))
Names in module1 : ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'factorial']
Names in module2 : ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'greet', 'product']
  • In the above code, first a list of all the names of module1 has been printed where we can see both function add and factorial .
  • Then a list of all the names of module2 has been printed where we can see add , greet and product function .
  • The above two lists also have some additional special string variables such as __name__ (which is used to know module_name), __file__ (which is used to find out in which file the module is used) etc.

The reload Function in Python

When a module is imported into a .py file, the import module statement is executed at once. If we then modify the module and want to re-import the module using the import module statement, the module will not be imported. The reload() function is used to re-import the module. This function is important to IDEs such as Jupyter notebook.

Syntax of reload() function

reload(module_name)  (for python 2)
import imp  (for <=python 3.3)
imp.reload(module_name)
import importlib  (for >=python 3.4)
importlib.reload(module_name)

Example 1:

import module2
module2.greet("sudipta")
hello sudipta

In the above code, module2 has been imported first. Then a function greet is called which returned "hello sudipta".

Then module2 is modified by writing only one line (s = 10). Modified module2 is as follows

#module2.py
def greet(name):
    print(f"hello {name}")

def product(a,b):
    return a*b

def add(a,b):
    return a-b

s=10

After modifying the module2 we have tried to import the module . Then we have tried to print s variable .

#after changing the module2 importing it
import module2

# printing the s variable
print(module2.s)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_11332/124747429.py in <module>
      3 
      4 # printing the s variable
----> 5 print(module2.s)

AttributeError: module 'module2' has no attribute 's'

In the above code we have tried to print s variable after importing module2 . As import module statement executes only one time and before it is executed so in this case import module2 statement is not executed . This means modified module2 has not been imported . Now since there was no s variable in the previous module2, the program has raised an error.

Now we will try to do the specified task using reload() function.

#import the module2 by reload function
import importlib
importlib.reload(module2)
print(module2.s)
10

In the above code module2 has been re-imported with the help of reload() function and s variable has been printed which has printed 10.

From where Python imports a module ?

Python can only import a module from some specific location. We use the sys module to find out where Python can import a module from.

# importing sys module
import sys

# printing all the path from where
# Python imports a name
for i in sys.path:
    print(i)
C:\Users\Rajkumar Bhattachary\Desktop\coding conception\code\Python
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\python39.zip
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\DLLs
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39

c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\tqdm-4.62.2-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\requests-2.26.0-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\phik-0.12.0-py3.9-win-amd64.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\missingno-0.5.0-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\htmlmin-0.1.12-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\visions-0.7.1-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\pyyaml-5.4.1-py3.9-win-amd64.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\pydantic-1.8.2-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\urllib3-1.26.6-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\idna-3.2-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\charset_normalizer-2.0.4-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\certifi-2021.5.30-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\imagehash-4.2.1-py3.9.egg
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\win32
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\win32\lib
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\Pythonwin
c:\users\rajkumar bhattachary\appdata\local\programs\python\python39\lib\site-packages\IPython\extensions
C:\Users\Rajkumar Bhattachary\.ipython

In the above code , we can see easily that first place is this folder where we are working now . For this reason it is always a good practice to keep any of the modules in the folder where we are working.

We should also avoid to name a python file as a module name . If we do so and our required module is not in the working folder then when we import a module that python file will be imported instead of actual module .

The locals and globals Function in Python

globals() function is used to find names in global namespaces and locals() function is used to find names in local namespaces. Both functions return a dictionary. If you call the locals() function in a function, the names that can be used locally by that function will be returned as the key of the dictionary and their value as the value of the respected key. If you call globals() function in any function all the names that can be used globally by that function will be returned as key of dictionary and their value as value of the respected key.

Example of locals function in Python

Now we will use the locals() function in the product() function of module2. Then we will call the product() function of module2. Since the locally accessible name of the product() function is a, b, the key of the returned dictionary will be a, b and the value will be the argument used in place of a and b in the product() function.

After using the locals() function in the product() function of module2 , module2 will look as following –

#module2.py
def greet(name):
    print(f"hello {name}")

def product(a,b):
    print(locals())
    return a*b

def add(a,b):
    return a-b

s=10
import module2
module2.product(10,5)
{'a': 10, 'b': 5}

Example of globals function in Python

Now we will use the globals() function in the product() function of module2. Then we will call the product() function of module2. Since the globally accessible names of the product() function is greet, product, add and s , the key of the returned dictionary will be greet, product, add and s.

After using the globals() function in the product() function of module2 , module2 will look as following –

#module2.py
def greet(name):
    print(f"hello {name}")

def product(a,b):
    print(globals())
    return a*b

def add(a,b):
    return a-b

s=10
import module2
module2.product(10,5)
{'__name__': 'module2', '__doc__': None,..........., 'greet': <function greet at 0x00000255C1C8FAF0>, 'product': <function product at 0x00000255C1C8FD30>, 'add': <function add at 0x00000255C1CB4820>, 's': 10}

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply