#17084·qiskit

`ForLoopOp` body with an `expression.Var` loop parameter cannot capture outer variables

Author: arthurostraussCreated Sep 29, 2026Updated Sep 30, 2026
Labelsbug

Environment

  • Qiskit version: 2.5.0
  • Python version: 3.13
  • Operating system: macOS Golden Gate

What is happening?

Since #16273, a ForLoopOp with an expr.Var loop parameter holds that variable as the single input var of its body. Circuits still forbid mixing inputand captured identifiers, so such a body cannot use any outer Var or Stretch. This includes the loop variable of an enclosing Var loop.

How can we reproduce the issue?

from qiskit.circuit import QuantumCircuit
from qiskit.circuit.classical import expr, types

qc = QuantumCircuit(1)
acc = qc.add_var("acc", expr.lift(0, types.Uint(8)))
with qc.for_loop(range(3), expr.Var.new("i", types.Uint(8))) as i:
    qc.store(acc, i)

Raises:

CircuitError: 'circuits with input variables cannot be enclosed, so they cannot be closures'

The same happens in two other cases:

QuantumCircuit(inputs=[i], captures=[acc]); compose or QPY-loading a circuit that contains such a loop.

ContractIdleWiresInControlFlow has a related failure, even without captures:

from qiskit.transpiler.passes import ContractIdleWiresInControlFlow

i = expr.Var.new("i", types.Uint(8))
body = QuantumCircuit(2, inputs=[i])
body.x(0)
qc = QuantumCircuit(2)
qc.for_loop(range(3), i, body, [0, 1], [])
ContractIdleWiresInControlFlow()(qc)

Raises: CircuitError: 'loop variable is a Var, but body does not contain one'

What should happen?

The body should take i as its input and capture acc, like any other control-flow block that reads an outer variable. The pass should keep `i as the input of the contracted body.

Any suggestions?

The review of #16273 anticipated this (github.com/gadial/qiskit/pull/2): the loop variable is an input because it is passed by value, while captures are passed by reference. The suggested path was "relaxing the 'input xor captures' rule for bodies".

Proposal:

Drop the mutual-exclusion check in VarStretchContainer::add_var / add_stretch. The enclosure rules already live in the operations: ForLoopOp accepts at most one input, equal to its loop parameter, and every other control-flow op rejects inputs. With that check gone, the builder, compose, DAG composition and substitution, and the QPY reader work unchanged. They already add inputs before captures, and the QPY format doesn't change. ContractIdleWiresInControlFlow should rebuild blocks with `inputs=block.iter_input_vars().

I have a branch with both fixes, tests and a release note, and I'm happy to open a PR.