sort of a beginner question about globals

Steven Bethard steven.bethard at gmail.com
Wed Apr 13 18:34:30 EDT 2005


fred.dixon wrote:
> ok I'm sorry, I'm not sure what your doing there.
> if i have to guess it looks like yo might me modifying the imported
> modules dict with another dict.

Yes, this takes all the atrributes of the options object and sets them 
as attributes of the module.  If you're afraid of __dict__, you could 
also write this as:

for name, value in vars(opts).iteritems():
     setitem(options, name, value)

> isn't there a way i can just assign to a var and have it seen no matter
> what part of the code is currently executing ?

No, unless you mean only within a single module.  Python has no globals 
in the sense of being global to all modules.  If globals in a single 
module is sufficient, you can modify the globals of the current module 
using globals(), e.g.:

     globals()[name] = value

or in my example:

     globals().update(vars(opts))

You can also do this by importing the module itself, e.g.:

     mod = __import__(__name__)
     setattr(mod, name, value)

> it seems that i can import __main__ where i set the global and then
> access the var from my local func.
>
> is ther any gotcha's involveld in this ?

Probably. ;)  But since I don't know what code you've actually produced 
here, I'm not sure.  What did you write to "import __main__ ... [and] 
set the gloabl and then access the var"?

STeVe



More information about the Python-list mailing list