|
From: Jack K. <kj...@gm...> - 2006-11-07 15:41:46
|
Hi all,
sorry, I couldn't wait for ConfigObj to be pickle-able (for pickle protocol
2). So, after some investigation here are some changes
that I've found necessary:
def __newobj__(cls, *args):
"""Required by Section.__reduce__ for using Pickle protocol 2 with
newstyle class. """
return cls.__new__(cls, *args)
class Section(dict):
def __reduce__(self):
d = {}
d.update(self.__dict__)
d['parent'] = d['main'] = None # remove recursive references
d['sections'] = d['scalars'] = [] # must be empty since we are
going to Section.__setitem__
return __newobj__, (self.__class__, d), self.__dict__, None,
self.iteritems()
def __new__(cls, *args, **kws):
"""Partially initialize the object so that it's safe to call
Section.__setitem__ before
the full states are restored during unpickling.
"""
inst = super(Section, cls).__new__(cls)
# Check the args to make sure it's called by __newobj__ before
updating
# there's probably a better way to verify this....
if len(args) == 1 and isinstance(args[0], dict):
d = args[0]
try:
if d['parent'] == d['main'] == None:
inst.__dict__.update(d)
except:
pass
return inst
then we also need to change just one line in Section.__setitem__:
the line where it says "if not self.main.stringify:", change it to "if
self.main and not self.main.stringify:" since if we are unpickling
self.main will be None, plus there's no need to check the value during
unpickling anyway.
I did some tests on a my configuration, it seems to work. But anyway, the
basic idea I think is that we need to have some states
restored so that during unpickling Section.__setitem__ can rebuild the
section tree structure, and then we complete the unpickling by restoring
the the original states.
Thanks,
Jack
|