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
¶
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
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 | |
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.
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. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Deserialized value. |
Source code in pygx/wire/_conversion.py
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 | |
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
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 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 | |
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