Basic Serialization
This page covers the Python xlang quickstart. pyfory.Fory() defaults to xlang mode with
compatible schema evolution; examples set xlang=True explicitly so the mode choice is visible.
Basic Object Serialization
Serialize and deserialize Python objects with a simple API:
import pyfory
fory = pyfory.Fory(xlang=True)
# Serialize xlang-compatible values
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
Use dataclasses and type annotations for stable xlang payloads:
import pyfory
from dataclasses import dataclass
from typing import List, Dict
@dataclass
class Person:
name: str
age: pyfory.Int32
scores: List[pyfory.Int32]
metadata: Dict[str, str]
fory = pyfory.Fory(xlang=True, ref=True)
fory.register(Person, typename="example.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 repeated references safely when the payload uses xlang-compatible types:
import pyfory
f = pyfory.Fory(xlang=True, ref=True)
shared = ["shared"]
value = [shared, shared]
data = f.serialize(value)
result = f.deserialize(data)
assert result[0] is result[1]
For arbitrary Python object graphs, local classes, functions, and methods, use Native Serialization.
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(xlang=True)
for obj in objects:
data = fory.dumps(obj)
# Bad: Create new instance each time
for obj in objects:
fory = pyfory.Fory(xlang=True) # Wasteful!
data = fory.dumps(obj)
Related Topics
- Configuration - Fory parameters
- Type Registration - Registration patterns
- Native Serialization - Functions and lambdas
- Out-of-Band Serialization - Buffer callback APIs