# Qiskit: Add a standard gate to circuit from a string

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()

• How did you call getattr? getattr(mycircuit, 'cx')(0, 1) works for me in this case. – Victory Omole Sep 10 '20 at 17:44
• @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. – Wutend Sep 10 '20 at 18:35

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()