dynamic module import?

alex23 wuwei23 at gmail.com
Sat Jan 17 05:36:50 CET 2009


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:

$ /usr/lib/python2.5/timeit.py -n 100000 'from os import system'
100000 loops, best of 3: 2.12 usec per loop

$ /usr/lib/python2.5/timeit.py -n 100000 '__import__("os", fromlist=
["system"])'
100000 loops, best of 3: 2.72 usec per loop

$ /usr/lib/python2.5/timeit.py -n 100000 'm = "os"; exec("from " + m +
" import system")'
100000 loops, best of 3: 25.1 usec per loop



More information about the Python-list mailing list