Skip to content

Commit 0f8701f

Browse files
dstrain115mhucka
andauthored
Add more informative message for improper cirq.qasm arguments. (#6905)
- Qubits is an optional parameter, only used for certain types (usually `cirq.Gate`), and, if supplied elsewhere, can raise an error. - Print out a more informative message. Fixes: #6016 Co-authored-by: Michael Hucka <[email protected]>
1 parent 59ab27a commit 0f8701f

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

cirq-core/cirq/protocols/qasm.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def qasm(
151151
involving qubits that the operation wouldn't otherwise know about.
152152
qubits: A list of qubits that the value is being applied to. This is
153153
needed for `cirq.Gate` values, which otherwise wouldn't know what
154-
qubits to talk about.
154+
qubits to talk about. It should generally not be specified otherwise.
155155
default: A default result to use if the value doesn't have a
156156
`_qasm_` method or that method returns `NotImplemented` or `None`.
157157
If not specified, non-decomposable values cause a `TypeError`.
@@ -172,10 +172,16 @@ def qasm(
172172
kwargs: Dict[str, Any] = {}
173173
if args is not None:
174174
kwargs['args'] = args
175+
# pylint: disable=not-callable
175176
if qubits is not None:
176177
kwargs['qubits'] = tuple(qubits)
177-
# pylint: disable=not-callable
178-
result = method(**kwargs)
178+
try:
179+
result = method(**kwargs)
180+
except TypeError as error:
181+
raise TypeError(
182+
"cirq.qasm does not expect qubits or args to be specified"
183+
f"for the given value of type {type(val)}."
184+
) from error
179185
# pylint: enable=not-callable
180186
if result is not None and result is not NotImplemented:
181187
return result

cirq-core/cirq/protocols/qasm_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ def test_qasm():
5454
assert cirq.qasm(ExpectsArgsQubits(), args=cirq.QasmArgs(), qubits=()) == 'text'
5555

5656

57+
def test_qasm_qubits_improperly_supplied():
58+
with pytest.raises(TypeError, match="does not expect qubits or args to be specified"):
59+
_ = cirq.qasm(cirq.Circuit(), qubits=[cirq.LineQubit(1)])
60+
61+
5762
def test_qasm_args_formatting():
5863
args = cirq.QasmArgs()
5964
assert args.format_field(0.01, '') == '0.01'

0 commit comments

Comments
 (0)