Skip to content

API Reference

This page provides comprehensive API documentation for the pyserde library, automatically generated from source code docstrings.

serde

ExternalTagging module-attribute

ExternalTagging = Tagging()

Untagged module-attribute

Untagged = Tagging(kind=Untagged)

disabled module-attribute

disabled = TypeCheck(kind=Disabled)

strict module-attribute

strict = TypeCheck(kind=Strict)

coerce module-attribute

coerce = TypeCheck(kind=Coerce)

SerdeError

Bases: Exception

Serde error class.

Source code in serde/compat.py
class SerdeError(Exception):
    """
    Serde error class.
    """

SerdeSkip

Bases: Exception

Skip a field in custom (de)serializer.

Source code in serde/compat.py
class SerdeSkip(Exception):
    """
    Skip a field in custom (de)serializer.
    """

ClassSerializer

Bases: Protocol

Interface for custom class serializer.

This protocol is intended to be used for custom class serializer.

from datetime import datetime from serde import serde from plum import dispatch class MySerializer(ClassSerializer): ... @dispatch ... def serialize(self, value: datetime) -> str: ... return value.strftime("%d/%m/%y")

Source code in serde/core.py
class ClassSerializer(Protocol):
    """
    Interface for custom class serializer.

    This protocol is intended to be used for custom class serializer.

    >>> from datetime import datetime
    >>> from serde import serde
    >>> from plum import dispatch
    >>> class MySerializer(ClassSerializer):
    ...     @dispatch
    ...     def serialize(self, value: datetime) -> str:
    ...         return value.strftime("%d/%m/%y")
    """

    def serialize(self, value: Any) -> Any:
        pass

ClassDeserializer

Bases: Protocol

Interface for custom class deserializer.

This protocol is intended to be used for custom class deserializer.

from datetime import datetime from serde import serde from plum import dispatch class MyDeserializer(ClassDeserializer): ... @dispatch ... def deserialize(self, cls: type[datetime], value: Any) -> datetime: ... return datetime.strptime(value, "%d/%m/%y")

Source code in serde/core.py
class ClassDeserializer(Protocol):
    """
    Interface for custom class deserializer.

    This protocol is intended to be used for custom class deserializer.

    >>> from datetime import datetime
    >>> from serde import serde
    >>> from plum import dispatch
    >>> class MyDeserializer(ClassDeserializer):
    ...     @dispatch
    ...     def deserialize(self, cls: type[datetime], value: Any) -> datetime:
    ...         return datetime.strptime(value, "%d/%m/%y")
    """

    def deserialize(self, cls: Any, value: Any) -> Any:
        pass

serde

serde(
    _cls: Type[T],
    rename_all: str | None = None,
    reuse_instances_default: bool = True,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    transparent: bool = False,
    serializer: SerializeFunc | None = None,
    deserializer: DeserializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    serialize_class_var: bool = False,
    class_serializer: ClassSerializer | None = None,
    class_deserializer: ClassDeserializer | None = None,
    deny_unknown_fields: bool = False,
) -> Type[T]
serde(
    _cls: Any = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = True,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    transparent: bool = False,
    serializer: SerializeFunc | None = None,
    deserializer: DeserializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    serialize_class_var: bool = False,
    class_serializer: ClassSerializer | None = None,
    class_deserializer: ClassDeserializer | None = None,
    deny_unknown_fields: bool = False,
) -> Callable[[type[T]], type[T]]
serde(
    _cls: Any = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = True,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    transparent: bool = False,
    serializer: SerializeFunc | None = None,
    deserializer: DeserializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    serialize_class_var: bool = False,
    class_serializer: ClassSerializer | None = None,
    class_deserializer: ClassDeserializer | None = None,
    deny_unknown_fields: bool = False,
) -> Any

serde decorator. Keyword arguments are passed in serialize and deserialize.

Source code in serde/__init__.py
@dataclass_transform(field_specifiers=(field,))
def serde(
    _cls: Any = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = True,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    transparent: bool = False,
    serializer: SerializeFunc | None = None,
    deserializer: DeserializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    serialize_class_var: bool = False,
    class_serializer: ClassSerializer | None = None,
    class_deserializer: ClassDeserializer | None = None,
    deny_unknown_fields: bool = False,
) -> Any:
    """
    serde decorator. Keyword arguments are passed in `serialize` and `deserialize`.
    """

    def wrap(cls: Any) -> Any:
        if should_impl_dataclass(cls):
            dataclass(cls)
        serialize(
            cls,
            rename_all=rename_all,
            reuse_instances_default=reuse_instances_default,
            convert_sets_default=convert_sets_default,
            skip_if_default=skip_if_default,
            skip_if_none=skip_if_none,
            transparent=transparent,
            serializer=serializer,
            deserializer=deserializer,
            tagging=tagging,
            type_check=type_check,
            serialize_class_var=serialize_class_var,
            class_serializer=class_serializer,
        )
        deserialize(
            cls,
            rename_all=rename_all,
            reuse_instances_default=reuse_instances_default,
            convert_sets_default=convert_sets_default,
            skip_if_default=skip_if_default,
            skip_if_none=skip_if_none,
            transparent=transparent,
            serializer=serializer,
            deserializer=deserializer,
            tagging=tagging,
            type_check=type_check,
            serialize_class_var=serialize_class_var,
            class_deserializer=class_deserializer,
            deny_unknown_fields=deny_unknown_fields,
        )
        return cls

    if _cls is None:
        return wrap

    return wrap(_cls)

serialize

serialize(
    _cls: type[T] | None = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = False,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    serializer: SerializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    serialize_class_var: bool = False,
    transparent: bool = False,
    class_serializer: ClassSerializer | None = None,
    **kwargs: Any
) -> type[T]

A dataclass with this decorator is serializable into any of the data formats supported by pyserde.

from datetime import datetime from serde import serialize from serde.json import to_json

@serialize ... class Foo: ... i: int ... s: str ... f: float ... b: bool

to_json(Foo(i=10, s='foo', f=100.0, b=True)) '{"i":10,"s":"foo","f":100.0,"b":true}'

