function to do dynamic import?

Peter Otten __peter__ at web.de
Wed Sep 12 05:37:15 EDT 2007


Am Wed, 12 Sep 2007 11:54:51 +1000 schrieb bambam:

> def gim():
>     exec "global gamel"
>     exec "import gamel"
> 
> Unfortunately, does not have the desired effect.
> Steve.

Both statements have to be part of a single exec:

def gim():
    modulename = "gamel" # determined at runtime
    exec "global %s; import %s" % (modulename, modulename)

It may work, but it is still a bad idea to create global variables with a
name not known until runtime.

Peter



More information about the Python-list mailing list