From b9cba9f1490f1a9684d205b7915800a77abdec24 Mon Sep 17 00:00:00 2001 From: gadial Date: Tue, 7 Jan 2025 12:21:15 +0200 Subject: [PATCH] ObservablesArray docstring improvement (#13423) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ObservablesArray docstring improvement * Update qiskit/primitives/containers/observables_array.py Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> * Update qiskit/primitives/containers/observables_array.py Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> * Linting * Added `ObservableLike` as possible return type --------- Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- .../containers/observables_array.py | 21 +++++++++++++++++-- ...bles_array_docstring-d6e74b1871e3145c.yaml | 6 ++++++ 2 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 releasenotes/notes/improve_observables_array_docstring-d6e74b1871e3145c.yaml diff --git a/qiskit/primitives/containers/observables_array.py b/qiskit/primitives/containers/observables_array.py index 21c415d75899..f339589ac79d 100644 --- a/qiskit/primitives/containers/observables_array.py +++ b/qiskit/primitives/containers/observables_array.py @@ -97,8 +97,25 @@ def __repr__(self): array = np.array2string(self._array, prefix=prefix, suffix=suffix, threshold=50) return prefix + array + suffix - def tolist(self) -> list: - """Convert to a nested list""" + def tolist(self) -> list | ObservableLike: + """Convert to a nested list. + + Similar to Numpy's ``tolist`` method, the level of nesting + depends on the dimension of the observables array. In the + case of dimension 0 the method returns a single observable + (``dict`` in the case of a weighted sum of Paulis) instead of a list. + + Examples:: + Return values for a one-element list vs one element: + + >>> from qiskit.primitives.containers.observables_array import ObservablesArray + >>> oa = ObservablesArray.coerce(["Z"]) + >>> print(type(oa.tolist())) + + >>> oa = ObservablesArray.coerce("Z") + >>> print(type(oa.tolist())) + + """ return self._array.tolist() def __array__(self, dtype=None, copy=None): diff --git a/releasenotes/notes/improve_observables_array_docstring-d6e74b1871e3145c.yaml b/releasenotes/notes/improve_observables_array_docstring-d6e74b1871e3145c.yaml new file mode 100644 index 000000000000..061dc8cfa4ce --- /dev/null +++ b/releasenotes/notes/improve_observables_array_docstring-d6e74b1871e3145c.yaml @@ -0,0 +1,6 @@ +--- +features_primitives: + - | + Expanded the docstring of :meth:`.ObservablesArray.tolist` + to make it clear it might return a scalar in the case + the observables array is of dimension 0.