What are packages and how to create and use packages
Get to know packages
Packages are used to organize modules. While a module is stored in a file with the file name extension .py, a package is a directory.
To make Python treat it as a package,
the folder must contain a file (module) named __init__.py
.
The contents of __init__.py
is the contents of the package,
if you import it as if it were a plain module.
For example, if you have a package named constants, and the file constants/__init__.py contains the statement PI = 3.14, you would be able to do the following:
import constants
print constants.PI
The following table illustrates a simple package layout.
To put modules inside a package, we can put the module files inside the package directory. For example, if you wanted a package called drawing, which contained one module called shapes and one called colors, you would need the files and directories as the follows.
File/Directory | Description |
---|---|
~/python/ | Directory in PYTHONPATH |
~/python/drawing/ | Package directory (drawing package) |
~/python/drawing/__init__.py | Package code ("drawing module") |
~/python/drawing/colors.py | colors module |
~/python/drawing/shapes.py | shapes module |
~/python/drawing/gradient.py | gradient module |
~/python/drawing/text.py | text module |
~/python/drawing/image.py | image module |
With this setup, the following statements are all legal:
import drawing # (1) Imports the drawing package
import drawing.colors # (2) Imports the colors module
from drawing import shapes # (3) Imports the shapes module
After the first statement, import drawing
,
the contents of the __init__ module in drawing would be
available but the drawing and colors modules would not be available.
After the second statement, import drawing.colors
,
the colors module would be available,
but only under its full name, drawing.colors.
After the third statement from drawing import shapes
,
the shapes module would be available, under its short name shapes
.