I’m taking a look at how the model system in django works and I noticed something that I don’t understand.
I know that you create an empty __init__.py file to specify that the current directory is a package. And that you can set some variable in __init__.py so that import * works properly.
But django adds a bunch of from … import … statements and defines a bunch of classes in __init__.py. Why? Doesn’t this just make things look messy? Is there a reason that requires this code in __init__.py?
All imports in
__init__.pyare made available when you import the package (directory) that contains it.Example:
./dir/__init__.py:./test.py:EDIT: forgot to mention, the code in
__init__.pyruns the first time you import any module from that directory. So it’s normally a good place to put any package-level initialisation code.EDIT2: dgrant pointed out to a possible confusion in my example. In
__init__.pyimport somethingcan import any module, not necessary from the package. For example, we can replace it withimport datetime, then in our top leveltest.pyboth of these snippets will work:and
The bottom line is: all names assigned in
__init__.py, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.