Source code in serde/se.py
@dataclass_transform()
def serialize(
    _cls: type[T] | None = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = False,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    serializer: SerializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    serialize_class_var: bool = False,
    transparent: bool = False,
    class_serializer: ClassSerializer | None = None,
    **kwargs: Any,
) -> type[T]:
    """
    A dataclass with this decorator is serializable into any of the data formats
    supported by pyserde.

    >>> from datetime import datetime
    >>> from serde import serialize
    >>> from serde.json import to_json
    >>>
    >>> @serialize
    ... class Foo:
    ...     i: int
    ...     s: str
    ...     f: float
    ...     b: bool
    >>>
    >>> to_json(Foo(i=10, s='foo', f=100.0, b=True))
    '{"i":10,"s":"foo","f":100.0,"b":true}'
    """

    def wrap(cls: type[T]) -> type[T]:
        tagging.check()

        # If no `dataclass` found in the class, dataclassify it automatically.
        if not is_dataclass(cls):
            dataclass(cls)

        if transparent:
            get_transparent_field(cls)

        if type_check.is_strict():
            serde_beartype = beartype(conf=BeartypeConf(violation_type=SerdeError))
            serde_beartype(cls)

        g: dict[str, Any] = {}

        # Create a scope storage used by serde.
        # Each class should get own scope. Child classes can not share scope with parent class.
        # That's why we need the "scope.cls is not cls" check.
        scope: Scope | None = getattr(cls, SERDE_SCOPE, None)
        if scope is None or scope.cls is not cls:
            scope = Scope(
                cls,
                reuse_instances_default=reuse_instances_default,
                convert_sets_default=convert_sets_default,
                skip_if_default_default=skip_if_default,
                skip_if_none_default=skip_if_none,
            )
            setattr(cls, SERDE_SCOPE, scope)
        scope.transparent = transparent

        class_serializers: list[ClassSerializer] = list(
            itertools.chain(GLOBAL_CLASS_SERIALIZER, [class_serializer] if class_serializer else [])
        )

        # Set some globals for all generated functions
        g["cls"] = cls
        g["copy"] = copy
        g["serde_scope"] = scope
        g["SerdeError"] = SerdeError
        g["enum_value"] = enum_value
        g["is_dataclass"] = is_dataclass
        g["typename"] = typename  # used in union functions
        g["is_instance"] = is_instance  # used in union functions
        g["to_obj"] = to_obj
        g["typing"] = typing
        g["Literal"] = Literal
        g["TypeCheck"] = TypeCheck
        g["disabled"] = disabled
        g["coerce_object"] = coerce_object
        g["class_serializers"] = class_serializers
        if serializer:
            g["serde_legacy_custom_class_serializer"] = functools.partial(
                serde_legacy_custom_class_serializer, custom=serializer
            )

        # Collect types used in the generated code.
        for typ in iter_types(cls):
            # When we encounter a dataclass not marked with serialize, then also generate serialize
            # functions for it.
            if is_dataclass_without_se(typ) and typ is not cls:
                # We call serialize and not wrap to make sure that we will use the default serde
                # configuration for generating the serialization function.
                serialize(typ)

            if is_primitive(typ) and not is_enum(typ):
                continue
            g[typename(typ)] = typ

        # render all union functions
        for union in iter_unions(cls):
            union_args = list(type_args(union))
            union_key = union_func_name(UNION_SE_PREFIX, union_args)
            add_func(scope, union_key, render_union_func(cls, union_args, tagging), g)
            scope.union_se_args[union_key] = union_args

        for f in sefields(cls, serialize_class_var):
            if f.skip_if:
                g[f.skip_if.name] = f.skip_if
            if f.serializer:
                g[f.serializer.name] = f.serializer

        add_func(
            scope,
            TO_ITER,
            render_to_tuple(cls, serializer, type_check, serialize_class_var, class_serializer),
            g,
        )
        add_func(
            scope,
            TO_DICT,
            render_to_dict(
                cls, rename_all, serializer, type_check, serialize_class_var, class_serializer
            ),
            g,
        )

        logger.debug(f"{typename(cls)}: {SERDE_SCOPE} {scope}")

        return cls

    if _cls is None:
        return wrap  # type: ignore

    if _cls in GENERATION_STACK:
        return _cls

    GENERATION_STACK.append(_cls)
    try:
        return wrap(_cls)
    finally:
        GENERATION_STACK.pop()

deserialize

deserialize(
    _cls: type[T] | None = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = True,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    deserializer: DeserializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    class_deserializer: ClassDeserializer | None = None,
    deny_unknown_fields: bool = False,
    transparent: bool = False,
    **kwargs: Any
) -> type[T]

A dataclass with this decorator is deserializable from any of the data formats supported by pyserde.

from serde import deserialize from serde.json import from_json

@deserialize ... class Foo: ... i: int ... s: str ... f: float ... b: bool

from_json(Foo, '{"i": 10, "s": "foo", "f": 100.0, "b": true}') Foo(i=10, s='foo', f=100.0, b=True)

