[Tutor] cannot pickle instancemethod objects

Kent Johnson kent37 at tds.net
Tue Jun 19 12:27:15 CEST 2007


hok kakada wrote:
>>> Actually, I use the translate-toolkit from
>>> http://translate.sourceforge.net/snapshots/translate-toolkit-1.0.1rc1/

>>> I just found the problem that it is because of the LevenshteinComparer.
>>> Once I assign self.comparer = None, the I can dump the matcher
>>> successfully. However, I still don't understand what could be wrong with
>>> LevenshteinComparer.
>> I think the problem is this code in LevenshteinComparer.__init__():
>>
>>          if Levenshtein:
>>              self.distance = self.native_distance
>>          else:
>>              self.distance = self.python_distance
>>
>> which assigns an instance method to an instance attribute; this is the
>> instancemethod that can't be pickled.
> Ok...but how can we deal with it?

Either assign self.comparer = None before pickling, or define a 
__getstate__() method that returns a dict which doesn't include the 
comparer. Something like

def __getstate__(self):
   d = self.__dict__.copy()
   del d[comparer]
   return d

See http://docs.python.org/lib/pickle-inst.html

Kent


More information about the Tutor mailing list