Skip to content

Instantly share code, notes, and snippets.

@crusaderky
Created April 4, 2024 23:47
Show Gist options
  • Save crusaderky/4ad2ccd05a7ca476e471c7373e202fa7 to your computer and use it in GitHub Desktop.
Save crusaderky/4ad2ccd05a7ca476e471c7373e202fa7 to your computer and use it in GitHub Desktop.
unravel_pickle
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