PseudoPickler
A simple plugin to work like pickle, in that it should
hopefully support serializing arbitrary python objects, but which
doesn’t attempt to put stuff down to a single bytearray, instead
supporting objects with to_state and from_state methods by converting
them to more primitive serializble types like arrays, strings, numbers,
etc.
Falls back to naive pickling when allow_pickle=True and nothing else works.
Protocol 2 (written by default) stores classes by import path
({"module": ..., "qualname": ...}, with moved names handled by register_alias),
writes objects that are referenced more than once a single time (later uses are
{"pseudopickle_ref": n}), and records an optional state_version class attribute.
Protocol 1 specs (which hold pickled classes) can still be read, but only with
allow_pickle=True, and with a DeprecationWarning. Reference cycles can’t be
rebuilt without a two-phase from_state, so they raise an error (or fall back to
pickle when that is allowed).
__init__(self, allow_pickle=False, protocol=2, b64encode=False):
LLM Docstring
Configure pseudo-pickling fallback, protocol marker, and optional base64 encoding for embedded pickle bytes.
allow_pickle:boolwhether unsupported values may be written with pickle, and whether
pickle_data(and protocol 1 class specs) may be read backprotocol:intpseudo-pickle protocol marker written into specs
b64encode:boolwhether pickle bytes are base64 encoded
:returns:NoneNo explicit value; the method mutates state or performs I/O.
@classmethod
register_alias(cls, old_path, new_path):
LLM Docstring
Record that the class stored as old_path now lives at new_path, so files written before a
move or rename still load.
old_path:strthe old location as
"module:Qual.Name"or"module.Name"new_path:strthe new location in the same format
:returns:NoneNo explicit value; the alias table is updated.
to_state(self, obj, cache=None):
Extracts the state for obj (what goes in the state field of its spec), through its
to_state interface or by walking its __dict__
obj:objectthe object to get the state of
cache:Anyunused, kept for compatibility (the walk keeps its own memo)
:returns:objectthe converted state
serialize(self, obj, cache=None):
Serializes an object first by checking for a to_state
method, and that missing, by converting to primitive-ish types
in a recursive strategy, falling back to pickle when that is allowed.
Objects reached more than once are written once and referenced afterwards.
obj:Anyobject to be serialized
cache:Anyunused, kept for compatibility (the walk keeps its own memo per thread)
:returns:dictspec for the pseudo-pickled data
deserialize(self, spec):
Deserializes from an object spec. Classes are imported by path (honoring registered aliases),
and pickle is only used for specs that contain pickled data when allow_pickle=True
(otherwise UnsafeLoadError).
spec:objectthe spec produced by
serialize:returns:objectthe restored object