In order for Python to make use of a directory as package, the
directory must have a name that is a valid Python identifier and contain
a special module named __init__
. Valid Python
names are composed of letters, digits and underscores. See the section called “Variables” for more informaiton.
The __init__
module is often an empty file,
__init__.py
in the package directory. Nothing else
is required to make a directory into a package. The
__init__.py
file, however, is essential. Without
it, you'll get an ImportError
.
For example, consider a number of modules related to the
definition of cards. We might have the following files.
cards/
__init__.py
standard.py
blackjack.py
poker.py
The cards.standard
module would provide the
base definition of card as an object with suit and rank. The
cards.blackjack
module would provide the
subclasses of cards that we looked at in the section called “Blackjack Hands”. The
cards.poker
module would provided the subclasses
of cards that we looked at in the section called “Poker Hands”.
The cards.blackjack module and the cards.poker module should both
import the cards.standard module to get the base definition for the
Card
and Deck
classes.
The __init__
module. The __init__
module is the
"initialization" module in a package. It is processed the first time
that a package name is encountered in an
import
statement. In effect, it initializes Python's understanding of the
package. Since it is always loaded, it is also effectively the default
module in a package. There are a number of consequences to
this.
-
We can import the package, without naming a specific module.
In this case we've imported just the initialization module,
__init__
. If this is part of our design,
we'll put some kind of default or top-level definitions in the
__init__
module.
-
We can import a specific module from the package. In this
case, we also import the initialization module along with the
requested module. In this case, the __init__
module can provide additional definitions; or it can simply be
empty.
In our cards example, above, we would do well to make the
__init__
module define the basic
Card
and Deck
classes. If
we import the package, cards
, we get the default
module, __init__
, which gives us
cards.Card
and cards.Deck
.
If we import a specific module like
cards.blackjack
, we get the
__init__
module plus the named module within the
package.