Python noob's simple config problem
kj
socyl at 987jk.com.invalid
Fri Jun 13 12:05:06 EDT 2008
In <g2s66c$mr$1 at kuling.itea.ntnu.no> =?iso-8859-1?q?Robin_K=E5veland?= Hansen <kaaveland at gmail.com> writes:
>On Thu, 12 Jun 2008 21:32:34 +0000, kj wrote:
>> I'm sure this is a simple, but recurrent, problem for which I can't hit
>> on a totally satisfactory solution.
>>
>> As an example, suppose that I want write a module X that performs some
>> database access. I expect that 99.999% of the time, during the
>> foreseeable future, the database connection parameters will remain
>> unchanged. The only exception that I envision for this would be during
>> testing or debugging.
>>
>> Given all this, I am tempted to turn these connection parameters into
>> hard-coded module attributes that I can always override (i.e. overwrite)
>> when necessary.
>>
>> But for as long as I can remember the dogma has been that hard-coded
>> values are bad, and that one should use other techniques, such as
>> configuration files, or parameters to a suitable constructor, etc.
>>
>> This is where I begin to get confused: whose responsibility is it to
>> know of and read the config file? I can think of two distinct
>> scenarios: 1) module X is being used by a large, full-fledged
>> application A that already uses a config file for its own configuration;
>> 2) module X is being used by a simple script that has no need for a
>> config file. In case 1 I'd be glad to let application A set module X's
>> connection parameters using values read from its own (i.e. A's) config
>> file; this minimizes the number of config files that need to be
>> maintained. In case 2, however, it would be preferable for module X to
>> read its connection params from its own (i.e. X's) config file. In this
>> way the script won't have to bother setting some parameters that are in
>> fact practically constant...
>>
>> After going round and round on this, my original idea of hard-coding the
>> values as module attributes begins to look pretty attractive again.
>>
>> How would you handle such situations?
>>
>> Thanks!
>>
>> kynn
>I think I would just abstract it away with a "getter" for the connection,
>a function that takes some optional parameters, if not supplied, it
>simply fetches them from a default configuration. Ie:
>def connect(params=None):
> if params is None:
> return dblayer.connect(conf["default"])
> else:
> return dblayer.connect(params)
>Unless I have misunderstood you completely? Now people can change your
>scripts config file, and if someone wants to use your code, they can use
>the getter directly.
>I hope this is of some help.
Thanks!
Kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
More information about the Python-list
mailing list