Python Package : Python Tutorial 19

Python Package :

What is a python package ? In simple words , python packages are directories containing python files. We love to arrange files in our computer in different directories, like all movies in a “movie” folder or all songs in a “songs” folder etc.

So, what is the use of using packages ? We can keep similar files in the same folder. If your application is of large number of files, then don’t you think that it would be better to place related files in a same folder instead of placing in separate folders ?

Inside a folder or package , we can create another package ,known as sub-package. Similarly , inside a sub-package , we can also have another package. 

How Does python recognises package : 

As packages are simply folders, how does python know these folders are python - packages ? Let’s take a look how to create a python package :

  1. Create a folder and place your python files (.py files ) inside it .

  2. Create one**** file inside the folder.

i.e. if a folder contains” file, it is a package.

Example of python package :

Let’s create a directory “project_dir”. Inside this directory, create one file “”. Now create two more directories “package_one” and “package_two”. Inside “package_one” create two files : “” and “” . And inside “package_two” create one file : “”. So the structure will be like :

/project_dir :
                —— /package_one
                —— /package_two

So, “package_one “ directory is a package . Now we will try to call “” from “” and “” from “” .

Edit as : 

def func_one():
    print "inside function one"

Now to call “func_one” of “” from “”, we need to import it first :

from import func_one and after that we can call “func_one” .

Edit “” as below : 

from import func_one

It will print Inside function one .  So, you have seen that we can directly call a function of a package by importing the package . But , how can we call “” from “” ? Both are in the same level !!

using “sys.path.append” . Edit “” as below : 

import sys
from import func_one


Now , if you run “” , it will provide the output  “Inside function one “ .

Actually, python check for packages in all directories defined in “sys.path”. So, we have appended the parent path to “sys.path” .


Similar tutorials :