Another software design question: program-level globals

Robin Munn rmunn at pobox.com
Fri Feb 13 13:43:54 EST 2004


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_option( ... )
    g.opts, g.args = parser.parse_args()

    somefuncs.do_setup()
    morefuncs.do_some_more_setup()
    
    somefuncs.do_some_work()

if __name__ == '__main__':
    main()


--- somefuncs.py ---
import my_globals as g

def do_setup():
    if g.opts.some_option:
        do_it_one_way()
    else:
        do_it_a_different_way()


--- morefuncs.py ---
import my_globals as g

def do_some_more_setup():
    for arg in g.args:
        do_something_with(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_setup(), 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
rmunn at pobox.com



More information about the Python-list mailing list