Avoiding `exec', how to?

Chris Liechti cliechti at gmx.net
Thu May 30 17:17:56 EDT 2002


pinard at iro.umontreal.ca (François Pinard) wrote in 
news:mailman.1022786751.23084.python-list at python.org:
> I do not like using `exec', and wonder if there is a way to avoid it in:
> 
> # Fabriquer une variable globale pour chaque élément de DEFS.
> for name, value in defs.__dict__.items():
>     if name[0] != '_':
>         # J'aimerais bien éviter `exec'...
>         exec '%s = %s' % (name, repr(value))
> del defs, name, value
> 
> The goal here is to initialise one global variable per item in DEFS,
> preserving the item name and value in each.

>>> dir()
['__builtins__', '__doc__', '__main__', '__name__', 'pywin']
>>> import __main__
>>> d = {'a':1, 'b':2}
>>> __main__.__dict__.update(d)
>>> dir()
['__builtins__', '__doc__', '__main__', '__name__', 'a', 'b', 'd', 'pywin']
>>> a
1

:-)) there isn't truly something as "global" in python. global is always 
the namespace of the current module.
if it's not your main module you must get the __dict__ of the current one. 
globals() gives you this, but you should not modify it...

this seems to work for a module, __main__ or any other:

moddict = __import__(__name__).__dict__
moddict.update( {'a':1, 'b':2} )

(puh, so many underlines ;-)
chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list