Thursday, January 28, 2016

Packaging in right way

How to make packages in python?

Packaging is very important in case of building any application using programming language. Python has a very unique and easy way to do this.

Say we want to call a function[mod()] written into /work/pyws/pac/dir1/mod1.py
from a caller.py which is in /work/pyws/pac/ 

To do that we need to follow below steps:

  1.  We need to set the python path[i.e. from where modules get loaded] It can be done using command:- export PYTHONPATH=$PYTHONPATH:/work/pyws/pac/
  2.  In each directory we need to create __init__.py [content might be left as blank]
  3.  We need to import the file before calling a function. e.g. from dir1 import mod1


I will demonstrate the above steps using my sample code snipptes in the following section.

Say we are in /work/pyws/pac/ directory. Here we have a caller.py inside /work/pyws/pac/
==caller.py===
from dir1 import mod1

def f():
   mod1.mod()

f()
===end of caller.py===

AND a blank __init__.py file.

Inside /work/pyws/pac/dir1 we have mod1.py.
===mod1.py===
def mod():
   print "inside mod1"
===end of mod1.py====

AND a blank __init__.py file.

Now run caller.py [python caller.py]
You will get output:
[root@XXXXX pac]# python caller.py
inside mod1

Try it yourself and comment below if you have any problem.

No comments:

Post a Comment