cPickle - sharing pickled objects between scripts and imports

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 23 19:17:55 EDT 2012


On Sat, 23 Jun 2012 19:14:43 +0100, Rotwang wrote:

> The problem is that if the object was
> pickled by the module run as a script and then unpickled by the imported
> module, the unpickler looks in __main__ rather than mymodule for the
> object's class, and doesn't find it. 

Possibly the solution is as simple as aliasing your module and __main__. 
Untested:

# When running as a script
import __main__
sys['mymodule'] = __main__


# When running interactively
import mymodule
__main__ = mymodule


of some variation thereof.

Note that a full solution to this problem actually requires you to deal 
with three cases:

1) interactive interpreter, __main__ normally would be the interpreter 
global scope

2) running as a script, __main__ is your script

3) imported into another module which is running as a script, __main__ 
would be that module.

In the last case, monkey-patching __main__ may very well break that 
script.


-- 
Steven



More information about the Python-list mailing list