[Tutor] Configuaration files and paths?

Martin Walsh mwalsh at mwalsh.org
Fri Aug 7 03:47:24 CEST 2009


Allen Fowler wrote:
> 
> 
>> Martin Walsh <mwalsh at mwalsh.org>
>>
> 
>> Allen Fowler wrote:
>>> As a follow-up question, how do give my modules stored under ./lib access to 
>> the data in my ConfigParser object?  (For instance, database connection string, 
>> storage path, etc.)
>>> I guess a global ConfigParser object would work, but that seems wrong.
>>>
>> And yet, to me it seems wrong to have more than one instance of config
>> data floating around. Instead of using a global you can pass the config
>> object, or just the appropriate attributes, around to your lib
>> functions/classes, as necessary -- and keep the flow in your main
>> script. For example (highly speculative, FWIW),
>>
>> # app.py
>> from database.connection import getcursor
>> from lib.persist import Storage
>>
>> def main():
>>     confp = ConfigParser()
>>     confp.read(join_relative(__file__, 'config/prefs.ini'))
>>     config = confp.defaults()
>>
>>     curs = getcursor(config[db_connection_string])
>>
>>     ...
>>
>>     storage = Storage(config[storage_path])
>>
>>    
> 
> 
> I hear your point.  It makes sense.
> 
> 
> The above sample code seems like the way to go... if I can structure my modules like that.
> 
> For an object that needs many settings, what about passing in an instance of ConfigParser?  (Or should I extract the settings to a dict, first?)
> 
> Thank you again,
> :)
> 

I don't see a problem with either of those approaches -- I suppose it
depends a little on the kind of config data you're working with, the
overall design of your app, which approach would be easiest to maintain.

If your intent is to package software that the general public will use,
then I believe Alan and Dave have correctly advised to follow the
packaging conventions for your target platform(s), and to be consistent
with user expectations (ie. how do popular apps typically handle config?)

I tend to write a lot of system automation scripts (sysadmin-style),
where I'm one of the few internal end users, and my toolbox module
contains wrappers for the various sources of config data (configparser,
optparse, os.environ, etc) each providing a common interface that I like
to use (and remember easily!) for dealing with config data in new
function and class definitions. But I use these a lot, and wouldn't
necessarily recommend the approach if you only need to consume config
data now and again. I think the point I may be trying to make is that it
took me a while to settle, after much trial and error, to find the
approach that works best for me -- others will have a different story to
tell, and I hope they do! :)

Good luck!

Marty



More information about the Tutor mailing list