pygx.wire¶
Wire formats for serializing PyGX values.
wire
¶
Wire formats for serializing PyGX values.
pygx.wire turns PyGX values into transport- and storage-friendly
representations and back. It is built in three decoupled layers:
- The canonical representation: a tree of plain Python values
(
WireValue, == the JSON data model). Both halves below meet only through this plain-data contract. - The object protocol:
WireConvertible— an object that converts itself to/from aWireValueviato_json/from_json.WireConversionContextcarries shared state (e.g. ref tracking) across a single conversion. - The codecs:
WireFormatimplementations that encode/decode aWireValueto bytes/text.JsonFormatis the default;YamlFormatis a second format with different capabilities. Pick one viaserialize/deserializeorformat=on the symbolic save/load helpers; add your own withregister_format.
WireConversionContext
¶
Bases: WireConvertible
JSON conversion context.
WireConversionContext is introduced to handle serialization scenarios where operations cannot be performed in a single pass. For example: Serialization and deserialization of shared objects across different locations.
Shared object serialization/deserialization.¶
In PyGX, only values referenced by pg.Ref and non-PyGX managed objects
are sharable. This ensures that multiple references to the same object are
serialized only once. During deserialization, the object is created just once
and shared among all references.
Source code in pygx/wire/_conversion.py
ObjectEntry
dataclass
¶
ObjectEntry(
value: Any,
serialized: WireValue | None,
ref_index: int,
ref_count: int,
inlined_at: dict | None = None,
)
Per-value bookkeeping for serialize_maybe_shared.
Allocated once per non-primitive value on the hot to_json path,
so slots=True matters: it skips the __dict__ and shrinks the
per-entry footprint.
inlined_at is non-None when the entry's serialized form is
currently inlined into the json tree at that dict (same object).
On a second reference, we mutate that dict in place to a
{REF_KEY: idx} wrap and move the original content to serialized.
inlined_at is None when the entry has already been promoted to a
ref, or was wrapped from the start (e.g. list-shaped serialized
that we can't mutate to a dict in place).
get_shared
¶
get_shared(ref_index: int) -> ObjectEntry
next_shared_index
¶
pending_ref
¶
A stand-in for a not-yet-built shared entry (a cycle's back-edge).
serialize_maybe_shared
¶
serialize_maybe_shared(
value: Any, json_fn: Callable[..., WireValue] | None = None, **kwargs
) -> WireValue
Track maybe-shared objects and return their JSON representation.
Inline-first strategy
- First encounter, dict-shaped: return the serialized content directly and remember it as the "inline" location.
- First encounter, other shape (list, scalar): wrap in
{REF_KEY: idx}— we can't mutate non-dicts to a ref shape later, so post-pass unwrap handles ref_count == 1. - Subsequent encounter: mutate the (still-inline) first
occurrence in place into
{REF_KEY: idx}, stash the original content on the entry, and return a fresh{REF_KEY: idx}.
This avoids the wrap/unwrap dance in the common (no-share) case and preserves identity-preserving dedup when sharing actually occurs.
Callers MUST nest the returned value (e.g. parent[k] = result);
a later .update(result) would mutate an orphan dict on promotion
and the ref would never appear in the tree.
Note: context is always a named arg on the callers
(utils.to_json, Ref.sym_jsonify), never inside **kwargs, so we
don't bother filtering it out of kwargs here.
Source code in pygx/wire/_conversion.py
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 | |
to_json
¶
Serializes a root node with the context to JSON value.
Source code in pygx/wire/_conversion.py
from_json
classmethod
¶
from_json(json_value: WireValue, **kwargs) -> WireConversionContext
Deserializes a WireConvertible value from JSON value.
Source code in pygx/wire/_conversion.py
WireConvertible
¶
Interface for objects convertible to/from the canonical wire representation.
A wire-convertible object is one that can turn itself into a WireValue
(a tree of plain Python dict/list/primitive values) and back, hence
can be serialized by any WireFormat (JSON, YAML, ...). The
representation coincides with the JSON data model, which is why the protocol
methods are named to_json/from_json.
Subclasses of WireConvertible should implement:
to_json: A method that returns a plain Python dict with a_typeproperty whose value should identify the class.from_json: A class method that takes a plain Python dict and returns an instance of the class.
Example::
class MyObject(pg.WireConvertible):
def __init__(self, x: int):
self.x = x
def to_json(self, **kwargs):
return {
'_type': 'MyObject',
'x': self.x
}
@classmethod
def from_json(cls, json_value, **kwargs):
return cls(json_value['x'])
All symbolic types (see pygx.Symbolic) are JSON convertible.
from_json
classmethod
¶
Creates an instance of this class from a plain Python value.
NOTE(daiyip): pg.Symbolic overrides from_json class method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_value
|
WireValue
|
JSON value type. |
required |
**kwargs
|
Any
|
Keyword arguments as flags to control object creation. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
An instance of cls. |
Source code in pygx/wire/_conversion.py
to_json
abstractmethod
¶
to_json(
*, context: Optional[WireConversionContext] = None, **kwargs: Any
) -> WireValue
Returns a plain Python value as a representation for this object.
A plain Python value are basic python types that can be serialized into
JSON, e.g: bool, int, float, str, dict (with string
keys), list, tuple where the container types should have plain
Python values as their values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Optional[WireConversionContext]
|
JSON conversion context. |
None
|
**kwargs
|
Any
|
Keyword arguments as flags to control JSON conversion. |
{}
|
Returns:
| Type | Description |
|---|---|
WireValue
|
A plain Python value. |
Source code in pygx/wire/_conversion.py
register
classmethod
¶
register(
type_name: str,
subclass: type[WireConvertible],
override_existing: bool = False,
) -> None
Registers a class with a type name.
The type name will be used as the key for class lookup during deserialization. A class can be registered with multiple type names, but a type name should be uesd only for one class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_name
|
str
|
A global unique string identifier for subclass. |
required |
subclass
|
type[WireConvertible]
|
A subclass of WireConvertible. |
required |
override_existing
|
bool
|
If True, override the class if the type name is already present in the registry. Otherwise an error will be raised. |
False
|
Source code in pygx/wire/_conversion.py
add_module_alias
classmethod
¶
Adds a module alias so previous serialized objects could be loaded.
set_trusted_pickle_types
classmethod
¶
Sets the global allow-list of types that may be unpickled.
Opaque (non-WireConvertible) objects are serialized via pickle
(see _OpaqueObject). Because pickle.loads can execute arbitrary
code, deserializing untrusted JSON is unsafe by default. Restrict it
by allow-listing exactly the types your data is expected to contain::
pg.WireConvertible.set_trusted_pickle_types([MyData, np.ndarray]) obj = pg.from_json_str(untrusted_json) # refuses anything else
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_types
|
Iterable[str | type[Any]] | None
|
An iterable of types or fully-qualified
|
required |
Note
The allow-list governs the standard-pickle reconstruction path,
where the pickle stream references the concrete type by name. Objects
serialized via the optional cloudpickle fallback (lambdas,
closures, local classes) reference cloudpickle's code-building
reconstructors instead, which cannot be meaningfully sandboxed by a
type allow-list — loading those requires trusting the payload.
Source code in pygx/wire/_conversion.py
trusted_pickle_types
classmethod
¶
is_registered
classmethod
¶
class_from_typename
classmethod
¶
class_from_typename(type_name: str) -> type[WireConvertible] | None
Gets the class for a registered type name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_name
|
str
|
A string as the global unique type identifier for requested class. |
required |
Returns:
| Type | Description |
|---|---|
type[WireConvertible] | None
|
A type object if registered, otherwise None. |
Source code in pygx/wire/_conversion.py
registered_types
classmethod
¶
registered_types() -> Iterable[tuple[str, type[WireConvertible]]]
Returns an iterator of registered (serialization key, class) tuples.
load_types_for_deserialization
classmethod
¶
load_types_for_deserialization(
*types_to_deserialize: type[Any],
) -> ContextManager[dict[str, type[Any]]]
Context manager for loading unregistered types for deserialization.
Example::
class A(pg.Object, to_json_key=False): x: int
class B(A): y: str with pg.JSONConvertile.load_types_for_deserialization(A, B): pg.from_json_str(A(1).to_json_str()) pg.from_json_str(B(1, 'hi').to_json_str())
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*types_to_deserialize
|
type[Any]
|
A list of types to be loaded for deserialization. |
()
|
Returns:
| Type | Description |
|---|---|
ContextManager[dict[str, type[Any]]]
|
A context manager within which the objects of the requested types could be deserialized. |
Source code in pygx/wire/_conversion.py
to_json_dict
classmethod
¶
to_json_dict(
fields: dict[str, tuple[Any, Any] | Any],
*,
exclude_default=False,
exclude_keys: set[str] | None = None,
**kwargs
) -> dict[str, WireValue]
Helper method to create JSON dict from class and field.
Source code in pygx/wire/_conversion.py
JsonFormat
¶
WireFormat
¶
Bases: ABC
Base class for a wire format: a codec over the canonical representation.
Subclasses set :attr:name and override :meth:encode / :meth:decode.
They may flip the capability flags to declare which PyGX semantics they can
represent; the conversion engine consults them (see supports_refs).
YamlFormat
¶
Bases: WireFormat
A YAML wire format -- a worked example of a second format.
YAML carries non-string keys natively (native_int_keys=True), so it
skips JSON's int-key escaping. It does not represent shared/cyclic
references (supports_refs=False): serializing a value with such sharing
raises a clear error instead of emitting an anchor-less __ref__ table.
escape_wire_key
¶
The emit-side escape: one added backslash on a marker-like key.
Source code in pygx/wire/_conversion.py
escape_wire_list_head
¶
Escapes a serialized LIST whose head spells the tuple marker.
Source code in pygx/wire/_conversion.py
from_json
¶
from_json(
json_value: WireValue,
*,
context: WireConversionContext | None = None,
auto_import: bool = True,
convert_unknown: bool = False,
**kwargs: Any
) -> Any
Deserializes a (maybe) WireConvertible value from JSON value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_value
|
WireValue
|
Input JSON value. |
required |
context
|
WireConversionContext | None
|
Serialization context. |
None
|
auto_import
|
bool
|
If True, when a '_type' is not registered, PyGX will identify its parent module and automatically import it. For example, if the type is 'foo.bar.A', PyGX will try to import 'foo.bar' and find the class 'A' within the imported module. |
True
|
convert_unknown
|
bool
|
If True, when a '_type' is not registered and cannot
be imported, PyGX will create objects of:
- |
False
|
**kwargs
|
Any
|
Keyword arguments that will be passed to WireConvertible.init.
Two names are consumed by the engine itself rather than forwarded:
|
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Deserialized value. |
Source code in pygx/wire/_conversion.py
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 | |
is_wire_marker_key
¶
True if k is a reserved wire marker key, unescaped.
The DECLARATION-side test (schema application rejects a symbolic field
spelled this way), as opposed to escape_wire_key's emit-side one:
this asks "is this the marker itself", so an already-escaped spelling
(\_type) is NOT a marker — it round-trips to the literal key.
Source code in pygx/wire/_conversion.py
registered_types
¶
registered_types() -> Iterable[tuple[str, type[WireConvertible]]]
Returns an iterator of registered (serialization key, class) tuples.
to_json
¶
to_json(
value: Any,
*,
context: WireConversionContext | None = None,
supports_refs: bool = True,
**kwargs: Any
) -> Any
Serializes a (maybe) WireConvertible value into a plain Python object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
value to serialize. Applicable value types are:
|
required |
context
|
WireConversionContext | None
|
JSON conversion context. |
None
|
supports_refs
|
bool
|
Whether the target wire format can represent shared/cyclic
references. When False, a value referenced more than once raises instead
of emitting a |
True
|
**kwargs
|
Any
|
Keyword arguments to pass to value.to_json if value is WireConvertible. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
JSON value. |
Source code in pygx/wire/_conversion.py
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 | |
unescape_wire_key
¶
The read-side unescape: strips exactly one backslash.
unescape_wire_list_head
¶
The read-side twin of escape_wire_list_head — strips one backslash.
Mutates and returns out: every caller owns the list it passes (a
freshly decoded payload), and the escape twin above mutates too.
Source code in pygx/wire/_conversion.py
deserialize
¶
deserialize(
data: str | bytes, *, format: str | WireFormat = "json", **kwargs: Any
) -> Any
Deserializes a value from a wire format (JSON by default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str | bytes
|
The serialized representation. |
required |
format
|
str | WireFormat
|
A registered format name or a :class: |
'json'
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The deserialized value. |
Source code in pygx/wire/_format.py
get_format
¶
get_format(format: str | WireFormat) -> WireFormat
Resolves a format name or instance to a :class:WireFormat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
format
|
str | WireFormat
|
Either a registered format name (e.g. |
required |
Returns:
| Type | Description |
|---|---|
WireFormat
|
The resolved :class: |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a name is given that is not registered. |
Source code in pygx/wire/_format.py
register_format
¶
register_format(fmt: WireFormat, *, override_existing: bool = False) -> None
Registers a wire format under its name for lookup by format=.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fmt
|
WireFormat
|
The format instance to register. |
required |
override_existing
|
bool
|
If True, replace an already-registered format with the
same name. Otherwise a |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Source code in pygx/wire/_format.py
registered_formats
¶
registered_formats() -> dict[str, WireFormat]
serialize
¶
serialize(
value: Any,
*,
format: str | WireFormat = "json",
indent: int | None = None,
**kwargs: Any
) -> str | bytes
Serializes a value to a wire format (JSON by default).
Convenience wrapper that runs the conversion engine then the format codec::
s = pg.serialize(obj, format='yaml') obj2 = pg.deserialize(s, format='yaml')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to serialize. |
required |
format
|
str | WireFormat
|
A registered format name (e.g. |
'json'
|
indent
|
int | None
|
Optional indentation passed to the format's encoder. |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
str | bytes
|
The serialized representation ( |
Source code in pygx/wire/_format.py
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2