Avoiding `exec', how to?

holger krekel pyth at devel.trillke.net
Thu May 30 16:55:29 EDT 2002


Fran?ois Pinard wrote:
> [Steven Majewski]
> 
> > 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__]
> 
> It works very nicely, thanks for the idea.  I now happily have:
> 
> 
> # Fabriquer une variable globale pour chaque élément de DEFS.
> module = sys.modules[__name__]

    module = __import__(__name__)

is the better way IMO.

    holger

> for name, value in defs.__dict__.items():

this is not robust if 'defs' is a subclass.
And it is desirable to avoid __*__ names if possible. 

  for name in dir(defs):
     if ...:
        setattr(mod,name,getattr(defs,name))

is the usual way to go.

    holger





More information about the Python-list mailing list