Source code in serde/de.py
@dataclass_transform()
def deserialize(
    _cls: type[T] | None = None,
    rename_all: str | None = None,
    reuse_instances_default: bool = True,
    convert_sets_default: bool = False,
    skip_if_default: bool = False,
    skip_if_none: bool = False,
    deserializer: DeserializeFunc | None = None,
    tagging: Tagging = DefaultTagging,
    type_check: TypeCheck = strict,
    class_deserializer: ClassDeserializer | None = None,
    deny_unknown_fields: bool = False,
    transparent: bool = False,
    **kwargs: Any,
) -> type[T]:
    """
    A dataclass with this decorator is deserializable from any of the data formats supported
    by pyserde.

    >>> from serde import deserialize
    >>> from serde.json import from_json
    >>>
    >>> @deserialize
    ... class Foo:
    ...     i: int
    ...     s: str
    ...     f: float
    ...     b: bool
    >>>
    >>> from_json(Foo, '{"i": 10, "s": "foo", "f": 100.0, "b": true}')
    Foo(i=10, s='foo', f=100.0, b=True)
    """

    stack = []

    def wrap(cls: type[T]) -> type[T]:
        if cls in stack:
            return cls
        stack.append(cls)

        tagging.check()

        # If no `dataclass` found in the class, dataclassify it automatically.
        if not is_dataclass(cls):
            dataclass(cls)

        if transparent:
            get_transparent_field(cls)

        if type_check.is_strict():
            serde_beartype = beartype(conf=BeartypeConf(violation_type=SerdeError))
            serde_beartype(cls)

        g: dict[str, Any] = {}

        # Create a scope storage used by serde.
        # Each class should get own scope. Child classes can not share scope with parent class.
        # That's why we need the "scope.cls is not cls" check.
        scope: Scope | None = getattr(cls, SERDE_SCOPE, None)
        if scope is None or scope.cls is not cls:
            scope = Scope(
                cls,
                reuse_instances_default=reuse_instances_default,
                convert_sets_default=convert_sets_default,
                skip_if_default_default=skip_if_default,
                skip_if_none_default=skip_if_none,
            )
            setattr(cls, SERDE_SCOPE, scope)
        scope.transparent = transparent

        class_deserializers: list[ClassDeserializer] = list(
            itertools.chain(
                GLOBAL_CLASS_DESERIALIZER, [class_deserializer] if class_deserializer else []
            )
        )

        # Set some globals for all generated functions
        g["cls"] = cls
        g["serde_scope"] = scope
        g["SerdeError"] = SerdeError
        g["UserError"] = UserError
        g["typename"] = typename
        g["ensure"] = ensure
        g["typing"] = typing
        g["collections"] = collections
        g["Literal"] = Literal
        g["from_obj"] = from_obj
        g["get_generic_arg"] = get_generic_arg
        g["is_instance"] = is_instance
        g["TypeCheck"] = TypeCheck
        g["disabled"] = disabled
        g["coerce_object"] = coerce_object
        g["_exists_by_aliases"] = _exists_by_aliases
        g["_get_by_aliases"] = _get_by_aliases
        g["class_deserializers"] = class_deserializers
        g["BeartypeCallHintParamViolation"] = BeartypeCallHintParamViolation
        g["is_bearable"] = is_bearable
        if deserializer:
            g["serde_legacy_custom_class_deserializer"] = functools.partial(
                serde_legacy_custom_class_deserializer, custom=deserializer
            )

        # Collect types used in the generated code.
        for typ in iter_types(cls):
            # When we encounter a dataclass not marked with deserialize, then also generate
            # deserialize functions for it.
            if is_dataclass_without_de(typ) and typ is not cls:
                # We call deserialize and not wrap to make sure that we will use the default serde
                # configuration for generating the deserialization function.
                deserialize(typ)

            # We don't want to add primitive class e.g "str" into the scope, but primitive
            # compatible types such as IntEnum and a subclass of primitives are added,
            # so that generated code can use those types.
            if is_primitive(typ) and not is_enum(typ) and not is_primitive_subclass(typ):
                continue

            if is_generic(typ):
                g[typename(typ)] = get_origin(typ)
            else:
                g[typename(typ)] = typ

        # render all union functions
        for union in iter_unions(cls):
            union_args = type_args(union)
            add_func(
                scope,
                union_func_name(UNION_DE_PREFIX, union_args),
                render_union_func(cls, union_args, tagging),
                g,
            )

        # render literal functions
        for literal in iter_literals(cls):
            literal_args = type_args(literal)
            add_func(
                scope, literal_func_name(literal_args), render_literal_func(cls, literal_args), g
            )

        # Collect default values and default factories used in the generated code.
        for f in defields(cls):
            assert f.name
            if has_default(f):
                scope.defaults[f.name] = f.default
            elif has_default_factory(f):
                scope.defaults[f.name] = f.default_factory
            if f.deserializer:
                g[f.deserializer.name] = f.deserializer

        add_func(
            scope,
            FROM_ITER,
            render_from_iter(cls, deserializer, type_check, class_deserializer=class_deserializer),
            g,
        )
        add_func(
            scope,
            FROM_DICT,
            render_from_dict(
                cls,
                rename_all,
                deserializer,
                type_check,
                class_deserializer=class_deserializer,
                deny_unknown_fields=deny_unknown_fields,
            ),
            g,
        )

        logger.debug(f"{typename(cls)}: {SERDE_SCOPE} {scope}")

        stack.pop()
        return cls

    if _cls is None:
        return wrap  # type: ignore

    if _cls in GENERATION_STACK:
        return _cls

    GENERATION_STACK.append(_cls)
    try:
        return wrap(_cls)
    finally:
        GENERATION_STACK.pop()

is_serializable

is_serializable(instance_or_class: Any) -> bool

Test if an instance or class is serializable.

@serialize ... class Foo: ... pass

Testing Foo class object returns True.

is_serializable(Foo) True

Testing Foo object also returns True.

is_serializable(Foo()) True

Source code in serde/se.py
def is_serializable(instance_or_class: Any) -> bool:
    """
    Test if an instance or class is serializable.

    >>> @serialize
    ... class Foo:
    ...     pass

    Testing `Foo` class object returns `True`.
    >>> is_serializable(Foo)
    True

    Testing `Foo` object also returns `True`.
    >>> is_serializable(Foo())
    True
    """
    return hasattr(instance_or_class, SERDE_SCOPE)

is_deserializable

is_deserializable(instance_or_class: Any) -> bool

Test if an instance or class is deserializable.

@deserialize ... class Foo: ... pass

is_deserializable(Foo) True

Source code in serde/de.py
def is_deserializable(instance_or_class: Any) -> bool:
    """
    Test if an instance or class is deserializable.

    >>> @deserialize
    ... class Foo:
    ...     pass
    >>>
    >>> is_deserializable(Foo)
    True
    """
    return hasattr(instance_or_class, SERDE_SCOPE)

to_dict

to_dict(
    o: Any,
    c: type[Any] | None = None,
    reuse_instances: bool | None = None,
    convert_sets: bool | None = None,
    skip_none: bool = False,
) -> dict[Any, Any]

