From 0fc564bdc9ae6db768f2e3b5522e98b61e50280f Mon Sep 17 00:00:00 2001 From: Ian Hincks Date: Fri, 26 Jan 2024 01:36:55 -0500 Subject: [PATCH] Add BindingsArray as allowed input type to BindingsArray.coerce() (#11645) --- qiskit/primitives/containers/bindings_array.py | 2 ++ .../containers/test_bindings_array.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/qiskit/primitives/containers/bindings_array.py b/qiskit/primitives/containers/bindings_array.py index 05d35e75be60..036465369ba0 100644 --- a/qiskit/primitives/containers/bindings_array.py +++ b/qiskit/primitives/containers/bindings_array.py @@ -270,6 +270,8 @@ def coerce(cls, bindings_array: BindingsArrayLike) -> BindingsArray: bindings_array = cls(bindings_array) elif isinstance(bindings_array, Mapping): bindings_array = cls(kwvals=bindings_array) + elif isinstance(bindings_array, BindingsArray): + return bindings_array else: raise TypeError(f"Unsupported type {type(bindings_array)} is given.") return bindings_array diff --git a/test/python/primitives/containers/test_bindings_array.py b/test/python/primitives/containers/test_bindings_array.py index dabe4b45a712..4affdcd41102 100644 --- a/test/python/primitives/containers/test_bindings_array.py +++ b/test/python/primitives/containers/test_bindings_array.py @@ -431,3 +431,20 @@ def test_simple_vals(self): self.assertEqual(ba.shape, (1,)) self.assertEqual(len(ba.vals), 1) np.testing.assert_allclose(ba.vals[0], [[1, 2, 3]]) + + def test_coerce(self): + """Test the coerce() method.""" + # BindingsArray passthrough + arg = BindingsArray({"a": np.linspace(0, 1, 5)}) + ba = BindingsArray.coerce(arg) + self.assertEqual(ba, arg) + + # dict-valued input + arg = {"a": np.linspace(0, 1, 5)} + ba = BindingsArray.coerce(arg) + self.assertEqual(ba.num_parameters, 1) + + # None-valued input + arg = None + ba = BindingsArray.coerce(None) + self.assertEqual(ba.num_parameters, 0)