LoginSignup
1
2

More than 3 years have passed since last update.

pythonで関数をpickleするときの注意点

Posted at

やった事

pythonの関数をpickleして復元できるかやってみました

結論

  • importしてるモジュールの関数は別モジュールから正しく呼べる
  • 同じモジュール内の関数は同名の関数が呼ばれる

実行した手順

  1. test1.pyとtest2.pyに同名のfunc()を書いておく
  2. test1.pyからfunc()とtest2.func()をpickleで保存する
  3. test1.py、test2.pyからpickleファイルを読んで実行

結果

test1.py
This is test1.func()
This is test2.func()
test2.py
This is test2.func()
This is test2.func()

上記のようにtest2.pyでは同名のfunc()を読んでしまいます。func()がtest2.pyにない場合は「NameError: name 'func' is not defined」でエラーになります。

なお、test1.pyでtest1.pyをimportして、test1.funcをpickle保存すれば正しく読み込めるようになります。

コード

以下の2つのファイルを同じディレクトリに置いてそれぞれ実行しました。

test1.py
import pickle
import test2


def save_pickle(obj, path):
    with open(path, mode='wb') as f:
        pickle.dump(obj, f)


def load_pickle(path):
    with open(path, mode='rb') as f:
        obj = pickle.load(f)
    return obj


def func():
    print('This is test1.func()')


def main():
    func()
    test2.func()

    path = 'test1_func.pickle'
    save_pickle(func, path)
    func_from_pickle = load_pickle(path)
    func_from_pickle()

    path = 'test2_func.pickle'
    save_pickle(test2.func, path)
    func_from_pickle = load_pickle(path)
    func_from_pickle()


if __name__ == '__main__':
    main()
test2.py
import pickle


def load_pickle(path):
    with open(path, mode='rb') as f:
        obj = pickle.load(f)
    return obj


def func():
    print('This is test2.func()')


def main():
    path = 'test1_func.pickle'
    func_from_pickle = load_pickle(path)
    func_from_pickle()

    path = 'test2_func.pickle'
    func_from_pickle = load_pickle(path)
    func_from_pickle()


if __name__ == '__main__':
    main()
1
2
0

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
1
2