Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python依赖项导入_Python - Fatal编程技术网

Python依赖项导入

Python依赖项导入,python,Python,假设我使用的第三方模块依赖于另一个模块的代码: # 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 # fr

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

# 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)
更好的方法是:
从package import fun
从第三方import fun
访问
fun

我喜欢第二个变体,因为我可能不需要考虑实际路径,也不需要从第三方导入所有依赖项,但这种方式有任何缺点吗?这是好的还是坏的做法


谢谢

我不认为从第三方软件包导入函数/类是一种不好的做法,它甚至可能有一些好处(例如:如果您想对软件包进行修补,或者需要确保某些设置正确)

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

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

# 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")