Serialize object into python dictionary. This function ensures that the dataclass's fields are accurately represented as key-value pairs in the resulting dictionary.

  • o: Any pyserde object that you want to convert to dict
  • c: Optional class argument
  • reuse_instances: pyserde will pass instances (e.g. Path, datetime) directly to serializer instead of converting them to serializable representation e.g. string. This behaviour allows to delegate serializtation to underlying data format packages e.g. pyyaml and potentially improve performance.
  • convert_sets: This option controls how sets are handled during serialization and deserialization. When convert_sets is set to True, pyserde will convert sets to lists during serialization and back to sets during deserialization. This is useful for data formats that do not natively support sets.
  • skip_none: When set to True, any field in the class with a None value is excluded from the serialized output. Defaults to False.

from serde import serde @serde ... class Foo: ... i: int ... s: str = 'foo' ... f: float = 100.0 ... b: bool = True

to_dict(Foo(i=10))

You can serialize not only pyserde objects but also objects of any supported types. For example, the following example serializes list of pyserde objects into dict.

lst = [Foo(i=10), Foo(i=20)] to_dict(lst) [{'i': 10, 's': 'foo', 'f': 100.0, 'b': True}, {'i': 20, 's': 'foo', 'f': 100.0, 'b': True}]

Source code in serde/se.py
def to_dict(
    o: Any,
    c: type[Any] | None = None,
    reuse_instances: bool | None = None,
    convert_sets: bool | None = None,
    skip_none: bool = False,
) -> dict[Any, Any]:
    """
    Serialize object into python dictionary. This function ensures that the dataclass's fields are
    accurately represented as key-value pairs in the resulting dictionary.

    * `o`: Any pyserde object that you want to convert to `dict`
    * `c`: Optional class argument
    * `reuse_instances`: pyserde will pass instances (e.g. Path, datetime) directly to serializer
    instead of converting them to serializable representation e.g. string. This behaviour allows
    to delegate serializtation to underlying data format packages e.g. `pyyaml` and potentially
    improve performance.
    * `convert_sets`: This option controls how sets are handled during serialization and
    deserialization. When `convert_sets` is set to True, pyserde will convert sets to lists during
    serialization and back to sets during deserialization. This is useful for data formats that
    do not natively support sets.
    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
    serialized output. Defaults to False.

    >>> from serde import serde
    >>> @serde
    ... class Foo:
    ...     i: int
    ...     s: str = 'foo'
    ...     f: float = 100.0
    ...     b: bool = True
    >>>
    >>> to_dict(Foo(i=10))
    {'i': 10, 's': 'foo', 'f': 100.0, 'b': True}

    You can serialize not only pyserde objects but also objects of any supported types. For example,
    the following example serializes list of pyserde objects into dict.

    >>> lst = [Foo(i=10), Foo(i=20)]
    >>> to_dict(lst)
    [{'i': 10, 's': 'foo', 'f': 100.0, 'b': True}, {'i': 20, 's': 'foo', 'f': 100.0, 'b': True}]
    """
    return to_obj(  # type: ignore
        o,
        named=True,
        c=c,
        reuse_instances=reuse_instances,
        convert_sets=convert_sets,
        skip_none=skip_none,
    )

from_dict

from_dict(
    cls: type[T],
    o: dict[str, Any],
    reuse_instances: bool | None = None,
    deserialize_numbers: (
        Callable[[str | int], float] | None
    ) = None,
) -> T
from_dict(
    cls: Any,
    o: dict[str, Any],
    reuse_instances: bool | None = None,
    deserialize_numbers: (
        Callable[[str | int], float] | None
    ) = None,
) -> Any
from_dict(
    cls: Any,
    o: dict[str, Any],
    reuse_instances: bool | None = None,
    deserialize_numbers: (
        Callable[[str | int], float] | None
    ) = None,
) -> Any

Deserialize dictionary into object.

@deserialize ... class Foo: ... i: int ... s: str = 'foo' ... f: float = 100.0 ... b: bool = True

from_dict(Foo, {'i': 10, 's': 'foo', 'f': 100.0, 'b': True}) Foo(i=10, s='foo', f=100.0, b=True)

You can pass any type supported by pyserde. For example,

  • deserialize_numbers: Optional callable to coerce numeric input to floats when the target type is float (e.g. accept ints or numeric strings supplied by a parser).

lst = [{'i': 10, 's': 'foo', 'f': 100.0, 'b': True}, ... {'i': 20, 's': 'foo', 'f': 100.0, 'b': True}] from_dict(list[Foo], lst) [Foo(i=10, s='foo', f=100.0, b=True), Foo(i=20, s='foo', f=100.0, b=True)]

Source code in serde/de.py
def from_dict(
    cls: Any,
    o: dict[str, Any],
    reuse_instances: bool | None = None,
    deserialize_numbers: Callable[[str | int], float] | None = None,
) -> Any:
    """
    Deserialize dictionary into object.

    >>> @deserialize
    ... class Foo:
    ...     i: int
    ...     s: str = 'foo'
    ...     f: float = 100.0
    ...     b: bool = True
    >>>
    >>> from_dict(Foo, {'i': 10, 's': 'foo', 'f': 100.0, 'b': True})
    Foo(i=10, s='foo', f=100.0, b=True)

    You can pass any type supported by pyserde. For example,

    * `deserialize_numbers`: Optional callable to coerce numeric input to floats when the target
      type is float (e.g. accept ints or numeric strings supplied by a parser).

    >>> lst = [{'i': 10, 's': 'foo', 'f': 100.0, 'b': True},
    ...        {'i': 20, 's': 'foo', 'f': 100.0, 'b': True}]
    >>> from_dict(list[Foo], lst)
    [Foo(i=10, s='foo', f=100.0, b=True), Foo(i=20, s='foo', f=100.0, b=True)]
    """
    return from_obj(
        cls,
        o,
        named=True,
        reuse_instances=reuse_instances,
        deserialize_numbers=deserialize_numbers,
    )

to_tuple

