Created
November 15, 2018 19:13
-
-
Save krzentner/abfcd00e3cc6e54d5ccf1a0b57eb5364 to your computer and use it in GitHub Desktop.
A picklable type that calls a function when unpickled.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PickledCall: | |
def __new__(cls, to_call, args=(), kwargs=None, __pickle_target=None): | |
if __pickle_target is None: | |
result = super(cls, PickledCall).__new__(cls) | |
result.to_call = to_call | |
result.args = args | |
result.kwargs = kwargs or {} | |
return result | |
else: | |
return __pickle_target(*args, **kwargs) | |
def __getnewargs__(self): | |
return (None, self.args, self.kwargs, self.to_call) | |
import pickle | |
class Gold: | |
def __init__(self, item): | |
self.item = item | |
def announce(self): | |
print(f'Golden {self.item}!') | |
pickled_call = pickle.dumps(PickledCall(Gold, ('crown',))) | |
print(pickled_call) | |
result = pickle.loads(pickled_call) | |
result.announce() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment