from spam import eggs, spam at runtime, how?

Fredrik Lundh fredrik at pythonware.com
Tue Dec 9 02:55:08 EST 2003


"Ganesan R" wrote:
>
> >     spam = __import__('spam.eggs')
> >     eggs = spam.eggs
>
> Is there a way to do this if I don't know about "eggs" beforehand. I have
> some code which needs to import a DB module dynamically. The module could be
> 'PyPgSQL.PgSQL' or 'sqlite'. Is there a sane way to do this without exec?

here's one way to do it:

    dbapi = __import__(dbname)
    for p in name.split(".")[1:]:
        dbapi = getattr(dbapi, p)

notes:

- when given a package, __import__ imports all components, but
returns a reference to the toplevel module).

- you may still need DB-specific code to connect to the database

</F>








More information about the Python-list mailing list