親ディレクトリにあるライブラリを使うために、実行ファイルからの相対パスを使ってimportするコードをたまに見かける。
bin/hoge.py
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import library
def hoge():
library.echo('hoge')
if __name__ == '__main__':
hoge()
$ python bin/hoge.py
hoge
このコードはimport library
の部分でWARNINGが出る。
Python | PEP 8 coding style violation
これは、親ディレクトリに実行ファイルを作り、python-fire経由で子の関数を見るようにすると綺麗に解決できる。
run.py
import fire
import bin
if __name__ == '__main__':
fire.Fire(bin)
bin/__init__.py
from .fuga import fuga
from .hoge import hoge
bin/fuga.py
import library
def fuga():
library.echo('fuga')
$ python run.py fuga
fuga
python-fireは、いいぞ。