Global Variables in Modules

Rich Harkins rich at worldsinfinite.com
Mon Feb 11 19:42:59 CET 2002


On Monday 11 February 2002 01:10 pm, Jeff Clement wrote:
> [stuff about importing a module and giving it globals snipped]

Although I would expect that this is generally considered bad form, you might 
look into execfile() then.  Execfile() loads and executes a file within a 
globals and locals dictionary that you optionally provide (if only Perl let 
me specify namespaces to an eval so easily).  

Or, if you're going to run the thing multiple times you could (this is a 
little cleaner):

# Do this once...
code=compile(open(filename).read(),filename,'exec')

# For each run do *ONE* of the following...
exec code					# Simple form
exec(code,globals,locals)			# Alternative form...

The downside, of course, is that expectations that your called script has 
must be provided by the calling script.  However, this can be *VERY* handy 
for complex pythonic configuration scripts, where you want to provide some 
set of objects to be configured and let a simple python script be your 
program's rc file.

Hope this helps...
Rich






More information about the Python-list mailing list