Avoiding `exec', how to?

holger krekel pyth at devel.trillke.net
Thu May 30 16:18:32 EDT 2002


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 élément de DEFS.

i think i understand that :-)

> 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

basically 

1) glob = globals()
   for name in dir(defs):
       if name[0]!='_':
            glob[name]=getattr(defs,name)

   which relies on beeing able to use __setitem__
   on the dictish object returned by 'globals()' 
   Also the use of dir/getattr allows for 'defs' to
   be subclassed. Using '__dict__' doesn't and is
   somewhat ugly.
   
2)  mod = __import__('currentmodulename') 
    for name in filter(lambda x: x[0]!='_', dir(defs)):
        setattr(mod, name, defs[name])

    if you know the module global scope.
    this way you can have this code outside of the module.
    (assuming you like lambda functions, which i do).

regards,

    holger





More information about the Python-list mailing list