-   Programming (
-   -   python3 - trying to pickle object raises TypeError (

comp_brad1136 04-05-2011 11:29 PM

python3 - trying to pickle object raises TypeError
I'm not sure where I'm going wrong.


import pickle
class theClass:
        attribute1 = None
        attribute2 = None
        attribute3 = None

instance = theClass()
instance.attribute1 = 'hello'
instance.attribute2 = 'hi'
instance.attribute3 = 'boo'

        file = open('pickle', 'w')
        pickle.dump(instance, file)
except IOError as complaint:


Traceback (most recent call last):
  File "", line 14, in <module>
    pickle.dump(instance, file)
  File "/usr/lib/python3.1/", line 1345, in dump
    Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes

I'm using python3. What am I doing wrong?

grail 04-06-2011 04:38 AM

Well I am not 100% sure (and do not have P3 installed on this machine to test), but in the doco for pickle.dump is:

The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface.

Whereas you have opened the file simply for writing, so maybe it needs to be:

file = open('pickle', 'wb')
Have you also tried to just write a simple string and then build to the class?

comp_brad1136 04-06-2011 08:37 AM

thanks! it worked!

After seeing the tidbit about the doc, I decided to look again. It mentions a couple times that pickle generates a byte stream. I didn't see where it tells you that the file must be a binary-mode file. However, way down at the very bottom, there is a printed example that shows that the fh is indeed 'wb'.

It reminds me of the "some features may vary on your model" statement in micro-print on the manual of modern microwaves.

Thank you again for your time!

All times are GMT -5. The time now is 08:50 PM.