to_tuple(
    o: Any,
    c: type[Any] | None = None,
    reuse_instances: bool | None = None,
    convert_sets: bool | None = None,
    skip_none: bool = False,
) -> tuple[Any, ...]

Serialize object into tuple.

@serialize ... class Foo: ... i: int ... s: str = 'foo' ... f: float = 100.0 ... b: bool = True

to_tuple(Foo(i=10)) (10, 'foo', 100.0, True)

You can pass any type supported by pyserde. For example,

lst = [Foo(i=10), Foo(i=20)] to_tuple(lst) [(10, 'foo', 100.0, True), (20, 'foo', 100.0, True)]

Source code in serde/se.py
def to_tuple(
    o: Any,
    c: type[Any] | None = None,
    reuse_instances: bool | None = None,
    convert_sets: bool | None = None,
    skip_none: bool = False,
) -> tuple[Any, ...]:
    """
    Serialize object into tuple.

    >>> @serialize
    ... class Foo:
    ...     i: int
    ...     s: str = 'foo'
    ...     f: float = 100.0
    ...     b: bool = True
    >>>
    >>> to_tuple(Foo(i=10))
    (10, 'foo', 100.0, True)

    You can pass any type supported by pyserde. For example,

    >>> lst = [Foo(i=10), Foo(i=20)]
    >>> to_tuple(lst)
    [(10, 'foo', 100.0, True), (20, 'foo', 100.0, True)]
    """
    return to_obj(  # type: ignore
        o,
        named=False,
        c=c,
        reuse_instances=reuse_instances,
        convert_sets=convert_sets,
        skip_none=skip_none,
    )

from_tuple

from_tuple(
    cls: type[T],
    o: Any,
    reuse_instances: bool | None = None,
    deserialize_numbers: (
        Callable[[str | int], float] | None
    ) = None,
) -> T
from_tuple(
    cls: Any,
    o: Any,
    reuse_instances: bool | None = None,
    deserialize_numbers: (
        Callable[[str | int], float] | None
    ) = None,
) -> Any
from_tuple(
    cls: Any,
    o: Any,
    reuse_instances: bool | None = None,
    deserialize_numbers: (
        Callable[[str | int], float] | None
    ) = None,
) -> Any

Deserialize tuple into object.

@deserialize ... class Foo: ... i: int ... s: str = 'foo' ... f: float = 100.0 ... b: bool = True

from_tuple(Foo, (10, 'foo', 100.0, True)) Foo(i=10, s='foo', f=100.0, b=True)

You can pass any type supported by pyserde. For example,

  • deserialize_numbers: Optional callable to coerce numeric input to floats when the target type is float (e.g. accept ints or numeric strings supplied by a parser).

lst = [(10, 'foo', 100.0, True), (20, 'foo', 100.0, True)] from_tuple(list[Foo], lst) [Foo(i=10, s='foo', f=100.0, b=True), Foo(i=20, s='foo', f=100.0, b=True)]

Source code in serde/de.py
def from_tuple(
    cls: Any,
    o: Any,
    reuse_instances: bool | None = None,
    deserialize_numbers: Callable[[str | int], float] | None = None,
) -> Any:
    """
    Deserialize tuple into object.

    >>> @deserialize
    ... class Foo:
    ...     i: int
    ...     s: str = 'foo'
    ...     f: float = 100.0
    ...     b: bool = True
    >>>
    >>> from_tuple(Foo, (10, 'foo', 100.0, True))
    Foo(i=10, s='foo', f=100.0, b=True)

    You can pass any type supported by pyserde. For example,

    * `deserialize_numbers`: Optional callable to coerce numeric input to floats when the target
      type is float (e.g. accept ints or numeric strings supplied by a parser).

    >>> lst = [(10, 'foo', 100.0, True), (20, 'foo', 100.0, True)]
    >>> from_tuple(list[Foo], lst)
    [Foo(i=10, s='foo', f=100.0, b=True), Foo(i=20, s='foo', f=100.0, b=True)]
    """
    return from_obj(
        cls,
        o,
        named=False,
        reuse_instances=reuse_instances,
        deserialize_numbers=deserialize_numbers,
    )

AdjacentTagging

AdjacentTagging(tag: str, content: str) -> Tagging
AdjacentTagging(
    tag: str, content: str, cls: T
) -> _WithTagging[T]
AdjacentTagging(
    tag: str, content: str, cls: T | None = None
) -> Tagging | _WithTagging[T]
Source code in serde/core.py
def AdjacentTagging(tag: str, content: str, cls: T | None = None) -> Tagging | _WithTagging[T]:
    tagging = Tagging(tag, content, kind=Tagging.Kind.Adjacent)
    if cls:
        return tagging(cls)
    else:
        return tagging

InternalTagging

InternalTagging(tag: str) -> Tagging
InternalTagging(tag: str, cls: T) -> _WithTagging[T]
InternalTagging(
    tag: str, cls: T | None = None
) -> Tagging | _WithTagging[T]
Source code in serde/core.py
def InternalTagging(tag: str, cls: T | None = None) -> Tagging | _WithTagging[T]:
    tagging = Tagging(tag, kind=Tagging.Kind.Internal)
    if cls:
        return tagging(cls)
    else:
        return tagging

field

field(
    *args: Any,
    rename: str | None = None,
    alias: list[str] | None = None,
    skip: bool | None = None,
    skip_serializing: bool | None = None,
    skip_deserializing: bool | None = None,
    skip_if: Callable[[Any], Any] | None = None,
    skip_if_false: bool | None = None,
    skip_if_none: bool | None = None,
    skip_if_default: bool | None = None,
    serializer: Callable[..., Any] | None = None,
    deserializer: Callable[..., Any] | None = None,
    flatten: FlattenOpts | bool | None = None,
    metadata: dict[str, Any] | None = None,
    **kwargs: Any
) -> Any

Declare a field with parameters.

