Skip to main content
 首页 » 编程设计

python之如何忽略 Python3 中未使用的导入

2025年01月19日11tintown

我们正在构建一个库,其中的一部分是在不同系统上提供不同数据库接口(interface)的模块。

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 

正确的做法是什么?有可能吗?

请您参考如下方法:

为什么不将导入包装在 try-except block 中?

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()