Python Modules

A module can define functions, classes and variables. A module can also include runnable code.

We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.

We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

import Statement
You can use any Python source file as a module by executing an import statement in some other Python source file.

We can import a module using import statement and access the definitions inside it using the dot operator .

Syntax:

import module1[, module2[,... moduleN]

program on module
pysum.py

def sum(a,b):
c=a+b
return c

vision.py
import mysum
a=int(input("enter first no"))
b=int(input("enter second no"))
c=mysum.sum(a,b)
print(c)

 

Import with renaming

We can import a module by renaming it as follows.

import mysum as m
a=int(input("enter first no"))
b=int(input("enter second no"))
c=m.sum(a,b)
print(c)

program on multiple functions in a module
mycalc.py

def fact(x):
f=1
for i in range(1,x+1):
f=f*i
return f

def table(x):
for i in range(1,21):
c=i*x
print(i,"*",x,"=",c)
def factors(x):
for i in range(1,x+1):
if x%i==0:
print(i)

vision.py
import mycalc as m
a=int(input("enter first no"))
c=m.fact(a)
print(c)
m.table(a)
m.factors(a)

from...import statement

Python's from statement lets you import specific attributes from a module into the current namespace.

Syntax:
from modname import name1[, name2[, ... nameN]]
from...import *

program on from import

from  mycalc import fact,table
a=int(input("enter first no"))
c=fact(a)
print(c)
table(a)

program on Command line arguments

import sys

print('The command line arguments are:')
for i in sys.argv:
print(i)

Locating Modules

 

When you import a module, the Python interpreter searches for the module in the following sequences −

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

Program to print the built in modules path
import sys
print(sys.path)

dir() built-in function

     
We can use the dir() function to find out names that are defined inside a module.

Program on dir() function
print(dir())

A module's __name__
when a module is imported for the first time, the code it contains gets executed. We can use this to make the module behave in different ways depending on whether it is being used by itself or being imported from another module. This can be achieved using the __name__ attribute of the module.

Program on __name__

if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')

 

For
More Explanation
&
Online Classes

Contact Us: +919885348743