using __init__.py using __init__.py python python

using __init__.py


The vast majority of the __init__.py files I write are empty, because many packages don't have anything to initialize.

One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's __init__.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package (uselessly repetitive and error-prone: that's obviously a case in which relying on the language's guarantee that the package's __init__.py is loaded once before any module in the package is obviously much more Pythonic!).

For other concrete and authoritative expressions of opinion, look at the different approaches taken in the various packages that are part of Python's standard library.


The contents of __init__.py are imported when you import a module within the package.

You're overlooking a third scenario, which is to put the common parts in a separate module and then have the other modules import that, leaving __init__.py for things that will be used outside the package. This is the practice I usually follow.