Infinite recursion in __reduce__ when calling original base class reduce, why?

Irmen de Jong irmen.NOSPAM at xs4all.nl
Mon Jun 13 15:50:00 EDT 2011


Hi,

I'm having a rather obscure problem with my custom __reduce__ function. I can't use
__getstate__ to customize the pickling of my class because I want to change the actual
type that is put into the pickle stream. So I started experimenting with __reduce__, but
am running into some trouble.

I've pasted my test code below. It works fine if 'substitute' is True, but as soon as it
is set to False, it is supposed to call the original __reduce__ method of the base
class. However, that seems to crash because of infinite recursion on Jython and
IronPython and I don't know why. It works fine in CPython and Pypy.

I wonder if my understanding of __reduce__ is wrong, or that I've hit a bug in
IronPython and Jython?  Do I need to do something with __reduce_ex__ as well?

Any help is very much appreciated.

Irmen de Jong



# ironpython / jython __reduce__ recursion problem test program

import pickle

class Substitute(object):
    def __init__(self, name):
        self.name=name
    def getname(self):
        return self.name

class TestClass(object):
    def __init__(self, name):
        self.name=name
        self.substitute=True
    def getname(self):
        return self.name
    def __reduce__(self):
        if self.substitute:
            return Substitute, ("SUBSTITUTED:"+self.name,)
        else:
            # call the original __reduce__ from the base class
            return super(TestClass, self).__reduce__()  #  crashes on ironpython/jython

obj=TestClass("janet")

s=pickle.dumps(obj)
d=pickle.loads(s)
print(d)
print(d.getname())

# now disable the substitution and try again
obj.substitute=False
s=pickle.dumps(obj)
d=pickle.loads(s)
print(d)
print(d.getname())



More information about the Python-list mailing list