What do you use __init__.py for?

alisonken1 alisonken1 at gmail.com
Thu Apr 27 15:25:17 EDT 2006


redefined.horiz... at gmail.com wrote:
<snip>
> But what other uses does the '__init__.py'  script have? What do you
> use it for?
<snip>

__init__.py is used for initialization of the package - similar to
__init__() in a function or class declaration.

One example would be if you create a package with generic database
methods - you can, in the __init__.py file, configure which actual
database drivers are used but only have to write your routines to the
generic setup.

Module structure:
<db directory>
__init__.py
<db directory>/my_bsddb
--> files for bsddb access go here

<db directory>/my_postgresql
--> files for postgresql access go here


Example __init__.py (pseudo coded, not python coded):
====================
if (configure_database == "berkelyDB"):
    import my_bsddb as db

elif (configure_database == "postgresql"):
    import my_postgresql as db

else:
    log("DB config error - no valid datbase selected")

====================

Then, in your routines, you only need to call db.<method/function>




More information about the Python-list mailing list