Skip to content

Serializable

The base class for all serializable objects in LoQS.

This class provides a unified serialization framework that supports both JSON and HDF5 formats. Derived classes must implement the abstract methods to define their serialization behavior.

Key Features:

  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

decode staticmethod

decode(encoded: Encoded, format: EncodeFormats = 'hdf5', decode_cache: DecodeCache = None) -> Encodable | DeferredRef

Recursively decode a serialized object following the same pattern as encode.

This method handles the recursive deserialization logic for both JSON and HDF5 formats. It automatically resolves object references, reconstructs complex nested structures, and handles all supported data types.

Parameters:

Name Type Description Default
encoded dict or Group

The encoded object (either JSON dict or HDF5 group). - For JSON: Dictionary with 'encode_type' field - For HDF5: h5py.Group with appropriate attributes

required
format ('json', 'hdf5', 'h5')

The format of the encoded data. - 'json': Decode from JSON dictionary structure - 'hdf5' or 'h5': Decode from HDF5 group structure

'json'
decode_cache dict

Dictionary mapping serialization IDs to object instances for caching. Enables proper handling of object references and prevents duplicate deserialization.

None

Returns:

Type Description
Encodable

The deserialized object. Can be a Serializable object, primitive type, collection (dict, list, tuple, set), or numpy array.


  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

dump

dump(f: IO[str] | TextIOBase | File, format: EncodeFormats = None, use_caching: bool = True, encode_cache: EncodeCache = None, json_format_kwargs: Mapping | None = None, reset_encode_id: bool = True) -> None

Serializes and writes this object to a given output stream.

This method provides the core serialization functionality that supports both JSON and HDF5 formats through a unified interface.

Parameters:

Name Type Description Default
f file - like or File

A writable output stream or HDF5 file.

required
format ('json', 'hdf5', 'h5')

The format to write. If None, auto-detect from file type. - 'json': JSON text format - 'hdf5' or 'h5': HDF5 binary format

'json'
json_format_kwargs dict

Additional arguments specific to the JSON format. For example, the JSON format accepts indent as an argument because json.dump does.

None
use_caching bool

If True (default), repeated objects are written once and referenced afterward. If False, encode_cache is ignored.

True
encode_cache dict

The encode cache to use when use_caching is True. A given cache is filled in place, so the caller can reuse it for later encodes. If None, a new cache is used and then discarded.

None
reset_encode_id bool

If True (default), the encoder's cache ID counter restarts at 0. If False, encoding continues from the current counter, so the new IDs do not repeat ones minted earlier in the same file.

True

Returns:

Type Description
None

  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

encode staticmethod

encode(obj: Encodable, format: EncodeFormats = 'hdf5', encode_cache: EncodeCache = None, ignore_no_serialize_flags: bool = False, reset_encode_id: bool = False, h5_group: Group | None = None)

Recursively encode an object to the specified format.

This method handles the recursive serialization logic for both JSON and HDF5 formats. It serves as the entry point for the serialization process, automatically dispatching to the appropriate encoder based on the format parameter.

Parameters:

Name Type Description Default
obj Encodable

The object to encode. Can be a Serializable object, primitive type, collection (dict, list, tuple, set), or numpy array.

required
format ('json', 'hdf5', 'h5')

The target serialization format. - 'json': Encode to JSON-compatible dictionary structure - 'hdf5' or 'h5': Encode to HDF5 group structure

'json'
encode_cache dict

Dictionary mapping object hashes to serialization IDs for caching. Enables object reference tracking and prevents duplicate serialization.

None
ignore_no_serialize_flags bool

Whether to ignore serialization flags and force serialization. It can't be combined with an encode_cache (a ValueError), because the cache's key reads attributes with the flags honoured.

False
reset_encode_id bool

Whether to reset the global encode ID counter. Useful for starting a new serialization session.

False
h5_group Group

Required for HDF5 format. The HDF5 group to write the object to.

None

Returns:

Type Description
Encoded

The encoded object in the appropriate format: - For JSON: dict with encode_type structure - For HDF5: h5py.Group with appropriate attributes

Examples:

Basic encoding examples:

