Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python Packages

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 packages in Python

What is a 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.

Creating Package

Let’s create a package in Python 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 our Python package looks like this:

Python Packages

 

Understanding __init__.py

__init__.py helps the Python interpreter recognize the folder as a 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 Python modules using the from…import statement and the dot(.) operator. 

Syntax:

import package_name.module_name

Example 1:

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

Example 2:

We can also import the specific function also using the same syntax.

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
Last Updated : 10 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials