What is the best way to do dynamic imports ?

Graham Dumpleton Graham.Dumpleton at gmail.com
Sun Dec 30 19:45:19 EST 2007


On Dec 31, 1:24 am, marcroy.ol... at gmail.com wrote:
> Hi list and python gurus :-)
>
> I'm playing with somemod_pythonand 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)
> And have to I check if the modul is already 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?
>
> Do anybody now a good howto or tutorial to this?
>
> Many thanks and hope you all have a happy new year :-)
>
> /marc

If using mod_python, you should use mod_python's own dynamic module
importer. See the documentation for mod_python.apache.import_module()
in:

  http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html

There is no need to use __import__ directly. By using mod_python's way
of doing things you can benefit from automatic module reloading
provided certain constraints met.

Graham



More information about the Python-list mailing list