3
$\begingroup$

Given a circuit, if one wishes to add a gate, it is done through a line like the one below

mycircuit.cx(0, 1)

Here, we have added a control-X gate on the 0 and 1 qubits. This is probably a Python question but how can one do this given the string 'cx' and integers 0 and 1 i.e. without manually typing them?

I tried using https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string but getattr did not work for me.

from qiskit import QuantumCircuit
circ = QuantumCircuit(2)
circ.draw()
a = ('cx', 0, 1)
circ = getattr(circ, a[0])(a[1], a[2])
circ.draw()
$\endgroup$
2
  • $\begingroup$ How did you call getattr? getattr(mycircuit, 'cx')(0, 1) works for me in this case. $\endgroup$ Commented Sep 10, 2020 at 17:44
  • $\begingroup$ @VictoryOmole I have added the code I tried. The first circ.draw() works fine but the second produces an error. I expected the second time that it would draw the circuit with a gate. $\endgroup$
    – Wutend
    Commented Sep 10, 2020 at 18:35

1 Answer 1

2
$\begingroup$

You are getting AttributeError: 'InstructionSet' object has no attribute 'draw' because getattr doesn't return a QuantumCircuit. It returns an InstructionSet, which doesn't have a draw() method.

from qiskit import QuantumCircuit
circuit = QuantumCircuit(2)
print(type(circuit)) # prints <class 'qiskit.circuit.quantumcircuit.QuantumCircuit'>
circuit.draw()
a = ('cx', 0, 1)
circuit = getattr(circuit, a[0])(a[1], a[2])
print(type(circuit)) # prints <class 'qiskit.circuit.instructionset.InstructionSet'>

Removing the assignment of circuit to what is returned from getatrr should get rid of the error.

from qiskit import QuantumCircuit
circuit = QuantumCircuit(2)
circuit.draw()
a = ('cx', 0, 1)
getattr(circuit, a[0])(a[1], a[2])
circuit.draw()
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.