What do you use __init__.py for?

R

redefined.horizons

I have just started learning about Python Packages. I know that a
directory must contains the '__init__.py' script to be considered a
Python package, and that this script is executed when the package is
imported.

But what other uses does the '__init__.py' script have? What do you
use it for?

I imagine it could provide, at the least, some helpful metadata about
the contents and dependencies of the package.

I'm just looking for ideas...

Thanks,

Scott Huey
 
A

alisonken1

(e-mail address removed) wrote:
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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,268
Latest member
AshliMacin

Latest Threads

Top