What is the best way to do dynamic imports ?

Benjamin musiccomposition at gmail.com
Sun Dec 30 09:45:10 EST 2007


On Dec 30, 8:24 am, marcroy.ol... at gmail.com wrote:
> Hi list and python gurus :-)
>
> 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
The correct way to do this is use the __import__ function. It takes
the string name of the module you want to import and returns the
module.
new_mod = __import__(some_modulename)
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc)
Well, it's generally frowned on to use exec and eval.
> And have to I check if the modul is already loaded?
sys.modules is a list of all imported modules, but python won't import
a module if it's already been loaded.
>
> 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?
If you just have the string name of a class, you have to use eval or
exec:
newclass = eval(classname)

However, if you have the class object, you can just instantiate that:
class LargeClass:
    def meth(): pass
some_class = LargeClass
new_class = some_class()
some_class.meth()
>
> Do anybody now a good howto or tutorial to this?
>
> Many thanks and hope you all have a happy new year :-)
You, too!
>
> /marc




More information about the Python-list mailing list