serde.pickle
Serialize and Deserialize in Pickle format.
1""" 2Serialize and Deserialize in Pickle format. 3""" 4 5import pickle 6from typing import overload, Any, Optional 7 8from .compat import T 9from .de import Deserializer, from_dict 10from .se import Serializer, to_dict 11 12__all__ = ["from_pickle", "to_pickle"] 13 14 15class PickleSerializer(Serializer[bytes]): 16 @classmethod 17 def serialize(cls, obj: Any, **opts: Any) -> bytes: 18 return pickle.dumps(obj, **opts) 19 20 21class PickleDeserializer(Deserializer[bytes]): 22 @classmethod 23 def deserialize(cls, data: bytes, **opts: Any) -> Any: 24 return pickle.loads(data, **opts) 25 26 27def to_pickle( 28 obj: Any, 29 cls: Optional[Any] = None, 30 se: type[Serializer[bytes]] = PickleSerializer, 31 reuse_instances: bool = False, 32 convert_sets: bool = True, 33 skip_none: bool = False, 34 **opts: Any, 35) -> bytes: 36 return se.serialize( 37 to_dict(obj, c=cls, reuse_instances=reuse_instances, convert_sets=convert_sets), **opts 38 ) 39 40 41@overload 42def from_pickle( 43 c: type[T], data: bytes, de: type[Deserializer[bytes]] = PickleDeserializer, **opts: Any 44) -> T: ... 45 46 47@overload 48def from_pickle( 49 c: Any, data: bytes, de: type[Deserializer[bytes]] = PickleDeserializer, **opts: Any 50) -> Any: ... 51 52 53# For Union, Optional etc. 54def from_pickle( 55 c: Any, data: bytes, de: type[Deserializer[bytes]] = PickleDeserializer, **opts: Any 56) -> Any: 57 return from_dict(c, de.deserialize(data, **opts), reuse_instances=False)
def
from_pickle( c: Any, data: bytes, de: type[serde.de.Deserializer[bytes]] = <class 'serde.pickle.PickleDeserializer'>, **opts: Any) -> Any:
def
to_pickle( obj: Any, cls: Optional[Any] = None, se: type[serde.se.Serializer[bytes]] = <class 'serde.pickle.PickleSerializer'>, reuse_instances: bool = False, convert_sets: bool = True, skip_none: bool = False, **opts: Any) -> bytes:
28def to_pickle( 29 obj: Any, 30 cls: Optional[Any] = None, 31 se: type[Serializer[bytes]] = PickleSerializer, 32 reuse_instances: bool = False, 33 convert_sets: bool = True, 34 skip_none: bool = False, 35 **opts: Any, 36) -> bytes: 37 return se.serialize( 38 to_dict(obj, c=cls, reuse_instances=reuse_instances, convert_sets=convert_sets), **opts 39 )