我们正在构建一个库,其中一部分是在不同系统上提供不同数据库接口的模块。
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
我们希望跳过未使用的导入内容。例如,在具有MySQLdb
的系统上,我们将使用DbInterface1
,并且不应要求安装SQLAlchemy
。也就是说,在系统A上,我们会像这样使用它:
from ourlibrary.dbinterfaces import DbInterface1
...
显然,这不起作用:
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
我们假设将导入移动到使用它们的类中会起作用,因为库客户端不会导入它未使用的内容,但它仍然存在失败的依赖项。
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
这样做的正确方法是什么?它甚至可能吗?
答案 0 :(得分:1)
为什么不将导入包装在try-except块中?
try:
import MySQLdb
except ImportError:
pass
try:
import sqlalchemy
except ImportError:
pass
即使没有安装任何模块,也应允许运行脚本。
您可以修改上述方法以跟踪导入的模块是否存在,以验证某个类是否可以在某个系统上使用。
try:
import MySQLdb
except ImportError:
module_MySQLdb = False
else:
module_MySQLdb = True
然后,您可以将该信息存储在类变量中,并在实例化类之前进行检查。
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()
或者您可以使用字典(例如avaliable_modules = {'MySQLdb':module_MySQLdb}
)并将其与您的班级一起导入。
from ourlibrary.dbinterfaces import DbInterface1, avaliable_modules
if avaliable_modules['MySQLdb']:
dbm = DbInterface1()