LoginSignup
11
5

More than 5 years have passed since last update.

[Python]関数内でのモジュールimportの是非

Last updated at Posted at 2018-06-25

結論

PEP的には非。ただし現場レベルでは採用することもある。

PEP8

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

ファイルの先頭でインポートすべしとの記述。

関数内でのモジュールインポートについては言及なし。

現場レベルの議論

インプット情報

https://stackoverflow.com/questions/3095071/in-python-what-happens-when-you-import-inside-of-a-function
https://stackoverflow.com/questions/1024049/is-it-pythonic-to-import-inside-functions/1024087

関数内でのモジュールインポートが採用される例

  • 循環参照の回避
  • 名前空間衝突の回避

  • パフォーマンス

    • ただし先頭インポートと比較して必ずしも優位ではなく、採用するなら実際に比較すべきとの意見あり
  • 複雑度の減少

    • ただしこれは応急対応であり、本来ならモジュール切り分け等で対処すべしという(解釈できる)意見あり
11
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5