From 7f1eb2b44310f3403cbb777e45941a8f891572dc Mon Sep 17 00:00:00 2001 From: "Azalea (on HyDEV-Daisy)" Date: Mon, 11 Apr 2022 01:43:05 -0400 Subject: [PATCH] [+] Pickle utils --- hypy_utils/__init__.py | 3 +-- hypy_utils/serializer.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 hypy_utils/serializer.py diff --git a/hypy_utils/__init__.py b/hypy_utils/__init__.py index 3191493..b7393dc 100644 --- a/hypy_utils/__init__.py +++ b/hypy_utils/__init__.py @@ -1,7 +1,6 @@ from __future__ import annotations - -__version__ = "1.0.6" +__version__ = "1.0.7" import dataclasses import hashlib diff --git a/hypy_utils/serializer.py b/hypy_utils/serializer.py new file mode 100644 index 0000000..736ba28 --- /dev/null +++ b/hypy_utils/serializer.py @@ -0,0 +1,23 @@ +import io +import pickle + + +def pickle_encode(obj: any, protocol=None, fix_imports=True) -> bytes: + """ + Encode object to pickle bytes + + >>> by = pickle_encode({'meow': 565656}) + >>> pickle_decode(by) + {'meow': 565656} + """ + with io.BytesIO() as bio: + pickle.dump(obj, bio, protocol=protocol, fix_imports=fix_imports) + return bio.getvalue() + + +def pickle_decode(by: bytes) -> any: + """ + Decode pickle bytes to object + """ + with io.BytesIO(by) as bio: + return pickle.load(bio)