Python Packages
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.
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.
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 –
- Create a folder named mypckg.
- Inside this folder create an empty Python file i.e. __init__.py
- Then create two modules mod1 and mod2 in this folder.
Mod1.py
Python3
def gfg(): print("Welcome to GFG") |
Mod2.py
Python3
def sum(a, b): return a+b |
The hierarchy of the our package looks like this –
mypckg | | ---__init__.py | | ---mod1.py | | ---mod2.py
Understanding __init__.py
__init__.py helps the Python interpreter to recognise the folder as package. 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.
For example, we can also create the __init__.py file for the above module as –
__init__.py
Python3
from .mod1 import gfgfrom .mod2 import sum |
This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to be imported.
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: Import Module from package
We will import the modules from the above created package and will use the functions inside those modules.
Python3
from mypckg import mod1from mypckg import mod2mod1.gfg()res = mod2.sum(1, 2)print(res) |
Output:
Welcome to GFG 3
We can also import the specific function also using the same syntax.
Example: Import Specific function from the module
Python3
from mypckg.mod1 import gfgfrom mypckg.mod2 import sumgfg()res = sum(1, 2)print(res) |
Output:
Welcome to GFG 3




.png)