It's just personal preference really, and has to do with the layout of your python modules.
Let's say you have a module called erikutils
. There are two ways that it can be a module, either you have a file called erikutils.py on your sys.path
or you have a directory called erikutils on your sys.path
with an empty __init__.py
file inside it. Then let's say you have a bunch of modules called fileutils
, procutils
, parseutils
and you want those to be sub-modules under erikutils
. So you make some .py files called fileutils.py, procutils.py, and parseutils.py:
erikutils
__init__.py
fileutils.py
procutils.py
parseutils.py
Maybe you have a few functions that just don't belong in the fileutils
, procutils
, or parseutils
modules. And let's say you don't feel like creating a new module called miscutils
. AND, you'd like to be able to call the function like so:
erikutils.foo()
erikutils.bar()
rather than doing
erikutils.miscutils.foo()
erikutils.miscutils.bar()
So because the erikutils
module is a directory, not a file, we have to define it's functions inside the __init__.py
file.
In django, the best example I can think of is django.db.models.fields
. ALL the django *Field classes are defined in the __init__.py
file in the django/db/models/fields directory. I guess they did this because they didn't want to cram everything into a hypothetical django/db/models/fields.py model, so they split it out into a few submodules (related.py, files.py, for example) and they stuck the made *Field definitions in the fields module itself (hence, __init__.py
).
__init__.py
django 1.8. Was this for an older version? if so which version? – Rubbico__init__.py
. Unfortunately I still haven't found any solid answers on what can go wrong or what's best practice with putting code in__init__.py
. One answer below suggested it's historical and a re-write would do it differently. I think that's my only take-away. – Aletheaalethia