[Django]-Why django contains a lot of '__init__.py'?

11👍

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.

7👍

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

Leave a comment