views:

133

answers:

2

Many directories in a django project contain a __init__.py and I think it will be used as initialization for something. Where is this __init__.py used?

+4  A: 

Your question is not clear. What exactly are you asking?

The file __init__.py is there so your folder can be defined as a package, which lets you do things like:

from myapp.models import Something
Nick Presta
+5  A: 

Python doesn't take every subdirectory of every directory in sys.path to necessarily be a package: only those with a file called __init__.py. Consider the following shell session:

$ mkdir adir
$ echo 'print "hello world"' > adir/helo.py
$ python -c 'import adir.helo'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named adir.helo
$ touch adir/__init__.py
$ python -c 'import adir.helo'
hello world

See? With just directory adir and module helo.py in it, the attempt to import adir.helo fails. If __init__.py also exists in adir, then Python knows that adir is a package, and therefore the import succeeds.

Alex Martelli