[docs] Correct Python docstrings and snippets that contradict the code - #5182
Open
udsy19 wants to merge 3 commits into
Open
[docs] Correct Python docstrings and snippets that contradict the code#5182udsy19 wants to merge 3 commits into
udsy19 wants to merge 3 commits into
Conversation
All three are transliteration slips from the adjacent C++ tab. 1. ``for bits, count in counts:`` (the "fine-grained access to the bits and counts" example under ``cudaq::sample``). ``SampleResult`` iterates over bit-string keys, like a ``dict``, so this unpacks each bit-string into characters instead of yielding pairs. For the two-qubit ``bell`` kernel the example demonstrates, it silently prints ``Observed: 0, 0`` and ``Observed: 1, 1`` rather than the actual counts; at any other width it raises ``ValueError: too many values to unpack (expected 2)``. Use ``counts.items()``, which is the form already used elsewhere in the docs. 2. ``result = cudaq::observe(...)`` inside a ``.. code-block:: python`` — the C++ scope-resolution operator. ``SyntaxError`` as written. 3. The Hamiltonian assignment is split across two lines with no parentheses or continuation, which C++ allows and Python does not. ``SyntaxError`` as written. Wrapping the right-hand side in parentheses matches how the same Hamiltonian is written in ``examples.rst``. After this change every ``.. code-block:: python`` in the file parses with ``ast.parse``; before it, these two did not. Signed-off-by: Udaya Tejas <udayatejas2004@gmail.com>
Each of these is rendered into the published Python API reference through ``docs/sphinx/api/languages/python_api.rst``. All were checked against the installed package. * ``Kernel.mz`` / ``mx`` / ``my`` document the optional register argument as ``register_name``; the parameter is ``regName``. Passing the documented name raises ``TypeError: PyKernel.mz() got an unexpected keyword argument 'register_name'``. * ``cudaq.operators.custom.define`` documents its first argument as ``op_id``; it is ``id``. ``cudaq.operators.custom.instantiate`` documents its first argument as ``operator_id``; it is ``op_id``. Both documented names raise ``TypeError``. * ``cudaq.translate`` describes its return value as a drawing of the execution path "without measurement operations". It returns the kernel translated to the requested format, measurements included: ``format="openqasm2"`` on a kernel containing ``mz(q)`` emits ``creg``/``measure`` lines, and the docstring's own QIR example output shows ``__quantum__qis__mz`` calls. The wording matches ``cudaq.draw``, where it is correct. * ``SampleResult.__getitem__`` documents a ``float`` return. It returns ``int`` -- as the nanobind-generated signature two lines above in the same ``__doc__`` already states, and as the sibling ``count()`` correctly documents. * ``QuakeValue.slice`` documents its first argument as ``start``; it is ``startIdx``. * The nine ``QuakeValue`` arithmetic dunders document ``Raises: RuntimeError: if the underlying QuakeValue type is not a float``. No such error is raised. ``__checkTypesAndCreateQuakeValue`` has emitted integer arithmetic since before these docstrings were added, and ``__neg__`` promotes an integer operand to floating point rather than failing. Replaced with a note describing the accepted operand types. Comments and docstrings only; no functional change. Signed-off-by: Udaya Tejas <udayatejas2004@gmail.com>
The ``.. code-block:: python`` in ``cudaq.get_unitary`` wraps two of its four kernel lines in single backticks and under-indents the trailing ``print(U)``. The backticks render literally and make the block invalid Python: transcribed verbatim it fails with ``SyntaxError`` on the first backticked line. With them removed and ``print(U)`` aligned, the example runs and prints the Bell unitary. The backticks were load-bearing for the spell checker: the ``python`` matrix in ``.github/pre-commit/spellcheck_config.yml`` skips docstring content between inline backticks, and ``cx`` and ``qvector`` are not in the allowlist. Both are CUDA-Q vocabulary (``qvec`` is already listed), so they are added there instead. Signed-off-by: Udaya Tejas <udayatejas2004@gmail.com>
udsy19
requested review from
1tnguyen,
bettinaheim,
bmhowe23 and
mitchdz
as code owners
August 18, 2026 18:43
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5181.
Nine places in the Python documentation state something the code does not do.
Each was verified against an installed
cudaq0.15.1 package before and afterthe change. In every case the code is correct and the documentation is wrong,
so this PR changes only comments, docstrings and whitespace — no executable
line changes.
One of them fails quietly, which is why this is worth a PR rather than a nit:
The
SampleResultiteration example in the specification prints wrong datasilently.
algorithmic_primitives.rstusesfor bits, count in counts:.SampleResultiterates over bit-string keys, like adict, so for thetwo-qubit
bellkernel the example demonstrates:Python unpacked
'00'into two characters; the real counts never appear, andthe output looks plausible next to the C++ tab's
Observed: 00, 514. Withcounts.items():At any other qubit count the documented form raises
ValueError: too many values to unpack (expected 2).The rest
.. code-block:: pythonblocks inalgorithmic_primitives.rstare notPython: one uses the C++ scope operator (
cudaq::observe), the other splitsan expression across two lines without parentheses. Both are
SyntaxError.After this change,
ast.parsesucceeds on all nine Python code blocks inthat file; before it, these two failed.
Kernel.mz/mx/mydocumentregister_name; the parameter isregName. The documented name raisesTypeError.cudaq.operators.custom.definedocumentsop_id(it isid) andinstantiatedocumentsoperator_id(it isop_id). Both raiseTypeError.cudaq.translatesays its result is "the circuit, without measurementoperations". It is not:
format="openqasm2"on a kernel containingmz(q)emits
creg/measure,format="qir"emits__quantum__qis__mzcalls, andthe docstring's own example output shows those calls. The sentence is copied
from
cudaq.draw, where it is correct.SampleResult.__getitem__documents afloatreturn and returnsint— asthe nanobind-generated signature two lines above in the same
__doc__already says, and as the sibling
count()documents correctly.QuakeValue.slicedocumentsstart; the parameter isstartIdx.QuakeValuearithmetic dunders documentRaises: RuntimeError: if the underlying QuakeValue type is not a float.No such error is raised: integer operands emit
arith.muli/addi/subi/divsi, and__neg__promotes toarith.negf.Integer support predates these
Raises:lines, so the claim was neveraccurate; replaced with a note on the accepted operand types.
cudaq.get_unitary's docstring code block wraps two lines in literalbackticks and under-indents the trailing
print, so it renders with thebackticks visible and fails with
SyntaxErrorif copied. Fixed; the block nowextracts and runs, printing the Bell unitary.
One thing that is not a doc fix
Commit
d7fabc860addscxandqvectorto.github/pre-commit/spelling_allowlist.txt. The literal backticks in theget_unitaryexample were load-bearing: thepythonmatrix inspellcheck_config.ymlskips docstring content between inline backticks, soremoving them exposes those two words. Both are CUDA-Q vocabulary and
qvecwasalready in the list. That is the only hunk outside docstrings and
.rst.It shares a commit with the
unitary.pydocstring fix rather than standingalone, so dropping the commit would also drop one of the nine corrections. If
you would rather solve the spelling side another way, say so and I will split
the commit and drop only the allowlist hunk.
Overlaps I checked
apply_noiseblock inpython_api.rst, replacingit with a
literalincludewhose extracted snippet has the indentation right.This PR therefore leaves
python_api.rstalone entirely, so the two cannotconflict; see the scope note below.
QuakeValue.slice. I deliberately left theReturns:block alone so this does not conflict with it, and changed only the wrong
parameter name, which Add half‐open slicing support to QuakeValue #3017 does not touch.
algorithmic_primitives.rstat lines 191-266 and 300-312;the hunks here are at 89, 543 and 586.
examples.rst, which carries a very similar defect in thedeuteron parameter-sweep example. I have kept
examples.rstout of this PRentirely and raised it there instead.
default_ops.rstis untouched — [docs] Document givens_rotation and fermionic_swap operations #5162 is open on it.Verification
cudaq0.15.1 (aca5853a7), Python 3.13, macOS 26.5.1 arm64. Every claim above wasexecuted, both before and after.
pre-commit run --all-files --hook-stage pre-pushwas run onupstream/mainand on this branch. Both give the same result: 13 hooks pass, and
Check links in Markdown filesfails on a pre-existing dead CI-badge URL inREADME.md, a file this branch does not touch.pyspellingpasses.The Sphinx build was not run locally —
conf.pyneeds autodoc against a fullsource build. As a substitute I parsed both edited
.rstfiles with docutilsbefore and after (identical diagnostics, nothing new),
ast.parsed every.. code-block:: pythonin the edited files, and extracted and executed thetwo blocks that were re-indented.
Scope note: an earlier draft of this branch also re-indented the
apply_noiseexample inpython_api.rst. That change was dropped because open PR #2969 already replaces that block with aliteralinclude. This PR deliberately leaves it alone.