The Python Way for module configuration?

Hendrik van Rooyen mail at microcorp.co.za
Sun Jun 28 04:59:07 EDT 2009


 "kj" <no.email at please.post> wrote:

> I want to write a module that serves as a Python front-end to a
> database.  This database can be either in the form of tab-delimited
> flat files, XML files, or a PostgreSQL server.  The module is meant
> to hide these database implementation details from its users.
> 
> But, minimally, the module needs to have some configuration details
> to know where to get the data.  There are many ways to provide this
> configuration data to the module, but I would like to know what's
> considered "best practice" for this type of problem in the Python
> world.
> 
> Ideally, I'm looking for a system that is unobtrusive under normal
> operations, but easy to override during testing and debugging.

To pass in configuration to a module, you have basically two
choices:

- Use the command line and sys.argv
- Put the stuff in a file of some sort.

I would not recommend the first option, because it ultimately
ends up as an abomination such as we can see with gcc, where
it has spawned over elaborate systems of makefiles to tell
it how to do something - so we are back at a file, in any event.

So the questions become - how do you organise the file,
and how do you get hold of the stuff in it.

You have been pointed to configparser, and others.

You can also do a simple thing, as a module gets executed
upon import.  If your parameters are simple, this may be the
easiest way of doing it, namely to just write the bunch of
them down, all in a configuration.py file, like this:

P1 = 7
P2 = 42
alloweds = [john,mary,sally]

Then where you want to use them, you do the following:

import configuration as cf

if cf.P1 > 3:
   do something

if suspect in cf.alloweds:
   let user in
else:
   print "Go away you fiend from the nether regions"
   sys.stdout.flush()
   sys.exit()

if not cf.P2 == 42:
    print "The end of the universe has arrived - hide!"
    while True:
        pass

Do not forget that you can put a dictionary
there to handle more complex stuff.

You can also get fancy and put whole classes
of data into such a file.  In what I do, I have
never felt the need for that.

You get the drift (I hope)

- Hendrik






More information about the Python-list mailing list