How to do module configuration properly
nagle at animats.com
Fri Oct 22 19:17:03 CEST 2010
On 10/22/2010 4:22 AM, Jan Kosinski wrote:
> I have created a python module, which contains a bunch of utility
> functions that use a number of global variables (directory and file
> names, etc.).
> I want to move that global variables to an external configuration
> file and I want to load all global variables from that configuration
> file when module is imported.
> I am not sure which is the proper way of doing that. At the moment I
> use the solution as in the following example, is it fine?
> #my_module.py: import ConfigParser
> config = ConfigParser.SafeConfigParser() config_f =
> open('my_module.cfg') config.readfp(config_f) config_f.close()
> global_var = config.get('section', 'global_var')
> def some_func(): print global_var
> #my_script.py: import my_module
> #my_module.cfg: [section] global_var = /tmp/
In general, it's a bad idea to do I/O during module import.
It's hard to deal with errors. If the program is running as a service,
the service isn't up yet, and if it's a GUI application, the GUI
isn't up yet. So error reporting tends to be poor.
If you have something with state, it's usually better to
define a class, and initialize a singleton instance of the class
from the main program, where you can handle errors.
More information about the Python-list