conditional importing

Gerhard Häring gerhard.haering at gmx.de
Sun Jul 28 21:47:30 EDT 2002


* Scott Hathaway <slhath at charter.net> [2002-07-28 20:29 -0500]:
> How can I do a conditional import?  I am creating a database wrapper class
> that is similar to adodb in PHP.
> I have the following class:
> 
> >from mx.ODBC import Windows as db1
> import MySQLdb as db2

Better use something like:

module_name = "MySQLdb"
try:
    dbmodule = __import__(module_name)
except ImportError, reason:
    # error handling here

def open_connection(*args, **kwargs):
    return dbmodule.connect(*args, **kwargs)

Unfortunately, the arguments for the connect method aren't standardized.
But at least some modules allow for a single connection string where the
arguments (host, user, passwd, ...) are separated by colons.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




More information about the Python-list mailing list