0% found this document useful (0 votes)
3 views

chp 2

Uploaded by

VISHAL SHINDE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

chp 2

Uploaded by

VISHAL SHINDE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit 2: Modules and Packages

1
What is Modular Programming?
• Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules.
• Therefore, we can build a bigger program by assembling different modules that act like
building blocks.
• Modularizing our code in a big application has a lot of benefits.
• Simplification:
• A module often concentrates on one comparatively small area of the overall problem
instead of the full task.
• We will have a more manageable design problem to think about if we are only
concentrating on one module.
• Program development is now simpler and much less vulnerable to mistakes.

2
What is Modular Programming? cont..
• Flexibility:
• Modules are frequently used to establish conceptual separations between various
problem areas.
• It is less likely that changes to one module would influence other portions of the
program if modules are constructed in a fashion that reduces interconnectedness. (We
might even be capable of editing a module despite being familiar with the program
beyond it.)
• It increases the likelihood that a group of numerous developers will be able to
collaborate on a big project.

3
What is Modular Programming? cont..
• Reusability:
• Functions created in a particular module may be readily accessed by different sections
of the assignment (through a suitably established api).
• As a result, duplicate code is no longer necessary.
• Scope:
• Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.

• In Python, modularization of the code is encouraged through the use of functions,


modules, and packages.

4
What are Modules in Python? cont..
• A document with definitions of functions and various statements written in Python is
called a Python module.
• In Python, we can define a module in one of 3 ways:
• Python itself allows for the creation of modules.
• Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
• A built-in module, such as the itertools module, is inherently included in the
interpreter.
• A module is a file containing Python code, definitions of functions, statements, or classes.

5
What are Modules in Python? cont..
• A modEx1.py file is a module, we will create with name modEx1.
• We employ modules to divide complicated programs into smaller, more understandable
pieces.
• Modules also allow for the reuse of code.
• Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.

#Python program to show how to create a module.


# defining a function in the module to reuse it
def square( number ):
"""This function will square the number passed to it"""
result = number ** 2
return result
6
How to Import Modules in Python?
• In Python, we may import functions from one module into our program, or as we say into,
another module.
• For this, we make use of the import Python keyword.
• In the Python window, we add the next to import keyword, the name of the module we
need to import.
• We will import the module we defined earlier modEx1.

import modEx1
result = modEx1.square(4)
print( "By using the module square of number is: ", result )

