Global Variables in Modules
Jeff Shannon
jeff at ccvcorp.com
Tue Feb 12 14:05:43 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 :)
Chances are that if you're using exec, you're not doing things in the best way possible. In the year that I've been using Python, I don't think I've seen *any* situation that's best done with an exec. (Admittedly, I haven't been doing anything at all esoteric, but still....) I'd recommend seriously
rethinking your architecture, honestly--exec/eval() are nice to have around, just in case, but using them is a big red flag that something ugly is going on. (It's good to have a fire extinguisher, too, but I wouldn't use one to put out a candle....)
However, as far as the global variables go... if you really must do this, then the best solution is to have a separate module (called globalvars or constants or whatever) that all your other modules import; they can then read (and modify) variables in that module as needed. (Though beware that while
global constants are useful, depending on global variables *is* a major source of bugs... do it if you need to, but be careful. :) )
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list