Python Packages

A package is a hierarchical file directory structure that has modules and other packages within it. Every package in Python is a directory that must have a special file called This file may not even have a single line of code. It’s simply added to indicate that this directory is not an ordinary directory and contains a Python package.


import MyPackage.MyModule // To create a package that is called MyPackage having the module MyModule.

Properties of Packages:

1. Packages are searched for in the path specified by [python]sys.path[/python].

2. [python][/python] file can be an empty file and may also be used to execute initialization code for the package or set the __all__variable.

3. The import statement first checks if the item is defined in the package. If it is unable to find it, an ImportError exception is raised.

4. When importing an item using syntax like import item.subitem.subitem, each item except the last must be a package. That is the last item should either be a module or a package. In no case, it can be a class or function or variable defined in the previous item.

5. Packages have an attribute [python]__path__[/python] which is initialized with a list having the name of the directory holding the [python][/python] file. The [python]__path__[/python] attribute can be modified to change the future searches for modules and sub-packages contained in the package.