AttributeError: Can't get attribute '' on <module '__main__'> pickle 1

AttributeError: Can’t get attribute ” on pickle

# Import the class that pickled the file in question into the object
# that does the unpickling

import pickle

def save_document(doc):

    from class_def import Document

    write_file = open(file_path, 'wb')
    pickle.dump(doc, write_file)

def load_document(file_path):
    from class_def import Document

    doc_file = open(file_path, 'rb')
    return pickle.load(doc_file)
if __name__ == '__main__':
    doc = Document()
if __name__ == '__main__':
    from class_def import Document 
    # ^ so that it is using the Document class defined under the class_def module
    doc = Document()

Here is what the above code is Doing:
1. The Document class is defined in the class_def module.
2. The save_document() function is defined in the utils module.
3. The main program is in the __main__ module.
4. The main program creates a Document object and passes it to the save_document() function.
5. The save_document() function opens a file and uses pickle.dump() to write the Document object to the file.
6. The pickle module needs to know the Document class in order to pickle the object.
7. The pickle module looks for the Document class in the __main__ module.
8. The pickle module doesn’t find the Document class in the __main__ module.
9. The pickle module raises an exception.

The solution is to import the Document class into the __main__ module.

Similar Posts