Avoiding `exec', how to?

François Pinard pinard at iro.umontreal.ca
Thu May 30 17:08:05 EDT 2002


[holger krekel]

>    Also the use of dir/getattr allows for 'defs' to be subclassed.
>    Using '__dict__' doesn't and is somewhat ugly.

Hello, Holger.

I do not well understand your argument here -- but I agree that __dict__ is
not fully nice.  What is the problem of not allowing `defs' to be subclassed?
I do not have any need for subclassing it, it is a rather simple thing...

> 2)  mod = __import__('currentmodulename') 
>     for name in filter(lambda x: x[0]!='_', dir(defs)):
>         setattr(mod, name, defs[name])

>     (assuming you like lambda functions, which i do).

I can easily grok `lambda', when used parsimoniously, and preferably by
others than me! :-) Your code fragment bears an excellent suggestion,
by which `dir()' allows getting rid of `__dict__'.  Thanks for this tip!
Combining your suggestion with others, the little piece of code is now:


# Fabriquer une variable globale pour chaque élément de DEFS.
module = sys.modules[__name__]
for name in dir(defs):
    if name[0] != '_':
        setattr(module, name, getattr(defs, name))
del defs, module, name


The code would be less clear, for me, if it was using `filter' and `lambda'.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list