Source code in serde/core.py
def field(
    *args: Any,
    rename: str | None = None,
    alias: list[str] | None = None,
    skip: bool | None = None,
    skip_serializing: bool | None = None,
    skip_deserializing: bool | None = None,
    skip_if: Callable[[Any], Any] | None = None,
    skip_if_false: bool | None = None,
    skip_if_none: bool | None = None,
    skip_if_default: bool | None = None,
    serializer: Callable[..., Any] | None = None,
    deserializer: Callable[..., Any] | None = None,
    flatten: FlattenOpts | bool | None = None,
    metadata: dict[str, Any] | None = None,
    **kwargs: Any,
) -> Any:
    """
    Declare a field with parameters.
    """
    if not metadata:
        metadata = {}

    if rename is not None:
        metadata["serde_rename"] = rename
    if alias is not None:
        metadata["serde_alias"] = alias
    if skip is not None:
        metadata["serde_skip"] = skip
    if skip_serializing is not None:
        metadata["serde_skip_serializing"] = skip_serializing
    if skip_deserializing is not None:
        metadata["serde_skip_deserializing"] = skip_deserializing
    if skip_if is not None:
        metadata["serde_skip_if"] = skip_if
    if skip_if_false is not None:
        metadata["serde_skip_if_false"] = skip_if_false
    if skip_if_none is not None:
        metadata["serde_skip_if_none"] = skip_if_none
    if skip_if_default is not None:
        metadata["serde_skip_if_default"] = skip_if_default
    if serializer:
        metadata["serde_serializer"] = serializer
    if deserializer:
        metadata["serde_deserializer"] = deserializer
    if flatten is True:
        metadata["serde_flatten"] = FlattenOpts()
    elif flatten:
        metadata["serde_flatten"] = flatten

    return dataclasses.field(*args, metadata=metadata, **kwargs)

default_deserializer

default_deserializer(_cls: type[Any], obj: Any) -> Any

Marker function to tell serde to use the default deserializer. It's used when custom deserializer is specified at the class but you want to override a field with the default deserializer.

Source code in serde/de.py
def default_deserializer(_cls: type[Any], obj: Any) -> Any:
    """
    Marker function to tell serde to use the default deserializer. It's used when custom
    deserializer is specified at the class but you want to override a field with the default
    deserializer.
    """

asdict

asdict(v: Any) -> dict[Any, Any]

Serialize object into dictionary.

Source code in serde/se.py
def asdict(v: Any) -> dict[Any, Any]:
    """
    Serialize object into dictionary.
    """
    return to_dict(v, reuse_instances=False, convert_sets=False)

astuple

astuple(v: Any) -> tuple[Any, ...]

Serialize object into tuple.

Source code in serde/se.py
def astuple(v: Any) -> tuple[Any, ...]:
    """
    Serialize object into tuple.
    """
    return to_tuple(v, reuse_instances=False, convert_sets=False)

default_serializer

default_serializer(_cls: type[Any], obj: Any) -> Any

Marker function to tell serde to use the default serializer. It's used when custom serializer is specified at the class but you want to override a field with the default serializer.

Source code in serde/se.py
def default_serializer(_cls: type[Any], obj: Any) -> Any:
    """
    Marker function to tell serde to use the default serializer. It's used when custom serializer
    is specified at the class but you want to override a field with the default serializer.
    """

add_serializer

add_serializer(serializer: ClassSerializer) -> None

Register custom global serializer.

Source code in serde/core.py
def add_serializer(serializer: ClassSerializer) -> None:
    """
    Register custom global serializer.
    """
    GLOBAL_CLASS_SERIALIZER.append(serializer)

add_deserializer

add_deserializer(deserializer: ClassDeserializer) -> None

Register custom global deserializer.

Source code in serde/core.py
def add_deserializer(deserializer: ClassDeserializer) -> None:
    """
    Register custom global deserializer.
    """
    GLOBAL_CLASS_DESERIALIZER.append(deserializer)

json

Serialize and Deserialize in JSON format.

from_json

from_json(
    c: type[T],
    s: AnyStr,
    de: type[Deserializer[AnyStr]] = JsonDeserializer,
    coerce_numbers: bool = True,
    **opts: Any
) -> T
from_json(
    c: Any,
    s: AnyStr,
    de: type[Deserializer[AnyStr]] = JsonDeserializer,
    coerce_numbers: bool = True,
    **opts: Any
) -> Any
from_json(
    c: Any,
    s: AnyStr,
    de: type[Deserializer[AnyStr]] = JsonDeserializer,
    coerce_numbers: bool = True,
    **opts: Any
) -> Any

Deserialize from JSON into the object. orjson will be used if installed.

c is a class object and s is JSON bytes or str. If you supply other keyword arguments, they will be passed in loads function.

  • coerce_numbers: When True (default), ints from JSON are coerced to floats when the target type is float. Strings are never coerced.

If you want to use another json package, you can subclass JsonDeserializer and implement your own logic.

Source code in serde/json.py
def from_json(
    c: Any,
    s: AnyStr,
    de: type[Deserializer[AnyStr]] = JsonDeserializer,
    coerce_numbers: bool = True,
    **opts: Any,
) -> Any:
    """
    Deserialize from JSON into the object. [orjson](https://github.com/ijl/orjson) will be used
    if installed.

    `c` is a class object and `s` is JSON bytes or str. If you supply other keyword arguments,
    they will be passed in `loads` function.

    * `coerce_numbers`: When True (default), ints from JSON are coerced to floats when the target
      type is float. Strings are never coerced.

    If you want to use another json package, you can subclass `JsonDeserializer` and implement your
    own logic.
    """
    deserialize_numbers = deserialize_json_numbers if coerce_numbers else None
    return from_dict(
        c,
        de.deserialize(s, **opts),
        reuse_instances=False,
        deserialize_numbers=deserialize_numbers,
    )

to_json

to_json(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[str]] = JsonSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = False,
    **opts: Any
) -> str

Serialize the object into JSON str. orjson will be used if installed.

You can pass any serializable obj. If you supply other keyword arguments, they will be passed in dumps function. By default, numpy objects are serialized, this behaviour can be customized with the option argument with orjson, or the default argument with Python standard json library.

  • skip_none: When set to True, any field in the class with a None value is excluded from the serialized output. Defaults to False.

