dynamic module import?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jan 17 06:55:34 CET 2009


On Fri, 16 Jan 2009 20:36:50 -0800, alex23 wrote:

> On Jan 17, 3:34 pm, Eduardo Lenz <l... at joinville.udesc.br> wrote:
>> modu = "os"
>> exec("from " + modu + " import *")
> 
> And of course, there's the usual disclaimer that this should be only
> used in circumstances where you can guarantee the contents of 'modu'
> aren't ever going to be anything like:
> 
> modu = "os import system; system('rm *'); from os "
> 
> Another reason to prefer __import__ over exec is speed:

Both very good points, but consider that you're not comparing apples with 
apples.

>>> from os import system
>>> system
<built-in function system>
>>> del system
>>>
>>> exec "from %s import system" % "os"
>>> system
<built-in function system>
>>> del system
>>> 
>>> __import__("os", fromlist=["system"])
<module 'os' from '/usr/lib/python2.5/os.pyc'>
>>> system
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'system' is not defined

I mention this only to be pedantic, because I agree with your point that 
exec can introduce security issues, and be significantly slower.


-- 
Steven



More information about the Python-list mailing list