conditional importing
Scott Hathaway
slhath at charter.net
Tue Jul 30 23:54:09 EDT 2002
Thanks to both of you guys for your advice. I will release the class when
it is done. Whether it will be useful to anyone but me remains to be seen.
:)
Scott
"Steve Holden" <sholden at holdenweb.com> wrote in message
news:0ad19.92805$724.68398 at atlpnn01.usenetserver.com...
> "Gerhard Häring" <gerhard.haering at gmx.de> wrote in message
> news:mailman.1027907323.21253.python-list at python.org...
> > * 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.
> >
>
> My preferred technique (when all modules obey the DB API sufficiently for
my
> needs) is:
>
> if dbtype == 'odbc':
> import mx.ODBC.Windows as db
> else:
> import MySQLdb as db
>
> conn = db.open(...)
>
> The real problem at present appears to be the various different modules'
> insistence on using different paramstyles - in the case above, mxODBC
> expects a "?" for a parameter substitution, while MySQLdb expects a "%s".
>
> something-i-need-to-work-on-ly y'rs - steve
> -----------------------------------------------------------------------
> Steve Holden http://www.holdenweb.com/
> Python Web Programming http://pydish.holdenweb.com/pwp/
> -----------------------------------------------------------------------
>
>
>
>
>
More information about the Python-list
mailing list