Loading a module by expanding a string variable?

Fredrik Lundh effbot at telia.com
Thu Oct 26 17:21:41 EDT 2000


Joakim wrote:
> I have written two modules Mod1 and Mod2, and then I want load either
> Mod1 or Mod2 - depending on the value of a string variable.
>
> Example script:
>
>    #!/usr/local/bin/python
>    module = "Mod1"
>    from module import *

if you insist on using "from import" and don't have too many
modules to chose from, a good old if statement is probably
your best choice:

if module == "Mod1":
    from Mod1 import *
else:
    from Mod2 import *

:::

if you trust whoever sets the module variable, and don't mind
compiling code on the fly, you can also use exec:

    exec "from %s import *" % module

(if you don't trust the source, consider what happens if module
is set to e.g "os import *; system('rm -rf $HOME') #")

:::

a third alternative is __import__; see the docs for details.

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list