what is __init__.py used for?

George Sakkis gsakkis at rutgers.edu
Tue Jul 5 15:44:08 CEST 2005

"John Roth" <newsgroups at jhrothjr.com> wrote:

> The other is as the module itself. Let's take a simple
> example. Assume you have a directory named breakfast
> which contains modules named spam.py, eggs.py,
> toast.py and jam.py, and that the directory containing
> breakfast is on the PYTHONPATH.
> If it try to import spam.py by writing
> import breakfast.spam
> it won't work because the breakfast directory
> doesn't contain an __init__.py file.
> If I then add __init__.py to the breakfast directory,
> the import will work, and the result will be *two*
> modules loaded. The first module will be bound to
> the identifier 'breakfast' in your module. It will be
> completely empty except for the identifier 'spam'
> which will have the spam module bound to it.

There is also an alternative form of import that does not load the
intermediate modules (actually packages), only the last one:
>>> import breakfast.spam as spam

Here you can refer to names defined in breakfast.spam as spam.eat(),
spam.slice, etc. However you can't refer to breakfast; if you do,
you'll get a NameError exception:

>>> import breakfast.spam as spam
>>> breakfast.spam
NameError: name 'breakfast' is not defined

In either form of import though, the __init__.py has to be in the
breakfast directory.


More information about the Python-list mailing list