Pickle Encoding Errors

Laszlo Nagy gandalf at shopzeus.com
Mon Sep 21 05:57:23 EDT 2009


> I'm running Python 2.5.4 on Debian Sid.
>
> If anybody understands the error please enlighten me.
>   

Very interesting! Here is a minimalist version:

import pickle
class PickleTest:
    def __init__(self):
        self.library={u"A": 1,u"B": 2,u"C": 3}
    def __del__(self):
        self.pickle()
    def pickle(self):
        pickle.dumps(self.library)
pt=PickleTest()

However, the exception is not thrown if dictionary keys are not 
unicodes. cPickle version is even more strange:

import cPickle
class PickleTest:
    def __init__(self):
        self.library={u"A": 1,u"B": 2,u"C": 3}
    def __del__(self):
        self.pickle()
    def pickle(self):
        cPickle.dumps(self.library)

pt=PickleTest()

Result:

Exception AttributeError: "'NoneType' object has no attribute 'dumps'" 
in <bound
 method PickleTest.__del__ of <__main__.PickleTest instance at 
0x00CC1F08>> ignored

Of course the error is gone if you do this:

if __name__ == "__main__":
    pt=PickleTest()
    del pt # No more references to object, will be destroyed before the 
main program starts exiting.

You should NOT write files from object destructors anyway. You can never 
know when an object willl be destroyed. The correct way to implement 
this is to put it in try - finally

pt=PickleTest()
try:
    do_something_with(pt)
finally:
    pt.pickle()

Best.

   Laszlo








More information about the Python-list mailing list