2

別のモジュールのコードに依存するサードパーティのモジュールを使用するとします。

# 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パッケージからすべての依存関係をインポートする可能性があるため、2番目のバリアントが好きですが、この方法には欠点がありますか?これは良い習慣ですか、それとも悪い習慣ですか?

ありがとう!

4

1 に答える 1

1

サードパーティのパッケージから関数/クラスをインポートすることは悪い習慣ではないと思います。いくつかの利点があるかもしれません(例:パッケージにモンキーパッチを適用したい場合、または何かが設定されていることを確認する必要がある場合正しく)。

さまざまなセットアップをサポートする必要がある場合もあります。APIについて考えてみましょうElementTree。これは、特定の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")

現在、さまざまなPythonインストールでも機能する実装がsomepackage含まれていることが保証されており、パッケージは抽象化として機能します。etree

于 2012-10-30T10:36:18.933 に答える