Wednesday, 15 March 2017

Import Python Modules/Packages with example



This short article describes how to include the python modules. This will help the python developers to refresh the syntax. 
For detailed articled go to https://docs.python.org/3/tutorial/modules.html#packages

Import a single file:
Lets take a python file say test.py

test.py

def testMod():
    print("In test module")

 To include this file in your python project, 

myPyt.py

#
# My python Project
#
import test
test.testMod()

Output:   
In test module
Import a library (directory of python files):

This concept is called Packaging/Packages.
Lets say library called 'lib' contains two python files 'test1.py' and 'test2.py'. 

lib/test1.py

def test1Mod():
    print("In test1 module")

lib/test2.py
 
def test2Mod():
    print("In test2 module")
Now create a empty file called __init__.py in the directory to be imported which is lib here
touch __init__.py

lib contains the following the files.
__init__.py
test1.py
test2.py
Now simply import this lib into your python file/project:

myPyt.py

#
# My python Project
#
from lib import test1,test2
test1.test1Mod()
test2.test2Mod()

Output:

In test1 module
In test2 module

__init__:
 
The
__init__.py file is the one which makes Python treat the directory as a package.

Generally import lib.* will import all the files in lib. To prevent this add a list called __all__ in __init__.py of the package/directory.

__init__.py
__al1__ = ["test1"]

Now 
from lib import  *    will import only test1













No comments:

Post a Comment