0% found this document useful (0 votes)
3 views8 pages

8.Modules in Python

The document provides an overview of Python modules, explaining their definition, usage, and how to import them in various ways, including aliasing and importing specific members. It also discusses module reloading, accessing module members using the dir() function, and handling modules from different directories. Additionally, it covers checking for and installing modules, as well as the special variable __name__ that indicates whether a script is run as a standalone program or as a module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

8.Modules in Python

The document provides an overview of Python modules, explaining their definition, usage, and how to import them in various ways, including aliasing and importing specific members. It also discusses module reloading, accessing module members using the dir() function, and handling modules from different directories. Additionally, it covers checking for and installing modules, as well as the special variable __name__ that indicates whether a script is run as a standalone program or as a module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Leela Soft Python3 Madhu

Modules in Python:
 A module is a Python object with arbitrarily named attributes that we can bind and
reference.
 Modules are Python .py files that consist of Python code. Any Python file can be
referenced as a module.
 A module can define functions, classes and variables that can then be utilized in other
Python programs.

Example: mathoperations.py
x=888

def add(a,b):
print("The Sum:",a+b)

def product(a,b):
print("The Product:",a*b)

The mathoperations module contains one variable and 2 functions.


If we want to use members of module in our program then we should import that module.

import <modulename>

We can access members by using module name.


modulename.variable
modulename.function()

Example:
test.py:
import mathoperations

print(mathoperations.x)
mathoperations.add(10,20)
mathoperations.product(10,20)

Note:
whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently.

www.leelasoft.com Cell: 78-42-66-47-66 1


Leela Soft Python3 Madhu

Renaming a module at the time of import (module aliasing):


Example:
import mathoperations as mo

Here mathoperations is original module name and mo is alias name. We can access
members by using alias name mo.

Example:
test.py
import mathoperations as mo

print(mo.x)
mo.add(10,20)
mo.product(10,20)

from ... import:


We can import particular members of module by using from ... import.
The main advantage of this is we can access members directly without using module name.

Example:
from mathoperations import x, add

print(x)
add(10,20)
product(10,20) #NameError: name 'product' is not defined

We can import all members of a module as follows


from mathoperations import *

test.py:
from mathoperations import *
print(x)
add(10,20)
product(10,20)

Various possibilities of import statement:


import modulename
import module1, module2, module3

www.leelasoft.com Cell: 78-42-66-47-66 2


Leela Soft Python3 Madhu

import module1 as m
import module1 as m1, module2 as m2, module3
from module import member
from module import member1, member2, memebr3
from module import memeber1 as x
from module import *

The member aliasing:


from mathoperations import x as y, add as sum
print(y)
sum(10,20)

Once we defined as alias name, we should use alias name only and we should not use original
name.

Example:
from mathoperations import x as y
print(x) #NameError: name 'x' is not defined

Reloading a Module:
By default module will be loaded only once even though we are importing multiple multiple
times.

Demo Program for module reloading:


import time
from imp import reload
import module1

time.sleep(30)
reload(module1)
time.sleep(30)
reload(module1)
print("This is test file")

Note: In the above program, every time updated version of module1 will be available to our
program.

module1.py:
print("This is from module1")
www.leelasoft.com Cell: 78-42-66-47-66 3
Leela Soft Python3 Madhu

test.py
import module1
import module1
import module1
import module1
print("This is test module")

In the above program module1 module will be loaded only once even though we are
importing multiple times.

The problem in this approach is after loading a module if it is updated outside then updated
version of module1 is not available to our program.

We can solve this problem by reloading module explicitly based on our requirement. We can
reload by using reload() function of imp module.

import imp
imp.reload(module1)

test.py:
import module1
import module1
from imp import reload
reload(module1)
reload(module1)
reload(module1)
print("This is test module")

In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
explicitly. In this case output is

This is from module1


This is from module1
This is from module1
This is from module1
This is test module

www.leelasoft.com Cell: 78-42-66-47-66 4


Leela Soft Python3 Madhu

The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.

Finding members of module by using dir() function:


Python provides inbuilt function dir() to list out all members of current module or a specified
module.

dir() : To list out all members of current module


dir(moduleName) : To list out all members of specified module

Example:
x=10
y=20
def f1():
print("Hello")

print(dir()) # To print all members of current module

Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'f1', 'x', 'y']

Example 2: To display members of particular module:


mathoperations.py
x=999
def add(a,b):
print("The Sum:",a+b)

def product(a,b):
print("The Product:",a*b)

test.py:
import mathoperations
print(dir(mathoperations))

Output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'product', 'x']

www.leelasoft.com Cell: 78-42-66-47-66 5


Leela Soft Python3 Madhu

Note: For every module at the time of execution Python interpreter will add some special
properties automatically for internal use.

Example: __builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__,


__spec__

Example: test.py:
print(__builtins__ )
print(__cached__ )
print(__doc__)
print(__file__)
print(__loader__)
print(__name__)
print(__package__)
print(__spec__)

Accessing Modules from Another Directory:


If we want to use a Python module from a location other than the same directory where our
main program is:
1. Appending Paths
2. Adding the Module to the Python Path

Checking for and Installing Modules:


There are a number of modules that are built into the Python Standard Library, which contains
many modules that provide access to system functionality or provide standardized solutions.
The Python Standard Library is part of every Python installation.

From within the interpreter we can run the import statement to make sure that the given
module is ready to be called, as in:

>>> import math


Since math is a built-in module, our interpreter should complete the task with no feedback,
returning to the prompt.

Let’s run the import statement with a module that we may not have installed, like the 2D
plotting library matplotlib:

www.leelasoft.com Cell: 78-42-66-47-66 6


Leela Soft Python3 Madhu

>>> import matplotlib


If matplotlib is not installed, we’ll receive an error like this:
Output:
ModuleNotFoundError: No module named: No module named
'matplotlib'

We can deactivate the Python interpreter with CTRL + D and then install matplotlib with
pip.

Next, we can use pip to install the matplotlib module:


>>>pip install matplotlib
Once it is installed, we can import matplotlib in the Python interpreter using import
matplotlib, and it will complete without error.

The Special variable __name__:


 For every Python program, a special variable __name__ will be added internally.
 This variable store information regarding whether the program is executed as an
individual program or as a module.

 If the program executed as an individual program then the value of this variable is
__main__.
 If the program executed as a module from some other program then the value of this
variable is the name of module where it is defined.

Hence by using this __name__ variable we can identify whether the program executed directly
or as a module.

Example:
module1.py:
def f1():
if __name__=='__main__':
print("The code executed as a program")
else:
print("The code executed as a module from some other program")

f1()

www.leelasoft.com Cell: 78-42-66-47-66 7


Leela Soft Python3 Madhu

test.py:
import module1
module1.f1()

Output:
E:\8am>py module1.py
The code executed as a program

E:\8am>py test.py
The code executed as a module from some other program
The code executed as a module from some other program

www.leelasoft.com Cell: 78-42-66-47-66 8

You might also like