Created
April 4, 2024 23:47
-
-
Save crusaderky/4ad2ccd05a7ca476e471c7373e202fa7 to your computer and use it in GitHub Desktop.
unravel_pickle
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
from pickle import PickleBuffer | |
def unravel_pickle(obj: object, seen: list[int] | None = None) -> Any: | |
if isinstance(obj, (int, float, complex, bytes, str, bool, type(None))): | |
return obj | |
if isinstance(obj, (bytearray, memoryview, PickleBuffer)): | |
return str(type(obj)), bytes(obj) | |
if callable(obj): | |
return str(obj) | |
seen = seen or [] | |
try: | |
return "__seen", seen.index(id(obj)), str(obj) | |
except ValueError: | |
pass | |
seen.append(id(obj)) | |
if isinstance(obj, (list, tuple)): | |
return str(type(obj)), [unravel_pickle(v, seen) for v in obj] | |
if isinstance(obj, (set, frozenset)): | |
return str(type(obj)), [unravel_pickle(v, seen) for v in sorted(obj, key=str)] | |
if isinstance(obj, dict): | |
return str(type(obj)), [ | |
(unravel_pickle(k, seen), unravel_pickle(v, seen)) for k, v in obj.items() | |
] | |
return unravel_pickle(obj.__reduce_ex__(5), seen) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment