writing pickle function

Gerard Flanagan grflanagan at gmail.com
Fri Jan 23 20:10:39 CET 2009

On Jan 23, 2:48 pm, perfr... at gmail.com wrote:
> hello,
> i am using nested defaultdict from collections and i would like to
> write it as a pickle object to a file. when i try:
> from collections import defaultdict
> x = defaultdict(lambda: defaultdict(list))
> and then try to write to a pickle file, it says:
> TypeError: can't pickle function objects
> is there a way around this? it's simply a dictionary that i want to
> write to file.. this works no problems with ordinary dicts.
> thank you.

One way via a subclass:

(from memory)

class MyCollection(defaultdict):

    def __init__(self):
        defaultdict.__init__(self, list)

    def __reduce__(self):
        return (MyCollection, (), None, None, self.iteritems())

and if you are so inclined (nothing to do with pickling):

    __setattr__ = defaultdict.__setitem__
    __getattr__ = defaultdict.__getitem__


More information about the Python-list mailing list