Avoiding `exec', how to?

Steven Majewski sdm7g at Virginia.EDU
Thu May 30 16:20:56 EDT 2002


On 30 May 2002, [iso-8859-1] François Pinard wrote:

> Hi, my fellow snakes :-).
>
> I do not like using `exec', and wonder if there is a way to avoid it in:
>
>
> # Fabriquer une variable globale pour chaque lment 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.


setattr will work for modules and is the best way to dynamically
'evaluate' assignments:

	setattr( module, name, value )

If you have to get a handle to a module while it's being executed
on it's initial import, you can use:

	import sys
	module = sys.modules[__name__]

If you want the assignments to be in the main module, use:

	import __main__
	module = __main__

which will work even executed in the __main__ module.


-- Steve Majewski









More information about the Python-list mailing list