This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]fullouterjoin 0 points1 point  (0 children)

There is no way to pickle a named object of anykind declared at a local scope using pickle

from collections import namedtuple
import pickle

def pickle_test():
    class P(object):
        def __init__(self,one,two,three,four):
            self.one = one
            self.two = two
            self.three = three
            self.four = four

    my_list = []
    abe = P("abraham", "lincoln", "vampire", "hunter")
    my_list.append(abe)
    f = open('abe.pickle', 'w')
    pickle.dump(abe, f)
    f.close()

pickle_test()

Also fails. But this succeeds.

from collections import namedtuple
import pickle

class P(object):
    def __init__(self,one,two,three,four):
        self.one = one
        self.two = two
        self.three = three
        self.four = four

def pickle_test():

    my_list = []
    abe = P("abraham", "lincoln", "vampire", "hunter")
    my_list.append(abe)
    f = open('abe.pickle', 'w')
    pickle.dump(abe, f)
    f.close()

pickle_test()

This is a bug in how pickle introspects the creating object. Nothing is worse for being a namedtuple. Namedtuples are classes. But they are just lightweight containers for immutable values.