How to do module configuration properly

J

Jan Kosinski

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.some_func()

#my_module.cfg:
[section]
global_var = /tmp/
 
J

John Nagle

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.some_func()

#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.

John Nagle
 

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,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top