Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot unpickle pickled object [duplicate]

Running Python 3.4.3 on linux.

import pickle
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
pickled = pickle.dumps(context)
unpickled = pickle.loads(pickled)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    unpickled = pickle.loads(pickled)
TypeError: __new__() missing 1 required positional argument: 'protocol'

I don't do much pickling, so forgive me if this is well know.

I had a bit of a look around the only I found this about pickle in the What's new In Python 3.4 which suggests this should work. Other than that just issues pickling between different python versions.

I also tried setting pickle.HIGHEST_PROTOCOL but this didn't help either.

(BTW I've already worked around this issue but I'm curious why it does not work.)

like image 560
Maxwell Talbot Avatar asked Sep 06 '26 02:09

Maxwell Talbot


1 Answers

Classes that take extra arguments to __new__ need to provide a __getnewargs__ method to tell pickle what the extra arguments are.

You can monkey-patch SSLProtocol to add a __getnewargs__ method:

ssl.SSLContext.__getnewargs__ = lambda self: (self.protocol,)

The new feature of pickle in Python 3.4 is that it also supports a __getnewargs_ex__ method that can supply keyword arguments for __new__; but classes still need to provide __getnewargs__ and/or __getnewargs_ex__ themselves.

like image 141
ecatmur Avatar answered Sep 07 '26 14:09

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!