API Reference¶
This page provides comprehensive API documentation for the pyserde library, automatically generated from source code docstrings.
serde ¶
SerdeError ¶
SerdeSkip ¶
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
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
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
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
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | |
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
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | |
is_serializable ¶
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
is_deserializable ¶
Test if an instance or class is deserializable.
@deserialize ... class Foo: ... pass
is_deserializable(Foo) True
Source code in serde/de.py
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 todictc: Optional class argumentreuse_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.pyyamland potentially improve performance.convert_sets: This option controls how sets are handled during serialization and deserialization. Whenconvert_setsis 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
from_dict ¶
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
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
from_tuple ¶
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
AdjacentTagging ¶
InternalTagging ¶
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
default_deserializer ¶
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
asdict ¶
astuple ¶
default_serializer ¶
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_deserializer ¶
json ¶
Serialize and Deserialize in JSON format.
from_json ¶
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
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
yaml ¶
Serialize and Deserialize in YAML format. This module depends on pyyaml package.
from_yaml ¶
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
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
toml ¶
Serialize and Deserialize in TOML format. This module depends on tomli (for python==3.10) and tomli-w packages.
from_toml ¶
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
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
msgpack ¶
Serialize and Deserialize in MsgPack format. This module depends on msgpack package.
from_msgpack ¶
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
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: Ifnamedis True, field names are preserved, namely the object is encoded asdictthen serialized into MsgPack. Ifnamedis False, the object is encoded astuplethen serialized into MsgPack.named=Falsewill 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
pickle ¶
Serialize and Deserialize in Pickle format.
from_pickle ¶
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