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
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.
The hierarchy of the our package looks like this –
mypckg | | ---__init__.py | | ---mod1.py | | ---mod2.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 –
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.
Example: Import Module from package
We will import the modules from the above created package and will use the functions inside those modules.
Welcome to GFG 3
We can also import the specific function also using the same syntax.
Example: Import Specific function from the module
Welcome to GFG 3