LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   python3 - trying to pickle object raises TypeError (http://www.linuxquestions.org/questions/programming-9/python3-trying-to-pickle-object-raises-typeerror-873236/)

comp_brad1136 04-05-2011 10:29 PM

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

Code:

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

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

try:
        file = open('pickle', 'w')
        pickle.dump(instance, file)
        file.close()
except IOError as complaint:
        print('darn!')
        print(complaint)

generates:
Code:

Traceback (most recent call last):
  File "class.py", line 14, in <module>
    pickle.dump(instance, file)
  File "/usr/lib/python3.1/pickle.py", 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 03: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:
Code:

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 07: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!

http://docs.python.org/release/3.1.3....html#examples


All times are GMT -5. The time now is 03:19 AM.