views:

472

answers:

2
+5  Q: 

using __init__.py

I am not getting usage scenarios or design goals of python __init__.py in my projects.

Assume that I have 'model' directory (refers as a package) which I have kept the following files.

1. __init__.py
2. meta.py
3. solrmodel.py
4. mongomodel.py
5. samodel.py

I found two ways of using __init__.py.

  1. I have common definition which needs to be used in solrmodel.py, mongomodel.py, samodel.py. In this case, can I use __init__.py as a base/common definition for all the *model.py classes? This means that I have to import model/__init__.py.

  2. Or, the __init__.py shall have imported definitions of solrmodel.py, mongomodel.py, samodel.py in its own and it allows the easy import of classes or function like this:

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

    (I am aware that import * is not recommended and I just used it as a convention)

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

References: Python docs says initialization of packages. I could not understand what is there in a package to initialize.

http://www.python.org/doc/2.1.3/tut/node8.html

+3  A: 

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.

Ignacio Vazquez-Abrams
+5  A: 

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.

Alex Martelli
Pylons recommend to put the models inside the __init__.py. Is it OK? Does that really initialize the model in that way?
Gopalakrishnan Subramani
Personally, I would rather not put substantial code in `__init__.py`, but there's no deep reason to avoid it -- it's purely a style choice. All code in that file is executed the first time you import the package, or any module from the package.
Alex Martelli