Basic Serialization
This page covers basic serialization patterns in pyfory.
Basic Object Serialization
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.
Custom Class Serialization
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, ...)
Reference Tracking & Circular References
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
API Reference
Serialization Methods
# 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
With Out-of-Band Buffers
# 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)
Performance Tips
- Disable
ref=Trueif not needed: Reference tracking has overhead - Use type_id instead of typename: Integer IDs are faster than string names
- Reuse Fory instances: Create once, use many times
- Enable Cython: Make sure
ENABLE_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)
Related Topics
- Configuration - Fory parameters
- Type Registration - Registration patterns
- Python Native Mode - Functions and lambdas