title: Basic Serialization sidebar_position: 1 id: 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 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.
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.
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, name="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, ...)
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.
ref=True if not needed: Reference tracking has overheadENABLE_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)