what is __init__.py used for?

John Roth newsgroups at jhrothjr.com
Tue Jul 5 07:39:51 EDT 2005


<zelzel.zsu at gmail.com> wrote in message 
news:1120552269.373658.254290 at g49g2000cwa.googlegroups.com...
>I am a new learner of Python Programming Language.
> Now. I am reading a book.

...

> ==========
>   I was wonderring ... what is the __init__.py used for ?
>   This question may seems to be stupid for an expert.
>   But, if you can give the answer, it will be helpful for me.

__init__.py is used for two things. One is as a flag to
indicate that the python programs in the directory are
part of a module.

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.

This means that if the spam module contains,
for example, an identifier named "vikings", then I
can refer to it as breakfast.spam.vikings.

The real kicker here is that when I say that the
first module will be completely empty, it's not
quite true. First, it will have some standard
identifiers that all modules have, and second
it will have anything you put into the __init__.py
module file. This last is an advanced feature, and
you're well advised to stay away from it until
you've got a lot more experiance.

HTH

John Roth


>
>  thanks.
> 




More information about the Python-list mailing list