If you want to use another json package, you can subclass JsonSerializer and implement your own logic.

Source code in serde/json.py
def to_json(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[str]] = JsonSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = False,
    **opts: Any,
) -> str:
    """
    Serialize the object into JSON str. [orjson](https://github.com/ijl/orjson)
    will be used if installed.

    You can pass any serializable `obj`. If you supply other keyword arguments,
    they will be passed in `dumps` function.
    By default, numpy objects are serialized, this behaviour can be customized with the `option`
    argument with [orjson](https://github.com/ijl/orjson#numpy), or the `default` argument with
    Python standard json library.

    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
    serialized output. Defaults to False.

    If you want to use another json package, you can subclass `JsonSerializer` and implement
    your own logic.
    """
    return se.serialize(
        to_dict(
            obj,
            c=cls,
            reuse_instances=reuse_instances,
            convert_sets=convert_sets,
            skip_none=skip_none,
        ),
        **opts,
    )

yaml

Serialize and Deserialize in YAML format. This module depends on pyyaml package.

from_yaml

from_yaml(
    c: type[T],
    s: str,
    de: type[Deserializer[str]] = YamlDeserializer,
    coerce_numbers: bool = True,
    **opts: Any
) -> T
from_yaml(
    c: Any,
    s: str,
    de: type[Deserializer[str]] = YamlDeserializer,
    coerce_numbers: bool = True,
    **opts: Any
) -> Any
from_yaml(
    c: Any,
    s: str,
    de: type[Deserializer[str]] = YamlDeserializer,
    coerce_numbers: bool = True,
    **opts: Any
) -> Any

c is a class object and s is YAML string. If you supply keyword arguments other than de, they will be passed in yaml.safe_load function.

  • coerce_numbers: When True (default), numeric YAML scalars or numeric strings (e.g. "1e-3") are coerced to floats when the target type is float. Booleans are rejected.

If you want to use the other yaml package, you can subclass YamlDeserializer and implement your own logic.

Source code in serde/yaml.py
def from_yaml(
    c: Any,
    s: str,
    de: type[Deserializer[str]] = YamlDeserializer,
    coerce_numbers: bool = True,
    **opts: Any,
) -> Any:
    """
    `c` is a class object and `s` is YAML string. If you supply keyword arguments other than `de`,
    they will be passed in `yaml.safe_load` function.

    * `coerce_numbers`: When True (default), numeric YAML scalars or numeric strings (e.g.
      "1e-3") are coerced to floats when the target type is float. Booleans are rejected.

    If you want to use the other yaml package, you can subclass `YamlDeserializer` and implement
    your own logic.
    """
    deserialize_numbers = deserialize_yaml_numbers if coerce_numbers else None
    return from_dict(
        c,
        de.deserialize(s, **opts),
        reuse_instances=False,
        deserialize_numbers=deserialize_numbers,
    )

to_yaml

to_yaml(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[str]] = YamlSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = False,
    **opts: Any
) -> str

Serialize the object into YAML.

You can pass any serializable obj. If you supply keyword arguments other than se, they will be passed in yaml.safe_dump function.

  • skip_none: When set to True, any field in the class with a None value is excluded from the serialized output. Defaults to False.

If you want to use the other yaml package, you can subclass YamlSerializer and implement your own logic.

Source code in serde/yaml.py
def to_yaml(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[str]] = YamlSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = False,
    **opts: Any,
) -> str:
    """
    Serialize the object into YAML.

    You can pass any serializable `obj`. If you supply keyword arguments other than `se`,
    they will be passed in `yaml.safe_dump` function.

    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
    serialized output. Defaults to False.

    If you want to use the other yaml package, you can subclass `YamlSerializer` and implement
    your own logic.
    """
    return se.serialize(
        to_dict(
            obj,
            c=cls,
            reuse_instances=reuse_instances,
            convert_sets=convert_sets,
            skip_none=skip_none,
        ),
        **opts,
    )

toml

Serialize and Deserialize in TOML format. This module depends on tomli (for python==3.10) and tomli-w packages.

from_toml

from_toml(
    c: type[T],
    s: str,
    de: type[Deserializer[str]] = TomlDeserializer,
    **opts: Any
) -> T
from_toml(
    c: Any,
    s: str,
    de: type[Deserializer[str]] = TomlDeserializer,
    **opts: Any
) -> Any
from_toml(
    c: Any,
    s: str,
    de: type[Deserializer[str]] = TomlDeserializer,
    **opts: Any
) -> Any

Deserialize from TOML into the object.

c is a class object and s is TOML string. If you supply keyword arguments other than de, they will be passed in toml.loads function.

If you want to use the other toml package, you can subclass TomlDeserializer and implement your own logic.

Source code in serde/toml.py
def from_toml(c: Any, s: str, de: type[Deserializer[str]] = TomlDeserializer, **opts: Any) -> Any:
    """
    Deserialize from TOML into the object.

    `c` is a class object and `s` is TOML string. If you supply keyword arguments other than `de`,
    they will be passed in `toml.loads` function.

    If you want to use the other toml package, you can subclass `TomlDeserializer` and implement
    your own logic.
    """
    return from_dict(c, de.deserialize(s, **opts), reuse_instances=False)

to_toml

to_toml(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[str]] = TomlSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = True,
    **opts: Any
) -> str

Serialize the object into TOML.

You can pass any serializable obj. If you supply keyword arguments other than se, they will be passed in toml_w.dumps function.

  • skip_none: When set to True, any field in the class with a None value is excluded from the serialized output. Defaults to True.

If you want to use the other toml package, you can subclass TomlSerializer and implement your own logic.

Source code in serde/toml.py
def to_toml(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[str]] = TomlSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = True,
    **opts: Any,
) -> str:
    """
    Serialize the object into TOML.

    You can pass any serializable `obj`. If you supply keyword arguments other than `se`,
    they will be passed in `toml_w.dumps` function.

    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
    serialized output. Defaults to True.

    If you want to use the other toml package, you can subclass `TomlSerializer` and implement
    your own logic.
    """
    return se.serialize(
        to_dict(
            obj,
            c=cls,
            reuse_instances=reuse_instances,
            convert_sets=convert_sets,
            skip_none=skip_none,
        ),
        **opts,
    )