>>> from tests.internal.test_serializable import MockSerializable
>>> obj = MockSerializable(name="test", value=42)
>>>
>>> # JSON encoding produces a dictionary
>>> encoded_json = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded_json, dict)  # Should return True
True
>>> encoded_json["encode_type"]  # Should be 'Serializable'
'Serializable'

  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

load classmethod

load(f: IO[str] | TextIOBase | File, format: EncodeFormats = None, use_caching: bool = True, decode_cache: DecodeCache = None, migrate_legacy_fns: bool = False) -> Encodable

Load an object of this type, or a subclass of this type, from an input stream.

This method deserializes objects from both JSON and HDF5 formats, automatically handling object caching and reference resolution.

Parameters:

Name Type Description Default
f file - like or File

An open input stream or HDF5 file to read from.

required
format ('json', 'json.gz', 'hdf5', 'h5')

The format of the input stream data. If None, auto-detect from file type. - 'json': JSON text format - 'json.gz': Gzip-compressed JSON format - 'hdf5' or 'h5': HDF5 binary format

'json'
migrate_legacy_fns bool

If a decoded Instruction's frozen source (from a file older than the current SERIALIZATION_VERSION) contains a known legacy-construction pattern (e.g. an old-style positional InstructionLabel(...) call), decoding normally raises a clear error rather than silently running it through a construction-time compatibility shim. Pass True to allow it to run as-is instead. Default is False.

False

Returns:

Type Description
Serializable

The deserialized object of the appropriate class.


  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

read classmethod

read(path: str | Path, format: EncodeFormats = None, use_caching: bool = True, decode_cache: DecodeCache = None, migrate_legacy_fns: bool = False) -> Encodable

Read and deserialize an object from a file.

Convenience method that combines file opening with deserialization. Automatically detects the serialization format from the file extension and delegates to the appropriate loading mechanism.

Parameters:

Name Type Description Default
path str or Path

Path to the file containing the serialized object.

required
format EncodeFormats

The serialization format. If None, automatically detected from file extension. Supported extensions: .json, .json.gz, .h5, .hdf5.

None
use_caching bool

Whether to use object caching during deserialization. Default is True.

True
decode_cache DecodeCache

Existing decode cache to use for reference resolution.

None
migrate_legacy_fns bool

See load(). Default is False.

False

Returns:

Type Description
Encodable

The deserialized object.

Raises:

Type Description
ValueError

If the format cannot be determined from the file extension.

CheckpointReadError

If an HDF5 checkpoint file holds entries past its commit marker, as an interrupted write leaves. Resume the run to read only the committed entries.


  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

serialize_function staticmethod

serialize_function(func: Callable) -> str

Public entry point for pre-computing a function's serialized source, for a caller who needs to supply it explicitly (e.g. as Instruction's serialized_apply_fn=/serialized_map_qubits_fn=) rather than relying on it being computed automatically later -- most importantly, for a function whose source might not stay inspectable until then, such as one defined directly in a Jupyter notebook cell (see Instruction's own docstring for why that matters).


  • Support for both JSON and HDF5 serialization formats
  • Automatic object caching and reference tracking
  • Recursive serialization of complex nested structures
  • Format-agnostic API for easy switching between formats

Derived classes should implement:

  • _from_decoded_attrs(): Create object from decoded attributes

Example: >>> # Define a simple serializable class >>> class SimpleClass(Serializable): ... _CACHE_ON_SERIALIZE = True ... _SERIALIZE_ATTRS = ["name", "value"] ... ... def init(self, name, value): ... self.name = name ... self.value = value ... ... ... @classmethod ... def _from_decoded_attrs(cls, attr_dict): ... return cls(**attr_dict)

>>> # Create and serialize an object
>>> obj = SimpleClass("test", 42)
>>> encoded = Serializable.encode(obj, format="json", reset_encode_id=True)
>>> isinstance(encoded, dict)  # Should return True
True
>>> encoded["encode_type"]  # Should be 'Serializable'
'Serializable'

write

write(path: str | Path, format: EncodeFormats = None, use_caching: bool = True, encode_cache: EncodeCache = None, json_format_kwargs: Mapping | None = None) -> None

Writes this object to a file.

Parameters:

Name Type Description Default
path str or Path

The name of the file that is written.

required
format_kwargs dict

Additional arguments specific to the format being used. For example, the JSON format accepts indent as an argument because json.dump does.

required

Returns:

Type Description
None