Skip to content

Make sure RegisterLayout.from_abstract_repr() only returns an instance of a matching type #1099

Description

@HGSilveri

Currently, calling .from_abstract_repr() on any of RegisterLayout or any of its subclasses (ie. SquareLatticeLayout, TriangularLatticeLayout or RectangularLatticeLayout) will:

  1. Work for any valid serialized RegisterLayout
  2. Always return a RegisterLayout instance

This is potentially misleading, since we can give a serialized instance of a SquareLatticeLayout to TriangularLatticeLayout.from_abstract_repr() and have it successfully return a RegisterLayout that matches the original square lattice layout (and is evidently not a triangular lattice layout).

Following #1096, this will arguably be made even more confusing since we will have TriangularLatticeLayout.from_abstract_repr() return a SquareLatticeLayout instance.

To circumvent this, I propose the following modifications:

  1. In RegisterLayout
- @staticmethod
- def from_abstract_repr(obj_str: str) -> RegisterLayout:
+ @classmethod
+ def from_abstract_repr(cls: Type[T], obj_str: str) -> T:
  1. In deserialize_abstract_layout():
-def deserialize_abstract_layout(obj_str: str) -> RegisterLayout:
+T = TypeVar("T", bound=RegisterLayout)
+def deserialize_abstract_layout(obj_str: str, matching_type: Type[T] | None = None) -> T:
     """Deserialize a layout from an abstract JSON object.

    Args:
        obj_str: the JSON string representing the layout encoded
            in the abstract JSON format.
+        matching_type: A specific `RegisterLayout` that the deserialized layout must match.
+           If not defined, attempts to match any of the known special layouts and returns 
+           `RegisterLayout` if it fails.

This will allow us to pass the specific layout type to deserialize_abstract_layout within from_abstract_repr() (i.e. matching_type=cls) and ensure the desired return type consistency

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions