I have created a .ini-like file with all the values which I need later in my program, see below:
[debugging]
checkForAbort = 10
...
[official]
checkForAbort
What J.F. Sebastian said.
Also, you could do it like Alex Martelli does in his Bunch class:
file MyConfig.py:
from ConfigParser import SafeConfigParser
section_names = 'official', 'debugging'
class MyConfiguration(object):
def __init__(self, *file_names):
parser = SafeConfigParser()
parser.optionxform = str # make option names case sensitive
found = parser.read(file_names)
if not found:
raise ValueError('No config file found!')
for name in section_names:
self.__dict__.update(parser.items(name)) # <-- here the magic happens
config = MyConfiguration('my.cfg', 'other.cfg')
file foo.py:
from MyConfig import config
# ...
file MyProgram.py:
from MyConfig import config
print config.checkForAbort
import foo
assert config is foo.config
The Python Language Reference states that "Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs)."
What that means is that, when a module gets imported, one or more local names are bound to a module object, and only the first time it is imported during the runtime of a Python program it gets initialized (i.e. read from file and run).
In the code above the name config is just a local name that refers to an attribute of a module object. The module object has been initialized by the Python interpreter when it was referenced (via from MyConfig import config) in MyProgram. When MyProgram imports foo it is already initialized and gets bound to a local name in module foo and in MyProgram we can refer to it as foo.config. But both names refer to the very same object.