7
Python Modules
• The import Statement
• You can use any Python source file as a module by executing an import statement in some
other Python source file.
• The import has the following syntax
import module1[, module2[,... moduleN]
• When the interpreter encounters an import statement, it imports the module if the module
is present in the search path.
• A search path is a list of directories that the interpreter searches before importing a
module.
# import module support
Example: import support Output:
def print_func(var): # call defined function that module as Hello : Omkar
print "Hello : ", var follows
return support.print_func(“Omkar")
8
Python Modules cont..
• A module is loaded only once, regardless of the number of times it is imported.
• This prevents the module execution from happening repeatedly, if multiple imports occur.
The from...import Statement
• Python's from statement lets you import specific attributes from a module into the current
namespace.
• The from...import has the following syntax
• From modname import name1[, name2[, ... nameN]]

9
Python Modules cont..
• Example
calculation.py: main.py:
#calculation.py from calculation import summation
#it will import only the summation() from calculation.py
def summation(a,b):
a = int(input("Enter the first number"))
return a+b b = int(input("Enter the second number"))
def multiplication(a,b): print("Sum=",summation(a,b)) #we do not need to specify the
return a*b; #module name while accessing summation()
def divide(a,b):
Output (Next slide)
return a/b;

10
(base) C:\Users\bhara\Python>python main.py
Enter the first number 10
Enter the second number 5
Sum= 15
(base) C:\Users\bhara\Python>python main.py
Enter the first number 10
Enter the second number20
Sum= 30
Traceback (most recent call last):
File "C:\Users\bhara\Python\main.py", line 7, in <module>
print("Multiplcation=",multiplication(a,b))
NameError: name 'multiplication' is not defined

(base) C:\Users\bhara\Python>python main.py


Enter the first number 10
Enter the second number20
Sum= 30
Multiplcation= 200
11
Python Modules cont..
• Example: to import the function fibonacci from the module fib
#Fibonacci numbers module
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1 • This statement does not import the entire module fib into
while b < n: the current namespace.
result.append(b) • It just introduces the item fib from the module fib into the
a, b = b, a+b global symbol table of the importing module.
return result
from fib import fib
fib(100)
Output: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
12
Python Modules cont..
The from...import * Statement:
• It is also possible to import all the names from a module into the current namespace by
using the following import statement
from modname import *
• This provides an easy way to import all the items from a module into the current
namespace;
• However, this statement should be used carefully.
Executing Modules as Scripts
• Within a module, the module’s name (as a string) is available as the value of the global
variable __name__.
• The code in the module will be executed, just as if you imported it, but with the __name__
set to "__main__".

13
Python Modules cont..
Example:
# Fibonacci numbers module
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b) Output:
a, b = b, a+b [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
return result
if __name__ == "__main__":
f=fib(100)
print(f)

14
Python Modules cont..
Locating Modules
• When you import a module, the Python interpreter searches for the module in the
following sequences-
• The current directory.
• If the module is not found, Python then searches each directory in the shell variable
PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python3/.
• 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.

15
Python Modules cont..
• The PYTHONPATH Variable
• The PYTHONPATH is an environment variable, consisting of a list of directories.
• The syntax of PYTHONPATH is the same as that of the shell variable PATH.

• Example: PYTHONPATH from a Windows system


set PYTHONPATH=c:\python34\lib;

• Example: PYTHONPATH from a UNIX system


set PYTHONPATH=/usr/local/lib/python

16
Python Modules cont..
• Naming a Module
• You can name the module file whatever you like, but it must have the file extension .py
• Re-naming a Module
• You can create an alias when you import a module, by using the as keyword:
• Example
Create an alias for calculation called c:
import calculation as c
sum = c.summation(10,20)
print(sum)

17
Python Modules cont..
The datetime Module:
• The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.
• To work with dates as date objects, we have to import the datetime module into the
python source code.
• Example
import datetime
#returns the current datetime object
print(datetime.datetime.now())

18
Python Modules cont..
The datetime Module:
• The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.
• To work with dates as date objects, we have to import the datetime module into the
python source code.
import time
• Example
localtime = time.localtime(time.time())
import datetime print ("Local current time :", localtime)
#returns the current datetime object
print(datetime.datetime.now())
import time
localtime =
import time time.asctime( time.localtime(time.time()) )
print (time.localtime()) print ("Local current time :", localtime)
19
Python Modules cont..
The calendar module:
• Python provides a calendar object that contains various methods to work with the
calendars.
• Consider the following example to print the calendar for the Fb month of 2016.
• Example
Here is the calendar:
import calendar;
February 2016
cal = calendar.month(2016,2) Mo Tu We Th Fr Sa Su
#printing the calendar of February 2016 1234567
print(cal) 8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29

20
Python Modules cont..
• The dir( ) Function
• The dir() built-in function returns a sorted list of strings containing the names defined by
a module.
• The list contains the names of all the modules, variables and functions that are defined in
a module.
• Example-
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
# Import built-in module math 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
import math 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
content = dir(math) 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
print (content)
Here, the special string variable __name__ is the module's name, and __file__is
the filename from which the module was loaded.
21
Python Modules cont..
• The reload() Function
• When a module is imported into a script, the code in the top-level portion of a module is
executed only once.
• Therefore, if you want to reexecute the top-level code in a module, you can use the
reload() function.
• The reload() function imports a previously imported module again.
• The syntax of the reload() function:
reload(module_name)
• Here, module_name is the name of the module you want to reload and not the string
containing the module name.
• For example, to reload hello module, do the following
reload(hello)

22
Python Packages
• A package is a directory with
all modules defined inside it.
• To make a Python interpreter
treat it as a package, your
directory should have the
init.py file.
• The init.py makes the
directory as a package.
• Here is the layout of the
package that we are going to
work on.

23
Python Packages
• The name of the package is mypackage.
• To start working with the package, create a directory called mypackage/.
• Inside the directory, create an empty file called __init__.py.
• Create 3 more files module1.py, module2.py, and module3.py and define the functions.
• Here are the details of module1.py,module2.py and module3.py (Refer next slide)

24
Python Packages
module1.py module2.py
def mod1_func1(): def mod2_func1():
print("Welcome to Module1 function1") print("Welcome to Module2 function1")

def mod1_func2(): def mod2_func2():


print("Welcome to Module1 function2") print("Welcome to Module2 function2")

def mod1_func3(): def mod2_func3():


print("Welcome to Module1 function3") print("Welcome to Module2 function3")

25
Python Packages
module3.py import mypackage.module1 as mod1
def mod3_func1():
print("Welcome to Module3 function1") print(mod1.mod1_func1())
print(mod1.mod1_func2())
print(mod1.mod1_func2())
def mod3_func2():
print("Welcome to Module3 function2") Output:
Welcome to Module1 function1
None
def mod3_func3(): Welcome to Module1 function2
print("Welcome to Module3 function3") None
Welcome to Module1 function2
None

26
Python Packages
• The packages in python facilitate the developer with the application development
environment by
• providing a hierarchical directory structure where a package contains sub-packages,
modules, and sub modules.
• The packages are used to categorize the application level code efficiently.
• Let's create a package named Employees in your home directory.
• Consider the following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name ITEmployees.py on the path /home/Employees
ITEmployees.py
def getITLang():
List = [“Prasad", “Manswini++", “Pradnya", " Parag “, “Anjali”]
return List; 27
Python Packages
3. Similarly, create one more python file with name BPOEmployees.py and create a function
getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python
modules.
To make this directory a package, we need to include one more file here, that is __init__.py
which contains the import statements of the modules defined in this directory.
• __init__.py
from ITEmployees import getITNames
from BPOEmployees import getBPONames
5. Now, the directory Employees has become the package containing two python modules.
Here we must notice that we must have to create __init__.py inside a directory to convert
this directory to a package.

28
Python Packages
• A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory.
This file has the following line of source code-
#!/usr/bin/python3
def Pots():
print ("I'm Pots Phone")

Similarly, we have other two files having different functions with the same name as above.
They are −
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
29
Python Packages
Now, create one more file __init__.py in the Phone directory-
• Phone/__init__.py
To make all of your functions available when you have imported Phone, you need to put
explicit import statements in __init__.py as follows
From Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have
all of these classes available when you import the
Phone package.

30
Python Packages
• Example:
• #!/usr/bin/python3
Output:
• # Now import your Phone Package. I'm Pots Phone
• import Phone I'm 3G Phone
• Phone.Pots() I'm ISDN Phone
• Phone.Isdn()
• Phone.G3()

• In the above example, we have taken example of a single function in each file, but you
can keep multiple functions in your files.
• You can also define different Python classes in those files and then you can create your
packages out of those classes.

31

You might also like