# Can any Qiskit circuit be converted to a gate?

I am trying to convert the following qiskit QuantumCircuit to a gate using to_gate() method.

from qiskit import QuantumCircuit
from qiskit.opflow import I, X, Y, Z

# construct one qubit circuit
circuit = QuantumCircuit(1, name='R')

# append gates as Pauli strings
circuit.append(0.5*I - 1j*np.sqrt(1-0.5**2)*Y, [0])

circuit.to_gate()


But I end up getting the following error.

QiskitError: 'One or more instructions cannot be converted to a gate. "circuit-304" is not a gate instruction'


Are there limitations to the use of to_gate()? Bing AI tells me

All instructions in the circuit must be gates.

But I cannot find a reference to this, and if that indeed must be true, I do not know how to enforce this condition.

Qiskit distinguishes operations into unitary operations ("gates") and operations that are not necessarily unitary ("instructions"). In your workflow you end up with an qiskit.circuit.Instruction object on the circuit, therefore it cannot be converted to a qiskit.circuit.Gate.

Since you're trying to construct a gate essentially from a matrix, you could instead use

U = (0.5*I - 1j*np.sqrt(1-0.5**2)*Y).to_matrix()
circuit.unitary(U, [0])
gate = circuit.to_gate()


Alternatively, you could construct the unitary directly

from qiskit.extensions import UnitaryGate

gate = UnitaryGate(U)  # U from above


@Cryoris' answer resolved the issue I had. Since qiskit.opflow is getting depreciated, here's another solution using qiskit.quantum_info.SparsePauliOp.

from qiskit.quantum_info import SparsePauliOp

circuit = QuantumCircuit(1, name='R')

theta=0.5
operator = SparsePauliOp(["I", "Y"], coeffs = [theta, -1j*np.sqrt(1-theta**2)]).to_operator()

circuit.append(operator, [0])

circuit.to_gate()