Help us understand the problem. What is going on with this article?

pickle.dumpしたオブジェクトを別のオブジェクト階層でpickle.loadすると死ぬ

More than 3 years have passed since last update.
|--b
|  |--unpickling.py
|--lib
|  |--__init__.py
|  |--__init__.pyc
|  |--class_a.py
|  |--class_a.pyc
|--pickling.py
|--unpickling.py
|--class_a.pkl
lib/class_a.py
class ClassA:
    pass
pickling.py
import pickle
from lib.class_a import ClassA

a = ClassA()

with open('class_a.pkl', 'w') as f:
    pickle.dump(a,f)
unpickling.py
# b/pickling.pyも同じ

import sys
import pickle

filepath = sys.argv[1]

with open(filepath, 'r') as f:
    a = pickle.load(f)

で、こうやると死ぬ

[~]> python pickling.py
[~]> cd b
[~/b]> python unpickling.py ../class_a.pkl
Traceback (most recent call last):
  File "unpickling.py", line 7, in <module>
    a = pickle.load(f)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1384, in load
    return Unpickler(file).load()
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 864, in load
    dispatch[key](self)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1075, in load_inst
    klass = self.find_class(module, name)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1130, in find_class
    __import__(module)
ImportError: No module named lib.class_a

こうやると生きる

[~]> python pickling.py
[~]> python unpickling.py ../class_a.pkl
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away