Global Variables in Modules

Jason Orendorff jason at jorendorff.com
Mon Feb 11 15:22:25 EST 2002


Jeff Clement wrote:
> What I'm actually doing is running a code block in an exec block 
> and declaring a bunch of globals for that exec.  The code block 
> imports some modules and I need those to be able to see the 
> global variables.  I can make this work by adding them to 
> __builtins__ but that doesn't seem right somehow :)

The best thing is to make a config.py, and have
everyone just "import config".  All the code for setting up those
globals should be inside config.py.  You can probably avoid exec
entirely (which is for the best).

Failing that, you can have an empty config.py and do:

  # test.py
  # Import the empty module and populate it using exec.
  import config
  exec "...huge string of globals and imports..." in config.__dict__

  # test_mod.py
  import config
  print config.A

Worst case, you can just:

  # test_mod.py
  import __main__
  print __main__.A

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list