Python logo

Python Package

In the last post I discussed about Python Module. From last post we came to know that a Python module is simply a Python source file, which can expose classes, functions and global variables.So, what is Package? The simple striate-forward answer is “A Python package is simply a directory of Python module(s).”

Make a Package

I assume that you are now familiar with module. When you are going to make a module you might have to make package. Hence, I show you how to build a package.

Example:

Suppose we are going to make a package name my_math. Actually my_math is a directory where we can keep one or more modules. Before put the modules we must create a file __init__.py. So, what is __init__.py do? It initializes the package my_math. If you you import something like modules,classes and so on, you may write the name of them on it or you may keep it empty. However, you must create a __init__.py in package directory and it’s subpackage directories. The my_math package directory structure is look like following

screenshot-from-2016-10-20-004512

Again we make another module named arith. We must create __init__.py inside the arith directory also. We also include a file named ops.py.

Finally, create another module named geo and include two files named circle.py , square.py. Final view of my_math package is like following:

screenshot-from-2016-10-20-010112

Use A Package

If we want use the geo module of my_math package we have write as following at the top of file.

import my_math.geo

 

again, if we want use the methods inside imported module, we have use a dot(.) module name and then method name

import package_name.module_name.file_name.function_name

 

suppose you want to use area method of circle.py of geo module, you may impoert the function as following:-

from my_math.geo.square import area

#use in code as below:

lenth=100
width=150
sa=area(lenth,width)
print ca ## area 15000

alternatively we can also import like this:-

import my_math.geo.square.area

#then

lenth=100
width=150
sa=my_math.geo.square.area(lenth,width)
print ca # area 15000

 

we can short the code using Alias :

import my_math.geo.square as square

lenth=100
width=150
sa=square.area(lenth,width)
print ca # area 15000

 

Leave a Reply

Your email address will not be published. Required fields are marked *