Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python Packages

  • Last Updated : 04 Dec, 2021

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 flder 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 gfg
from .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 mod1
from mypckg import mod2
 
mod1.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 gfg
from mypckg.mod2 import sum
 
gfg()
res = sum(1, 2)
print(res)

Output:

Welcome to GFG
3



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!