22

I am trying to write some result on to pickle file as below:

raw_X = (self.token_ques(text) for text in training_data)
with open('/root/Desktop/classifier_result.pkl', 'wb') as handle:
    pickle.dump(raw_X, handle)

Error:

    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle generator objects

Any help would be much appreciable.

2

2 Answers 2

11

Don't use a generator expression when you want to pickle data. Use a list comprehension instead, or call list() on the generator to capture all generated elements for pickling.

For example, the following works just fine:

raw_X = [self.token_ques(text) for text in training_data]
with open('/root/Desktop/classifier_result.pkl', 'wb') as handle:
    pickle.dump(raw_X, handle)

as does:

raw_X = (self.token_ques(text) for text in training_data)
with open('/root/Desktop/classifier_result.pkl', 'wb') as handle:
    pickle.dump(list(raw_X), handle)
6
  • @nlper: so what does self.token_ques(text) return? Is that a generator object too perhaps?
    – Martijn Pieters
    Mar 10, 2015 at 12:42
  • yeah, when I printed type it gave <type 'generator'>
    – nlper
    Mar 10, 2015 at 12:51
  • So apply list() to each return value; raw_X = [list(self.token_ques(text)) for text in training_data]
    – Martijn Pieters
    Mar 10, 2015 at 12:53
  • okay, but when I load it back, how can I put it in original form
    – nlper
    Mar 10, 2015 at 13:00
  • 1
    Define original form. You can still iterate over the unpickled lists; they are iterables just like the generators produced iterables.
    – Martijn Pieters
    Mar 10, 2015 at 13:01
4
raw_X = (self.token_ques(text) for text in training_data)

This is a generator. As the error says, we cannot pickle generators. Use this instead.

raw_X=[]
for text in data:
  raw_X.append(self.token_ques(text))
raw_X=tuple(raw_X)

And pickle raw_X then.


Edit

This works for me

import pickle

raw_X=[]
data=[1,2,3,4,5,6,2,0]
for text in data:
    raw_X.append(str(text))

print pickle.dumps(raw_X)

I'm using str() instead of your function and dumps() instead of dump().

2
  • 1
    Why turning it into a tuple? If a tuple was the goal, just use tuple(self.token_ques(text) for text in training_data).
    – Martijn Pieters
    Mar 10, 2015 at 12:42
  • Using append is much slower than list comprehension. Feb 25, 2022 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.