Pickling a dictionary

Devashish Tyagi devashishrocker at gmail.com
Wed Nov 7 12:40:26 EST 2012


On Wednesday, 7 November 2012 21:57:05 UTC+5:30, Peter Otten  wrote:
> Devashish Tyagi wrote:
> 
> 
> 
> > So I want to store the current state of a InteractiveInterpreter Object in
> 
> > database. In order to achieve this I tried this
> 
> > 
> 
> > obj = InteractiveInterpreter()
> 
> > local = obj.locals()
> 
> > pickle.dump(local, open('obj.dump','rw'))
> 
> 
> 
> Assuming InteractiveInterpreter is imported from the code module the above 
> 
> will fail with a TypeError. Please copy-and paste code snippets to avoid 
> 
> guessing games.

Here is the code

from code import InteractiveInterpreter
import StringIO
import pickle

src = StringIO.StringIO()
inter = InteractiveInterpreter()
inter.runcode('a = 5')
local = inter.locals

pickle.dump(local,open('obj.dump','wb'))

Here is the error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/pickle.py", line 1370, in dump
    Pickler(file, protocol).dump(obj)
  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 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


> 
> 
> 
> > But I received an error say
> 
> > TypeError: can't pickle ellipsis objects
> 
> > 
> 
> > From what I understand this shouldn't occur as local is a dictionary. Any
> 
> > particular reason for this behaviour?
> 
> 
> 
> For a dict to be pickled all its keys and values have to be pickled, too.



More information about the Python-list mailing list