Skip to content

Replace assert False with KeyError in DAGCircuit methods#133

Merged
gecrooks merged 1 commit intogecrooks:mainfrom
ddri:fix/issue-130-dagcircuit-assert
Dec 19, 2025
Merged

Replace assert False with KeyError in DAGCircuit methods#133
gecrooks merged 1 commit intogecrooks:mainfrom
ddri:fix/issue-130-dagcircuit-assert

Conversation

@ddri
Copy link
Contributor

@ddri ddri commented Dec 19, 2025

Summary

  • Replace assert False with proper KeyError exceptions in next_element() and prev_element()
  • Add docstrings for both methods (previously marked # DOCME TESTME)

Problem

The methods used assert False as error handling:

def next_element(self, elem: Operation, qubit: Optional[Qubit] = None) -> Operation:
    for _, node, key in self.graph.edges(elem, keys=True):
        if qubit is None or key == qubit:
            return node
    assert False  # Insanity check  # FIXME, raise exception

This is problematic because:

  1. Running Python with -O disables assertions, causing the function to return None
  2. AssertionError with no message provides no diagnostic information

Fix

Now raises KeyError with descriptive message:

raise KeyError(f"No next element found for {elem!r} on qubit {qubit}")

Test plan

  • Verified fix manually - KeyError raised with helpful message
  • All existing dagcircuit_test.py tests pass (including test_next_prev)

Fixes #130

The next_element() and prev_element() methods used `assert False` to
handle the case when no element is found. This is problematic because:
1. Assertions are disabled with `python -O`
2. AssertionError provides no diagnostic information

Now raises KeyError with a descriptive message including the element
and qubit being searched for. Also added docstrings for these methods.

Fixes gecrooks#130
@gecrooks gecrooks merged commit 5faf212 into gecrooks:main Dec 19, 2025
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: assert False used instead of raising exception in DAGCircuit

2 participants