cPickle - sharing pickled objects between scripts and imports

Rotwang sg552 at hotmail.co.uk
Mon Jun 25 10:48:54 EDT 2012


On 24/06/2012 00:17, Steven D'Aprano wrote:
> 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__

??? What is "sys" here?


> # 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.

I had not thought of that.


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

My original solution will also cause problems in this case. Thanks.

-- 
Hate music? Then you'll hate this:

http://tinyurl.com/psymix



More information about the Python-list mailing list