OK, here's another software design question, one that's been bugging me
for a while now. What do y'all think is the best way to handle
program-level globals, such as configuration option -- especially in
multi-module programs?
Here's one approach:
--- main.py ---
import my_globals as g
import somefuncs
import morefuncs
from optparse import OptionParser
def main():
parser = OptionParser()
parser.add_opti on( ... )
g.opts, g.args = parser.parse_ar gs()
somefuncs.do_se tup()
morefuncs.do_so me_more_setup()
somefuncs.do_so me_work()
if __name__ == '__main__':
main()
--- somefuncs.py ---
import my_globals as g
def do_setup():
if g.opts.some_opt ion:
do_it_one_way()
else:
do_it_a_differe nt_way()
--- morefuncs.py ---
import my_globals as g
def do_some_more_se tup():
for arg in g.args:
do_something_wi th(arg)
--- my_globals.py ---
(empty file)
This approach relies on the fact that modules only get imported once.
Thus when each module imports my_globals, it gets the *same* object
(which is then given the name g to make it easier to write later). So
when the attributes of g are modified in the main() function, they can
then be read by do_setup() and do_some_more_se tup(), because the object
that somefuncs.py and morefuncs.py call "g" is the same module object
that main.py also calls "g".
This is the best approach I've found so far, but I would welcome
comments and suggestions for improvements.
--
Robin Munn
rm***@pobox.com