The subdirectory that you are importing from is a package if it has an __init__.py
file in it. You don't need to use packages, you can just add the subdirectory to the sys.path
list. However they are a neat way of keeping related modules together and are generally encouraged.
The __init__.py
file has a similar purpose to the __init__
in a class, it initialises the package. This enables attributes to be given to the package, and __all__
is an example (list of exported names for import *
).
There is sometimes no initialisation required, so it can be empty. A good place to look for examples is in the standard library subdirectories of the Lib
directory. There you will find huge __init__.py
files, and others that are empty.
Whether this is mandatory or not depends on the Python version. From Python 3.3 the __init__.py
is not mandatory, and such packages are called Namespace Packages, see PEP0420. This means that a package can span directories, but there is a price to pay. There can be no __init__.py
initialisation code and you don't get a __file__
attribute for the package. So unless you specifically need to span directories it is probably better to stick with regular packages.