[Bug]: ParallelGate accepts non-integer num_copies, producing an invalid gate
Description of the issue
cirq.ParallelGate.__init__ only checks that num_copies > 0. It doesn't check that num_copies is an integer, so a float such as 2.5 is accepted and creates a gate in an invalid state. num_qubits() then returns a non-integer, and later calls fail with confusing errors.
How to reproduce the issue
import cirq
g = cirq.ParallelGate(cirq.X, 2.5) # no error raised
print(g.num_qubits()) # 2.5
g.on(*cirq.LineQubit.range(3))
# TypeError: can't multiply sequence by non-int of type 'float'
cirq.decompose_once_with_qubits(g, cirq.LineQubit.range(3))
# ValueError: len(qubits)=3 should be 2.5
Expected behavior
The constructor should reject a non-integer num_copies immediately with a clear error. The docstring already says it raises ValueError for invalid input, so this fits that contract. For example:
ValueError: num_copies must be a positive integer.
Suggested fix
In cirq-core/cirq/ops/parallel_gate.py, validate the type alongside the existing check:
if not isinstance(num_copies, int) or num_copies <= 0:
raise ValueError("num_copies must be a positive integer.")
and add a test case with a float value (e.g. 2.5) to parallel_gate_test.py.
Cirq version 1.8.0.dev0
Hi! I'd like to work on this. Could you please assign it to me?
My approach:
- Add an integer check for
num_copiesinParallelGate.__init__, raising aValueErrorwith a clear message (accepting numpy integers too). - Update the docstring.
- Add tests for a float value and a numpy integer.
Thank You!
@NiranjanRSoorej06 Thank you for this report!
However, this particular problem is not significant enough to be a concern. Technically, yes, ParallelGate.__init__ does not check the type of num_copies at run time. However:
-
The parameter is annotated with the type
num_copies: inton bothParallelGate.__init__andParallelGate.with_num_copies. Static type checkers (e.g., Mypy) will flag code that uses the wrong type. -
A
ParallelGatewith a non-integernum_copiescannot silently corrupt a circuit, unitary matrix, or simulation. Every downstream operation will fail immediately withTypeErrors orValueErrors if given a float for this parameter.
Other gates in cirq.ops follow the same pattern of relying on type annotations rather than explicit isinstance checks in __init__. Given this, and the low risk in practical terms, I feel it's better to close this as a "wont-fix" situation.