Python Native Mode
pyfory provides a Python-native serialization mode that offers the same functionality as pickle/cloudpickle, but with significantly better performance, smaller data size, and enhanced security features.
Overview
The binary protocol and API are similar to Fory's xlang mode, but Python-native mode can serialize any Python object—including global functions, local functions, lambdas, local classes and types with customized serialization using __getstate__/__reduce__/__reduce_ex__, which are not allowed in xlang mode.
To use Python-native mode, create Fory with xlang=False:
import pyfory
fory = pyfory.Fory(xlang=False, ref=False, strict=True)
Drop-in Replacement for Pickle/Cloudpickle
pyfory can serialize any Python object with the following configuration:
- For circular references: Set
ref=Trueto enable reference tracking - For functions/classes: Set
strict=Falseto allow deserialization of dynamic types
⚠️ Security Warning: When strict=False, Fory will deserialize arbitrary types, which can pose security risks if data comes from untrusted sources. Only use strict=False in controlled environments where you trust the data source completely.
Common Usage
import pyfory
# Create Fory instance
fory = pyfory.Fory(xlang=False, ref=True, strict=False)
# serialize common Python objects
data = fory.dumps({"name": "Alice", "age": 30, "scores": [95, 87, 92]})
print(fory.loads(data))
# serialize custom objects
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
person = Person("Bob", 25)
data = fory.dumps(person)
print(fory.loads(data)) # Person(name='Bob', age=25)
Serialize Global Functions
Capture and serialize functions defined at module level. Fory deserialize and return same function object:
import pyfory
fory = pyfory.Fory(xlang=False, ref=True, strict=False)
def my_global_function(x):
return 10 * x
data = fory.dumps(my_global_function)
print(fory.loads(data)(10)) # 100