Using __init__.py

I'm having difficulty understanding use cases or design goals for python __init__.py files in my projects.

Suppose I have a “model” directory (refers to a package) that contains the following files

  • __init__.py
  • meta.py
  • solrmodel.py
  • mongomodel.py
  • samodel.py

I found two ways to use __init__.py :

  • I have a generic definition that needs to be used in solrmodel.py , mongomodel.py , samodel.py . Can I use __init__.py as the base / general definition for all * model.py classes? This means that I need to import model/__init__.py .

  • Or, __init__.py should import the definitions of solrmodel.py, mongomodel.py, samodel.py into its own, and this makes it easy to import classes or execute a function as follows:

     # file: __init__.py from mongomodel import * from solrmodel import * from samodel import * 

    (I know that import * not recommended, and I just used it as a convention)

I could not decide between the two above scenarios. Are there more usage scenarios for __init__.py and can you explain the usage?

+60
python initialization module packages
Mar 02
source share
2 answers

The vast majority of __init__.py files that I write are empty, because many packages have nothing to initialize.

One example in which I can start initialization is when, during the download of a package, I want to read a bunch of data once and for all (from files, a database or a network, say) - in this case it is much better to do this reading in a private function in the __init__.py package instead of having a separate “initialization module” and redundantly importing this module from each separate real module in the package (uselessly repeating and -prone error: this is obviously the case when relying on the language, ensuring that the package __init__.py loaded once before m any module in the package is obviously much larger than Pythonic!).

For other specific and authoritative expressions of opinion, see the various approaches adopted in the various packages that are part of the Python standard library.

+47
Mar 02 '10 at 6:26
source share

The contents of __init__.py imported when the module is imported inside the package.

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

+22
Mar 02
source share



All Articles