Reputation: 2477
We are building a library, and part of that is a module that provides different database interfaces on different systems.
class DbInterface1(object):
"""Uses MySQLdb, and is useful on system A."""
def __init__():
pass
class DbInterface2(object):
"""Uses SQLAlchemy, and is useful on system B."""
def __init__():
pass
We'd like to skip imports that aren't used. For instance, on a system that has MySQLdb
, we will use DbInterface1
and should not require SQLAlchemy
to be installed. That is, on system A, we would use it like this:
from ourlibrary.dbinterfaces import DbInterface1
...
Obviously, this will not work:
import MySQLdb
import sqlalchemy
class DbInterface1(object):
"""Uses MySQLdb, and is useful on system A."""
def __init__():
pass
class DbInterface2(object):
"""Uses SQLAlchemy, and is useful on system B."""
def __init__():
pass
We assumed that moving the imports into the classes that use them would work, since the library client won't import something it's not using, but it still has failed dependencies.
class DbInterface1(object):
"""Uses MySQLdb, and is useful on system A."""
import MySQLdb
def __init__():
pass
class DbInterface2(object):
"""Uses SQLAlchemy, and is useful on system B."""
import sqlalchemy
def __init__():
pass
What is the correct way to do this? Is it even possible?
Upvotes: 3
Views: 2096
Reputation: 15376
Why don't you wrap your imports in a try-except block?
try:
import MySQLdb
except ImportError:
pass
try:
import sqlalchemy
except ImportError:
pass
This should allow to run your script even if neither module is installed.
You can modify the above method to track if the imported modules exist in order to verify if a class can be used on a certain system.
try:
import MySQLdb
except ImportError:
module_MySQLdb = False
else:
module_MySQLdb = True
Then you could store that information in a class variable and check it before instantiating the class.
class DbInterface1(object):
"""Uses MySQLdb, and is useful on system A."""
is_avaliable = module_MySQLdb
def __init__(self):
pass
if DbInterface1.is_avaliable:
dbm = DbInterface1()
Or you could use a dictionary (eg avaliable_modules = {'MySQLdb':module_MySQLdb}
) and import it along with your class.
from ourlibrary.dbinterfaces import DbInterface1, avaliable_modules
if avaliable_modules['MySQLdb']:
dbm = DbInterface1()
Upvotes: 1