msgpack

Serialize and Deserialize in MsgPack format. This module depends on msgpack package.

from_msgpack

from_msgpack(
    c: type[T],
    s: bytes,
    de: type[Deserializer[bytes]] = MsgPackDeserializer,
    named: bool = True,
    ext_dict: dict[int, type[Any]] | None = None,
    **opts: Any
) -> T
from_msgpack(
    c: Any,
    s: bytes,
    de: type[Deserializer[bytes]] = MsgPackDeserializer,
    named: bool = True,
    ext_dict: dict[int, type[Any]] | None = None,
    **opts: Any
) -> Any
from_msgpack(
    c: Any,
    s: bytes,
    de: type[Deserializer[bytes]] = MsgPackDeserializer,
    named: bool = True,
    ext_dict: dict[int, type[Any]] | None = None,
    skip_none: bool = False,
    **opts: Any
) -> Any

Deserialize from MsgPack into the object.

c is a class object and s is MsgPack binary. If ext_dict option is specified, c is ignored and type is inferred from msgpack.ExtType If you supply other keyword arguments, they will be passed in msgpack.unpackb function.

If you want to use the other msgpack package, you can subclass MsgPackDeserializer and implement your own logic.

Source code in serde/msgpack.py
def from_msgpack(
    c: Any,
    s: bytes,
    de: type[Deserializer[bytes]] = MsgPackDeserializer,
    named: bool = True,
    ext_dict: dict[int, type[Any]] | None = None,
    skip_none: bool = False,
    **opts: Any,
) -> Any:
    """
    Deserialize from MsgPack into the object.

    `c` is a class object and `s` is MsgPack binary. If `ext_dict` option is specified,
    `c` is ignored and type is inferred from `msgpack.ExtType` If you supply other keyword
    arguments, they will be passed in `msgpack.unpackb` function.

    If you want to use the other msgpack package, you can subclass `MsgPackDeserializer`
    and implement your own logic.
    """
    if ext_dict is not None:
        ext = de.deserialize(s, **opts)
        ext_type = ext_dict.get(ext.code)
        if ext_type is None:
            raise SerdeError(f"Could not find type for code {ext.code} in ext_dict")
        return from_msgpack(ext_type, ext.data, de, named, **opts)
    else:
        from_func = from_dict if named else from_tuple
        return from_func(c, de.deserialize(s, **opts), reuse_instances=False)

to_msgpack

to_msgpack(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[bytes]] = MsgPackSerializer,
    named: bool = True,
    ext_dict: dict[type[Any], int] | None = None,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    **opts: Any
) -> bytes

Serialize the object into MsgPack.

You can pass any serializable obj. If ext_dict option is specified, obj is encoded as a msgpack.ExtType If you supply other keyword arguments, they will be passed in msgpack.packb function.

  • named: If named is True, field names are preserved, namely the object is encoded as dict then serialized into MsgPack. If named is False, the object is encoded as tuple then serialized into MsgPack. named=False will produces compact binary.

  • skip_none: When set to True, any field in the class with a None value is excluded from the serialized output. Defaults to False.

If you want to use the other msgpack package, you can subclass MsgPackSerializer and implement your own logic.

Source code in serde/msgpack.py
def to_msgpack(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[bytes]] = MsgPackSerializer,
    named: bool = True,
    ext_dict: dict[type[Any], int] | None = None,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    **opts: Any,
) -> bytes:
    """
    Serialize the object into MsgPack.

    You can pass any serializable `obj`. If `ext_dict` option is specified, `obj` is encoded
    as a `msgpack.ExtType` If you supply other keyword arguments, they will be passed in
    `msgpack.packb` function.

    * `named`: If `named` is True, field names are preserved, namely the object is encoded as `dict`
    then serialized into MsgPack.  If `named` is False, the object is encoded as `tuple` then
    serialized into MsgPack. `named=False` will produces compact binary.

    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
    serialized output. Defaults to False.

    If you want to use the other msgpack package, you can subclass `MsgPackSerializer` and
    implement your own logic.
    """
    ext_type_code = None
    if ext_dict is not None:
        obj_type = type(obj)
        ext_type_code = ext_dict.get(obj_type)
        if ext_type_code is None:
            raise SerdeError(f"Could not find type code for {obj_type.__name__} in ext_dict")

    kwargs: Any = {"c": cls, "reuse_instances": reuse_instances, "convert_sets": convert_sets}
    dict_or_tuple = to_dict(obj, **kwargs) if named else to_tuple(obj, **kwargs)
    return se.serialize(
        dict_or_tuple,
        ext_type_code=ext_type_code,
        **opts,
    )

pickle

Serialize and Deserialize in Pickle format.

from_pickle

from_pickle(
    c: type[T],
    data: bytes,
    de: type[Deserializer[bytes]] = PickleDeserializer,
    **opts: Any
) -> T
from_pickle(
    c: Any,
    data: bytes,
    de: type[Deserializer[bytes]] = PickleDeserializer,
    **opts: Any
) -> Any
from_pickle(
    c: Any,
    data: bytes,
    de: type[Deserializer[bytes]] = PickleDeserializer,
    **opts: Any
) -> Any
Source code in serde/pickle.py
def from_pickle(
    c: Any, data: bytes, de: type[Deserializer[bytes]] = PickleDeserializer, **opts: Any
) -> Any:
    return from_dict(c, de.deserialize(data, **opts), reuse_instances=False)

to_pickle

to_pickle(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[bytes]] = PickleSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = False,
    **opts: Any
) -> bytes
Source code in serde/pickle.py
def to_pickle(
    obj: Any,
    cls: Any | None = None,
    se: type[Serializer[bytes]] = PickleSerializer,
    reuse_instances: bool = False,
    convert_sets: bool = True,
    skip_none: bool = False,
    **opts: Any,
) -> bytes:
    return se.serialize(
        to_dict(obj, c=cls, reuse_instances=reuse_instances, convert_sets=convert_sets), **opts
    )