Unpickling Exception-type objects

David McClosky dmcc.usenet at gmail.com
Thu Oct 2 14:18:24 EDT 2008


Hi everyone,

I'm stumped over what is probably (hopefully?) a very simple problem.
Suppose I have a class that multiply inherits from two classes, call
them A and B.  A inherits from a class that takes any number of
arguments in __init__.  B does not inherit from anything and requires
one argument.  For reasons I don't understand, if A inherits from
Exception, unpickling fails due to a TypeError:

   __init__() takes exactly 2 arguments (1 given)

If A in inherits from a class that also takes any number of arguments,
the TypeError vanishes.  To illustrate:

# ------------------------------------
import pickle

class Parent:
    def __init__(self, *optional):
        self.optional = optional

for Base in (Parent, Exception):
    print "Base =", Base
    print

    class A(Base):
        pass

    class B:
        def __init__(self, required):
            self.required = required

    class Child(A, B):
        def __init__(self, *args):
            A.__init__(self)
            B.__init__(self, *args)

    def test_dump(obj):
        print 'obj:', type(obj), obj.__dict__
        pickle.dump(obj, file('/tmp/pickle.p', 'w'), -1)
        try:
            loaded = pickle.load(file('/tmp/pickle.p'))
            print 'loaded', type(loaded), loaded.__dict__
        except TypeError, e:
            print 'failed to load', e
        print

    test_dump(Child(7))
# ------------------------------------

I get the following output in python 2.5.2:

# ------------------------------------
Base = __main__.Parent

obj: <type 'instance'> {'required': 7, 'optional': ()}
loaded <type 'instance'> {'required': 7, 'optional': ()}

Base = <type 'exceptions.Exception'>

obj: <class '__main__.Child'> {'required': 7}
failed to load __init__() takes exactly 2 arguments (1 given)
# ------------------------------------

Any help on this would be greatly appreciated.

Thanks,
David



More information about the Python-list mailing list