简体   繁体   中英

Why can't we pickle an instance of InteractiveInterpreter?

An attempt to pickle an instance of InteractiveInterpreter results in the following error


  File "", line 1, in 
  File "/usr/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 725, in save_inst
    save(stuff)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle ellipsis objects

which is strange InteractiveInterpreter isn't an Ellipsis object according to what I know. Any reasons? And is there any alternate way to pickle InteractiveInterpreter Object?

By some reason Ellipsis cannot be pickled in the stock pickler. But you can use persistent id functionality to achieve this.

First, instead of pickle.dump and pickle.load you should use Pickler and Unpickler objects.

Second, you must define two functions - first will take an object and return its id (or None for regular pickling) and second will convert this id to object on unpickling.

Working example:

import cPickle as pickle

def dump_ellipsis(obj):
    if obj is Ellipsis:
        return "Ellipsis"

def load_ellipsis(persid):
    if persid == "Ellipsis":
        return Ellipsis


storage = open("tmp.pkl", "w")

pickler = pickle.Pickler(storage)

pickler.persistent_id = dump_ellipsis

pickler.dump(Ellipsis)

storage.close()

storage = open("tmp.pkl")

unpickler = pickle.Unpickler(storage)

unpickler.persistent_load = load_ellipsis

print unpickler.load()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM