-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
43 additions
and
3 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
|
||
import pickle | ||
from collections import namedtuple | ||
|
||
MemoRecord = namedtuple("MemoRecord", "key, task") | ||
|
||
class MyPickler(pickle.Pickler): | ||
|
||
def persistent_id(self, obj): | ||
# Instead of pickling MemoRecord as a regular class instance, we emit a | ||
# persistent ID. | ||
if isinstance(obj, MemoRecord): | ||
# Here, our persistent ID is simply a tuple, containing a tag and a | ||
# key, which refers to a specific record in the database. | ||
print('persistent_id set') | ||
return ("MemoRecord", obj.key) | ||
else: | ||
# If obj does not have a persistent ID, return None. This means obj | ||
# needs to be pickled as usual. | ||
return None | ||
|
||
def main(): | ||
memo = MemoRecord("aa", "bb") | ||
filehandler = open(b"persistent_id.pkl", "wb") | ||
MyPickler(filehandler).dump(memo) | ||
|
||
if __name__ == '__main__': | ||
main() |
This file contains 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