0% found this document useful (0 votes)
12 views15 pages

Ad. Python Ch-2 - Notes

This document covers the concept of modules and packages in Python, explaining what they are, their advantages, and how to create and import them. It details built-in and user-defined modules, the use of the random module, and the steps to create user-defined packages. Additionally, it discusses intra-package references and the purpose of the __init__.py file in a package.

Uploaded by

savaliyabhavy422
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)
12 views15 pages

Ad. Python Ch-2 - Notes

This document covers the concept of modules and packages in Python, explaining what they are, their advantages, and how to create and import them. It details built-in and user-defined modules, the use of the random module, and the steps to create user-defined packages. Additionally, it discusses intra-package references and the purpose of the __init__.py file in a package.

Uploaded by

savaliyabhavy422
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/ 15

Advanced Python Programming (UNIT-2) | 4321602

Unit-II: Modules and Packages (Marks-12)


What is module? Write a program to define a module to find the area and
circumference of circle .Import this module in a program and call functions from it.
SUMMER-2023
What is a module? Write the syntax to create a module. WINTER-2022
Introduction to Modules
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also
makes the code logically organized.
Explain the advantages of the module. SUMMER-2023
Advantages of the module.
Here are several advantages to using modules in Python:
1. Code Reuse: Modules can be imported and used in multiple programs, which allows you
to reuse code across projects. This can save you time and effort, as you don’t have to write
the same code over and over again.
2. Namespace Management: Modules provide a way to organize your code and keep track
of variables, functions, and classes. Each module has its own namespace, which helps to
avoid naming conflicts and keeps your code organized.
3. Simplicity: The module focus on a a small portion of the problem, rather than focusing on
entire problem.
4. Code Maintenance: Modules make it easier to maintain your code, as you can modify a
single module and have the changes reflected in all programs that import that module.
5. Separation of Concerns: Modules allow you to separate different parts of your code into
different files, which can make it easier to understand and maintain.
6. Packaging and Distribution: Modules can be packaged into libraries and distributed to
other users, which makes it easy to share your code with others.
Types of Module:
There are two types of python modules:
1. Built-in python modules
2. User-defined python modules

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 1


Advanced Python Programming (UNIT-2) | 4321602
1. Built-in python modules
Modules that are pre-defined are called built-in modules. We don’t have to create these
modules in order to use them. Built-in modules are mostly written in C language.
All built-in modules are available in the Python Standard Library.
Examples:
 math module
 os module
 random module
 datetime module
2. User-defined python modules
User-defined modules are modules that we create. These are custom-made modules created
specifically to satisfies the needs of a certain project.
Create a Module
To create a Python module, write the desired code and save that in a file with .py extension.
Example:
# A simple module, calc.py
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
What are the different ways to import module? Explain it with suitable example.
WINTER-2022
Import module in Python
 We can import the functions, and classes defined in a module to another module using the
import statement in some other Python source file.
 When the interpreter encounters an import statement, it imports the module if the module
is present in the search path.
Syntax
import module_name
Example:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 2
Advanced Python Programming (UNIT-2) | 4321602
# importing module calc.py
import calc
print(calc.add(10, 2))
O/P:
12
Import Specific Attributes from a Python module(The from ... import Statement)
Example:
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))
O/P:
4.0
720
2. The from...import * Statement(Import all Names)
The * symbol used with the import statement is used to import all the names from a module
to a current namespace.
Syntax:
from module_name import *
Example:
from math import *
print(sqrt(16))
print(factorial(6))
O/P:
4.0
720
3. The import ... as Statement
You can assign an alias name to the imported module.
Synatx:
from modulename as alias
Example:
import math as m

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 3


Advanced Python Programming (UNIT-2) | 4321602
print(m.sqrt(16))
print(m.factorial(6))
O/P:
4.0
720
What is the dir() function in python. Explain with example. SUMMER-2022
dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The
dir() function
Example:
import math
import sys

