2

次のパッケージがあるとします。

testpackage
    __init__.py
    testmod.py
    testmod2.py

の内容__init__.py

from . import testmod
from . import testmod2

の内容testmod.py

# relative import without conditional logic, breaks when run directly
from . import testmod2
...
if __name__ == '__main__':
    # do my module testing here
    # this code will never execute since the relative import 
    # always throws an error when run directly

の内容testmod2.py

if __name__ == 'testpackage.testmod2':
    from . import testmod
else:
    import testmod
...
if __name__ == '__main__':
    # test code here, will execute when the file is run directly
    # due to conditional imports

これは悪いですか?もっと良い方法はありますか?

4

1 に答える 1

1

それは間違いなく将来のメンテナンスの頭痛の種になるでしょう. 条件付きインポートだけでなく...さらに、条件付きインポートを行う必要がある理由つまりtestpackage/testmod2.py、メインスクリプトとして実行すると、の最初のエントリsys.path./testpackageではなく になり、パッケージとして.の testpackage の存在そのものが失われます。あちらへ。

代わりに、testmod2 を 経由python -m testpackage.testmod2で実行し、外部から実行することをお勧めしtestpackageます。testpackage.testmod2は引き続き として表示されますが、常にパッケージである__main__ため、条件付きインポートは常に機能します。testpackage

問題は、 Python 2.5 以降-mが必要なことです。

于 2011-08-25T03:25:13.597 に答える