Skip to main content
 首页 » 编程设计

Python 依赖导入

2025年05月04日10mayingbao

假设我使用一些依赖于另一个代码的第三方模块:

# third_party.py 
from package import fun, A 
 
class B(A): 
    def foo(self): 
        self.do() 
        self.some() 
        self.stuff() 
        return fun(self) 

然后我想在我的代码中继承这个类来改变功能:

# my_code.py 
 
from third_party import B 
 
# from third_party import fun? 
# from package import fun? 
 
class C(B): 
    def foo(self): 
        return fun(self) 

哪个更好:from package import fun 或 from third_party import fun 来访问 fun?

我喜欢第二种变体,因为我可能不关心实际路径并从 third_party 包中导入所有依赖项,但是这种方式有什么缺点吗?这是好事还是坏事?

谢谢!

请您参考如下方法:

我不认为从第三方包中导入函数/类是一种不好的做法,它甚至可能有一些好处(例如:如果你想猴子修补一个包,或者需要确定一些东西设置正确)。

甚至可能需要支持各种设置。考虑 ElementTree API,它在特定 Python 版本上的可用性不同,甚至可能由第三方库提供(取自 here ):

# somepackage.py 
 
try: 
  from lxml import etree 
  print("running with lxml.etree") 
except ImportError: 
  try: 
    # Python 2.5 
    import xml.etree.cElementTree as etree 
    print("running with cElementTree on Python 2.5+") 
  except ImportError: 
    try: 
      # Python 2.5 
      import xml.etree.ElementTree as etree 
      print("running with ElementTree on Python 2.5+") 
    except ImportError: 
      try: 
        # normal cElementTree install 
        import cElementTree as etree 
        print("running with cElementTree") 
      except ImportError: 
        try: 
          # normal ElementTree install 
          import elementtree.ElementTree as etree 
          print("running with ElementTree") 
        except ImportError: 
          print("Failed to import ElementTree from any known place") 

现在,保证 somepackage 包含一个有效的 etree 实现,即使在不同的 Python 安装上也是如此,并且您的包作为抽象。