title: Basic Serialization sidebar_position: 2 id: python_basic_serialization license: | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
This page covers basic serialization patterns in pyfory.
Serialize and deserialize Python objects with a simple API:
import pyfory # Create Fory instance fory = pyfory.Fory(xlang=True) # Serialize any Python object data = fory.dumps({"name": "Alice", "age": 30, "scores": [95, 87, 92]}) # Deserialize back to Python object obj = fory.loads(data) print(obj) # {'name': 'Alice', 'age': 30, 'scores': [95, 87, 92]}
Note: dumps()/loads() are aliases for serialize()/deserialize(). Both APIs are identical, use whichever feels more intuitive.
Fory automatically handles dataclasses and custom types:
import pyfory from dataclasses import dataclass from typing import List, Dict @dataclass class Person: name: str age: int scores: List[int] metadata: Dict[str, str] # Python mode - supports all Python types including dataclasses fory = pyfory.Fory(xlang=False, ref=True) fory.register(Person) person = Person("Bob", 25, [88, 92, 85], {"team": "engineering"}) data = fory.serialize(person) result = fory.deserialize(data) print(result) # Person(name='Bob', age=25, ...)
Handle shared references and circular dependencies safely:
import pyfory f = pyfory.Fory(ref=True) # Enable reference tracking # Handle circular references safely class Node: def __init__(self, value): self.value = value self.children = [] self.parent = None root = Node("root") child = Node("child") child.parent = root # Circular reference root.children.append(child) # Serializes without infinite recursion data = f.serialize(root) result = f.deserialize(data) assert result.children[0].parent is result # Reference preserved
# Serialize to bytes data: bytes = fory.serialize(obj) data: bytes = fory.dumps(obj) # Alias # Deserialize from bytes obj = fory.deserialize(data) obj = fory.loads(data) # Alias
# Serialize with buffer callback buffer_objects = [] data = fory.serialize(obj, buffer_callback=buffer_objects.append) # Deserialize with buffers buffers = [obj.getbuffer() for obj in buffer_objects] obj = fory.deserialize(data, buffers=buffers)
ref=True if not needed: Reference tracking has overheadENABLE_FORY_CYTHON_SERIALIZATION=1# Good: Reuse instance fory = pyfory.Fory() for obj in objects: data = fory.dumps(obj) # Bad: Create new instance each time for obj in objects: fory = pyfory.Fory() # Wasteful! data = fory.dumps(obj)