Avoiding `exec', how to?
Chris Liechti
cliechti at gmx.net
Thu May 30 17:43:56 EDT 2002
pinard at iro.umontreal.ca (François Pinard) wrote in
news:mailman.1022792988.25468.python-list at python.org:
> [holger krekel]
>> 2) mod = __import__('currentmodulename')
>> for name in filter(lambda x: x[0]!='_', dir(defs)):
>> setattr(mod, name, defs[name])
> ... Your code fragment bears an excellent
> suggestion, by which `dir()' allows getting rid of `__dict__'. Thanks
> for this tip!
please not that the output of "dir" has changed over the versions. i think
there was a message on the group this or last week about that. (it was bout
dir and classes/types)
> # 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'.
ok i couldn't resist :-)
moddict = __import__(__name__).__dict__
defs = {'a':1, 'b':2}
moddict.update( dict(filter(lambda k: k[0][0]!='_', defs.items())) )
del defs, moddict
altough a list comprehension is more readable:
moddict = __import__(__name__).__dict__
defs = {'a':1, 'b':2}
moddict.update( dict([ (k,v) for k,v in defs.items() if k[0]!='_']) )
del defs, moddict, k, v
chris
he, always interesting how a simple questions generate that many traffic on
the list! (and in your inbox)
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list