Possible to import a module whose name is contained in a variable?

Heiko Wundram modelnine at ceosg.de
Mon Mar 7 11:08:20 CET 2005

On Monday 07 March 2005 11:52, Claudio Grondi wrote:
> I try to avoid using any of the
> __xxxx__() functions if possible
> (considering this a good
> programming style).

This is never good style, at least in the case of exec. exec is evil.

What works (beware that the below code is nevertheless untested and might 
contain little warts) and is the "usual" and clean way to go:

### libinfo/__init__.py

# Empty.

### libinfo/Module1.py

def libinfo():
    return "I am module1."


### libinfo/Module2.py

def libinfo():
    return "I am module2."


### Importer.py

modules = {}

def load_modules(to_load=["module1","module2"]):
    global modules, CFLAGS

    for mod in to_load:
            modules[mod] = getattr(__import__("libinfo.%s" % mod),mod)
        except ImportError:
            print "Could not load %s." % mod
        print "Module: %s (%r)." % (mod,modules[mod])
        print "Modules libinfo: %r." % modules[mod].libinfo()
        CFLAGS += modules[mod].CFLAGS

    print "Total CFLAGS: %s." % CFLAGS

if __name__ == "__main__":
    print "Module container: %s." % modules

### End Importer.py


--- Heiko.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050307/b1fc98c9/attachment.pgp>

More information about the Python-list mailing list