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 ?
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 :
- Create a folder and place your python files (.py files ) inside it .
- Create one __init__.py file inside the folder.
Example of python package :
Let’s create a directory “project_dir”. Inside this directory, create one file “main.py”. Now create two more directories “package_one” and “package_two”. Inside “package_one” create two files : “__init__.py” and “one.py” . And inside “package_two” create one file : “two.py”. So the structure will be like :
/project_dir : —— main.py —— /package_one — __init__.py — one.py —— /package_two — two.py
So, “package_one “ directory is a package . Now we will try to call “one.py” from “main.py” and “one.py” from “two.py” .
def func_one(): print "inside function one"
from package_one.one import func_one and after that we can call “func_one” .
from package_one.one import func_one 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 “one.py” from “two.py” ? Both are in the same level !!
import sys sys.path.append('../') from package_one.one import func_one func_one()
Now , if you run “two.py” , it will provide the output
“Inside function one “ .