Packages
Packages
A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package.
A Python module may contain several classes, functions, variables, etc. whereas a
Python package can contains several module. In simpler terms a package is folder
that contains various modules as files.
As we usually organize our files in different folders and subfolders based on some
criteria, so that they can be managed easily and efficiently. For example, we keep all our
games in a Games folder and we can even subcategorize according to the genre of the
game or something like this. The same analogy is followed by the Python package.
Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and mod2. To
create this module follow the below steps –
Understanding __init__.py
__init__.py helps the Python interpreter to recognize the folder as package.
A package is a directory of Python modules that contains an additional __init__.py file, which
distinguishes a package from a directory that is supposed to contain multiple Python
scripts.
It also specifies the resources to be imported from the modules. If the __init__.py is empty
this means that all the functions of the modules will be imported. We can also specify the
functions from each module to be made available.
Steps:
Create a folder. Name it as pack (you can give any name)
Create a blank python file. Name it as __init__.py
Create any number of modules in that package
Import package in the another python program
Screenshots:
Module 1: calculator1.py
def add(x,y):
return(x+y)
def sub(a,b):
return(a-b)
Module 2: Calculator2.py
def mul(x,y):
return(x*y)
def div(a,b):
return(x/y)
import pack.calculator1
import pack.calculator2
print(pack.calculator1.add(10, 20))
print(pack.calculator2.mul(10, 20))
Here, pack is name of folder where module1, module2 and __init__.py is saved.
Import Modules from a Package
We can import these modules using the from…import statement and the dot(.) operator.
Syntax:
import package_name.module_name
Example:
from mypckg import sum
1. A Package consists of the __init__.py file for each user-oriented script. However, the
same does not apply to the modules in runtime for any script specified to the users.
2. A module is a file that contains a Python script in runtime for the code specified to
the users. A package also modifies the user interpreted code in such a manner that it
gets easily operated in the runtime.