Pickle errors with Python 3
Question: I'm converting some code from Python **2** to Python **3** , and I have hard
time with a pickle problem! Here is a simple example of what I'm trying to do:

    
    
    class test(str):
    
            def __new__(self, value, a):
                    return (str.__new__(self, value))
    
            def __init__(self, value, a):
                    self.a = a
    
    
    if __name__ == '__main__':
            import pickle
            t = test("abs", 5)
            print (t)
            print( t.a)
    
            wdfh = open("./test.dump", "wb")
            pickle.dump(t, wdfh)
            wdfh.close()
    
            awfh = open("./test.dump", "rb")
            newt = pickle.load(awfh)
            awfh.close()
    
            print (t)
            print (newt.a)
    

This works just fine with Python 2 but I have the following error with Python
3:

> Traceback (most recent call last):
>
> File "test.py", line 21, in
>  
>  
>     newt = pickle.load(awfh)
>  
>
> TypeError: **new**() takes exactly 3 arguments (2 given)

I do not understand what is the difference, any idea?


Answer: The problem here is that your code only works with protocol 0 or 1. By
default, Python 2 uses protocol 0, whereas Python 3 uses protocol 3.

For protocol 2 and above you can't have additional arguments to the `__new__`
method unless you implement the `__getnewargs__` method.

In this case simply adding:

    
    
        def __getnewargs__(self):
            return (str(self),self.a)
    

should do the trick.

Or you could stick with protocol 0 or 1 and change the dump call:

    
    
        pickle.dump(t, wdfh, 0)
    

