What is the best way to do dynamic imports ?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Dec 30 09:57:26 EST 2007


En Sun, 30 Dec 2007 12:24:53 -0200, <marcroy.olsen at gmail.com> escribi�:

> I'm playing with some mod_python and web development. And in me code I
> need to do som dynamic imports.
> Right now I just do a:
>
> exec 'import '+some_modulename
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc)

Use __import__, specially if some_modulename comes from the outside.
What if some_modulename contains "modulename\nsome_nasty_function_call()"

> And have to I check if the modul is already loaded?

Not needed; the standard import machinery already does that.

> Another thing is how to call my dynamic imported moduls.
> Now I use exec (as with my modules), like this:
>
> exec 'newclass = '+classname+'()'
> newclass.somefunction()
>
> Again it seems to easy. Is there a better/proper way to do it?

Use getattr to obtain the desired class from the containing module, then  
use it as any other class:
the_module = __import__(some_modulename)
the_class = getattr(the_module, classname)
o = the_class()
o.somefunction()

Never use exec/eval and friends - and never ever use them in a web  
application!

> Do anybody now a good howto or tutorial to this?

No... what do you want covered?

> Many thanks and hope you all have a happy new year :-)

Thanks, and a happy new year for you too!

-- 
Gabriel Genellina




More information about the Python-list mailing list