x=dir(math)
y= dir(sys)
print(x)
print(y)
O/P:
['acosh', 'asin', 'asinh', ……………..', 'log10']
[ 'version', 'version_info',………… 'warnoptions', 'winver']
What is the module search path? WINTER-2022
Module search path
Modules are simply a python .py file from which we can use functions, classes, variables in
another file. To use these things in another file we need to first import that module in that file
and then we can use them. Modules can exist in various directories.
Python looks for modules in 3 steps:-
1. First, it searches in the current directory.
2. If not found then it searches in the directories which are in shell variable PYTHONPATH
3. If that also fails python checks the installation-dependent list of directories configured at
the time Python is installed
Now we will discuss each of these steps:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 4


Advanced Python Programming (UNIT-2) | 4321602
Step 1: Firstly the python searches in the current directory. From the current directory we
mean the directory in which the file calling the module exists. We can check the working
directory from os module of python by os.getcwd() method. The directory returned from this
method is referred to as the current directory. The code for getting the current directory is:
# importing os module
import os
# printing the current working directory
print(os.getcwd())

The output of the above code will be the current working directory which will be first
searched for a module to be imported.
Step 2: If the module that needs to be imported is not found in the current directory. Then
python will search it in the PYTHONPATH which is a list of directory names, with the same
syntax as the shell variable PATH. To know the directories in PYTHONPATH we can
simply get them by the sys module. The sys.path gives us the list of all the paths where the
module will be searched when it is needed to import. To see these directories we have to
write the following code:
Example:
# importing the sys module
import sys
# printing sys.path variable of sys module
for path in sys:
print(path)
O/P:
E:\Advance Python Program
C:\Program Files\Python311\python311.zip
C:\Program Files\Python311\DLLs
C:\Program Files\Python311\Lib
C:\Program Files\Python311
C:\Users\AKV\AppData\Roaming\Python\Python311\site-packages
C:\Program Files\Python311\Lib\site-packages

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 5


Advanced Python Programming (UNIT-2) | 4321602
One of those variables is PYTHONPATH. It is used to set the path for the user-defined
modules so that it can be directly imported into a Python program. It is also responsible for
handling the default search path for Python Modules. The PYTHONPATH variable holds
a string with the name of various directories that need to be added to the sys.path directory
list by Python. The primary use of this variable is to allow users to import modules that are
not made installable yet.
Step 3: If the module is not found in the above 2 steps the python interpreter then tries to
find it in installation dependent list of directories that are configured at the time of
installation of python. These directories are also included in sys.path variable of sys
module and can be known in the same way as the above step. The code will be:
# importing the sys module
import sys
# printing sys.path variable of sys module
print(sys.path)
Output
[‘/home’, ‘/usr/lib/python2.7’, ‘/usr/lib/python2.7/plat-x86_64-linux-gnu’,
‘/usr/lib/python2.7/lib-tk’, ‘/usr/lib/python2.7/lib-old’, ‘/usr/lib/python2.7/lib-dynload’,
‘/usr/local/lib/python2.7/dist-packages’, ‘/usr/lib/python2.7/dist-packages’]
What is random module? Explain with example. SUMMER-2022
Random Module
Python Random module is an in-built module of Python that is used to generate random
numbers in Python.
These numbers occur randomly and does not follow any rules or instructuctions.
We can therefore use this module to generate random numbers, display a random item for a
list or string, and so on.
Sr.
Function Use Example
No
1 random.random() Generate random floating numbers random.random()=
between 0 to 1 0.4585545764414376
2 random.randint() Returns a random integer within the random.randint(1,50)=
range 22

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 6


Advanced Python Programming (UNIT-2) | 4321602
Example:
import random
print(random.random())
print(random.random())
print(random.randint(5,50))
O/P:
0.050357716811645026
0.8258126187037218
49
List out the steps to create a user defined package with proper example. SUMMER-
2023
What is the package? Write the steps to create a package. WINTER-2022
Python Package
 Python modules may contain several classes, functions, variables, etc. whereas Python
packages contain several modules.
 In simpler terms, Package in Python is a folder that contains various modules as files.
 While working on big projects, we have to deal with a large amount of code, and writing
everything together in the same file will make our code look messy.
 Instead, we can separate our code into multiple files by keeping the related code together
in packages.
 Suppose we are developing a game. One possible organization of packages and modules
could be as shown in the figure below.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 7


Advanced Python Programming (UNIT-2) | 4321602

Advantages
 Naming conflicts can be solved easily.
 Improve the modularity of the application.
 The readability of the application will be improved.
 Maintainability of the application will be improved.
Creating User Define Packages
 To tell Python that a particular directory is a package, we create a file named __init__.py
inside it and then it is considered as a package and we may create other modules and sub-
packages within it.
 This __init__.py file can be left blank or can be coded with the initialization code for the
package.
To create a package in Python, we need to follow these three simple steps:
1. First, we create a directory and give it a package name.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the
directory is a package.
Example:
1. First we create a directory and name it Calci.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 8


Advanced Python Programming (UNIT-2) | 4321602
2. Then we need to create modules. To do this we need to create a file with the name
Add.py and create its content by putting this code into it.
Add.py
def add(a, b):
c= a+ b
print(“addition=”,c)
Then we create another file with the name Mul.py and add the similar type of code to it with
different members.
Mul.py
def mul(a, b):
c= a * b
print(“Multiplication=”,c)
3. Finally we create the __init__.py file. This file will be placed inside Math directory
and can be left blank or we can put this initialization code into it.
Now, let’s use the package that we created. To do this make a sample.py file in the same
directory where Math package is located and add the following code to it:
Example:
#import statement
from Calci import Add
from Calci import Mul
#executable part
a , b = 10, 20
Add.add( a, b)
Mul.mul( a, b)
O/P:
Addition=30
Multiplication =200
Explain different ways of importing package. Give one example of it. SUMMER-2022,
WINTER-2022
Importing a package in python

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 9


Advanced Python Programming (UNIT-2) | 4321602
To use modules define inside the package MyPack we must have to import this in our python
source file
1. using import
Syntax:
import packagename OR
import packagename.sub_ packagename.module_name
2. ‘from…import’ in Packages
Syntax:
from packagename import module_name OR
from packagename.sub_packagename import module_name
Example:
Add.py
def add(a, b):
c= a+ b
print(“addition=”,c)
Mul.py
def mul(a, b):
c= a * b
print(“Multiplication=”,c)
Sample.py
#import statement
from MyPack import Add
from MyPack import Mul
#executable part
a , b = 10, 20
Add.add( a, b)
Mul.mul( a, b)
O/P:
Addition=30
Multiplication =200
Explain the intra-package reference concept in python. SUMMER-2023

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 10


Advanced Python Programming (UNIT-2) | 4321602
Intra-package References
When building packages of multiple modules, it is common to want to use code from one
module in another. If you have packages inside sub-packages you can refer to submodules of
siblings packages.
For example, consider the following package structure:
src
└── package
├── __init__.py
├── moduleA.py
├── moduleB.py
└── subpackage
├── __init__.py
└── moduleC.py
 A developer may want to import code from moduleA in moduleB. This is an “intra-
package reference” and can be accomplished via an “absolute” or “relative” import.

 Absolute imports use the package name in an absolute context. Relative imports use
dots to indicate from where the relative import should begin.
 A single dot indicates an import relative to the current package (or subpackage),
additional dots can be used to move further up the packaging hierarchy, one level per
dot after the first dot.

Absolute Relative
Import
from package.moduleA import X from .moduleA import XX
from moduleA in modu
XX X
leB
Import
from package.moduleA import X from ..moduleA import XX
from moduleA in modu
XX X
leC
Import
from package.subpackage.module from .subpackage.moduleC
from moduleC in modu
C import XXX import XXX
leA

What is the purpose of the init.py file in a package?


The `__init__.py` file is a special file in a Python package that serves multiple purposes:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 11
Advanced Python Programming (UNIT-2) | 4321602

1. Package Initialization: The primary purpose of the `__init__.py` file is to initialize the
package when it is imported. It can contain code that you want to execute when the package
is first imported, such as setting up initial configurations or importing specific modules that
should be available at the package level.
2. Package as a Namespace: The `__init__.py` file allows you to treat the package directory
as a namespace. It defines what symbols (modules, sub-packages, or other objects) are part
of the package's public interface. By importing the package, you can access the symbols
defined in the `__init__.py` file directly.
3. Package-Level Attributes and Functions: You can define variables, functions, or classes
in the `__init__.py` file that should be accessible at the package level. These can serve as
convenient shortcuts or utilities for users of the package.
4. Python 2 Compatibility: In older versions of Python (Python 2.x), the presence of the
`__init__.py` file was required to recognize a directory as a package. Although this
requirement has been relaxed in Python 3, it is still a common practice to include an empty
`__init__.py` file to maintain compatibility with older Python versions.
Overall, the `__init__.py` file plays an essential role in package initialization, defining
package-level symbols, and providing a namespace for the package. It helps maintain the
organization and structure of your code when working with packages.
What is PIP? Write the syntax to install and uninstall python packages. WINTER-2022
Installing PIP- Package Installer for Python
PIP stand for Package Installer for Python
Python pip is the package manager for python packages. We can use pip to install packages
that do not come with Python.
The basic syntax of pip command in command prompt is:
pip ‘argument’
Python pip comes pre-installed on 3.4 and older version of python. To check whether pip is
installed or not type the below code in the terminal,
pip -version
This command tell the version of pip if already installed in python.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 12


Advanced Python Programming (UNIT-2) | 4321602
PIP is a package management system used to install and manage software packages/libraries
written in python.
Pip uses PyPI as the default source for packages and their dependencies. So whenever you
type:
pip install package_name
pip will look for that package on PyPI and found, it will download and install the package on
your local system,
Manually install Python PIP on Windows
Step 1: Download the get-pip.py (https://bootstrap.pypa.io/get-pip.py) file and store it in the
same directory as python is installed.

Step 2: Change the current path of the directory in the command line to the path of the
directory where the above file exists.

Step 3: Run the command given below and wait through the installation process

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 13


Advanced Python Programming (UNIT-2) | 4321602

Verification of the Installation Process


Yoy can easily verify if the pip has been installed correctly by performing a version check on
the same. Just go to the command line and execute the following command:
pip -V
or
pip --version

Uninstalling PIP
To uninstall a package use following command
pip uninstall package_name

Difference Between Module and Package in Python

Parameter Module Package


It can be a simple Python file (.py
A Package is a collection of different
Definition extensions) that contains collections
modules with an _init_.py file.
of functions and global variables.
Purpose Code organization Code distribution and reuse
Organization Code within a single file Related modules in a directory hierarchy
Sub-modules None Multiple sub-modules and sub-packages
Required
Only Python File(.py format) ‘_init_.py’ file and python files
Files
How to
import module_name import package_name.module_name
import
Example math, random, os, datetime, csv Numpy, Pandas, Matplotlib, django

**********

“Do not give up, the beginning is always hardest!”


INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 14
Advanced Python Programming (UNIT-2) | 4321602

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani,Mrs.Hina S.Jayani] 15

You might also like