In this article, we will discuss about python packages, how to create python package and you will also learn about how to import a module from a package in python programming language.
What is Python Package?
In python, package is a folder which contains python modules and other python files. In conceptual way, we can that a python package is a namespace or directory with the file name that contains python modules.
For example, we contain and manage our files in an organized hierarchy of directories in our computer. Similarly, in python the modules and other files are organised and managed in the packages. In other words, python packages are directories with contains different modules as files.
The modules with similarity are put together in same package. A package have modules and sub-packages. A directory or file must named with in order to be considered as python package.
How to Create Python Package?
Now, we will create a python package with name mypackage in which two modules will be included demo1.py and demo2.py
You have follow these steps to create a python package;
• Firstly create a folder with the name mypackage
• Then create an empty file inside this folder i.e.,
• After that we will create two modules with name demo1.py and demo2.py
# demo1.py># function
def foo():
print("Welcome to Answersjet")
# demo2.py># function
def multiply(a, b):
return a*b
Now you will see that hierarchy of the our package which will appear in the screen something like this:
mypackage|
|
---__init__.py
|
|
---demo1.py
|
|
---demo2.py
Understanding _init_.py
As we know that, in order to be recognised as a package, a file must be named with . This also helps in specifying the resources that are to be imported from the modules. An empty file is present in the package directory then it means that all module functions will be imported.
# __init__.py>from .demo1 import foo
from .demo2 import multiply
Import module from a package
With the help of from...import package and dot (.) operator, we can import a python module from a package.
Let's understand the importing of python module from a package with the following example;
from mypackage import demo1from mypackage import demo2
demo1.foo()
fn = demo2.multiply(7, 2)
print(fn)
Output
Welcome to Answersjet
14
If you want to Import specific function from the module:
from mypackage.demo1 import foofrom mypackage.demo2 import multiply
foo()
fn = multiply(7, 2)
print(fn)
Output
Welcome to Answersjet
14
Conclusion
Above we have discussed about python packages. You will learn about how to create Python package and also about how to import a module from a package in python programming language. In python, package is a folder which contains python modules and other python files. With the help of from...import package and dot (.) operator, we can import a python module from a package.