I am trying to use pickle to transfer python objects over the wire between 2 servers. I created a simple class, that subclasses dict
and I am trying to use pickle for the marshalling:
def value_is_not_none(value):
return value is not None
class CustomDict(dict):
def __init__(self, cond=lambda x: x is not None):
super().__init__()
self.cond = cond
def __setitem__(self, key, value):
if self.cond(value):
dict.__setitem__(self, key, value)
I first tried to use pickle
for the marshalling, but when I un-marshalled I received an error related to the lambda
expression.
Then I tried to do the marshalling with dill
but it seemed the __init__
was not called.
Then I tried again with pickle
, but I passed the value_is_not_none()
function as the cond
parameter - again the __init__()
does not seemed to be invoked and the un-marshalling failed on the __setitem__()
(cond
is None
).
Why is that? what am I missing here?
If I try to run the following code:
obj = CustomDict(cond=value_is_not_none)
obj['hello'] = ['world']
payload = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
obj2 = pickle.loads(payload)
it fails with
AttributeError: 'CustomDict' object has no attribute 'cond'
This is a different question than: Python, cPickle, pickling lambda functions
as I tried using dill
with lambda
and it failed to work, and I also tried passing a function and it also failed.