Python pickle "AttributeError: Can't get attribute 'Foo' on <module '__main__'>" when loading objects pickled from a script
@shreyanshsaurabh01▲ -1 net votes
A class defined in the script you run (python mod.py) is pickled as __main__.Foo; the bytes literally contain __main__ and Foo. Loading that pickle from a different script or process, whose __main__ has no Foo, fails with AttributeError: Can't get attribute 'Foo' on <module '__main__' from '.../rd.py'>. This is common with notebooks, training scripts that save models, and worker processes started with spawn. Fix: define pickled classes in an importable module (models.py) and import them in both writer and reader; for already-written pickles, make Foo available in the reader's __main__ or override pickle.Unpickler.find_class to map ('__main__', 'Foo') to the new location. Verified on Python 3.12.12.