diff --git a/qiskit/circuit/library/blueprintcircuit.py b/qiskit/circuit/library/blueprintcircuit.py index 958b1b65c2db..7d339f11ae3e 100644 --- a/qiskit/circuit/library/blueprintcircuit.py +++ b/qiskit/circuit/library/blueprintcircuit.py @@ -100,6 +100,16 @@ def append(self, instruction, qargs=None, cargs=None): self._build() return super().append(instruction, qargs, cargs) + def compose(self, other, qubits=None, clbits=None, front=False, inplace=False): + if self._data is None: + self._build() + return super().compose(other, qubits, clbits, front, inplace) + + def inverse(self): + if self._data is None: + self._build() + return super().inverse() + def __len__(self): return len(self.data) diff --git a/releasenotes/notes/build-blueprintcircuit-before-inverse-8ef85f6389588fe0.yaml b/releasenotes/notes/build-blueprintcircuit-before-inverse-8ef85f6389588fe0.yaml new file mode 100644 index 000000000000..a8be8850b7b3 --- /dev/null +++ b/releasenotes/notes/build-blueprintcircuit-before-inverse-8ef85f6389588fe0.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Calling inverse or compose on a ``BlueprintCircuit`` could fail + if ``_data`` was not yet populated. This has been fixed by asserting + a call on ``_build`` method. diff --git a/test/python/circuit/library/test_blueprintcircuit.py b/test/python/circuit/library/test_blueprintcircuit.py index 36e42f640285..701085541e00 100644 --- a/test/python/circuit/library/test_blueprintcircuit.py +++ b/test/python/circuit/library/test_blueprintcircuit.py @@ -15,7 +15,7 @@ import unittest from qiskit.test.base import QiskitTestCase -from qiskit.circuit import QuantumRegister, Parameter +from qiskit.circuit import QuantumRegister, Parameter, QuantumCircuit from qiskit.circuit.library import BlueprintCircuit @@ -90,7 +90,7 @@ def test_calling_attributes_works(self): self.assertGreater(len(circuit._data), 0) methods = ['qasm', 'count_ops', 'num_connected_components', 'num_nonlocal_gates', - 'depth', '__len__', 'copy'] + 'depth', '__len__', 'copy', 'inverse'] for method in methods: with self.subTest(method=method): circuit = MockBlueprint(3) @@ -102,6 +102,20 @@ def test_calling_attributes_works(self): _ = circuit[2] self.assertGreater(len(circuit._data), 0) + def test_compose_works(self): + """Test that the circuit is constructed when compose is called.""" + qc = QuantumCircuit(3) + qc.x([0, 1, 2]) + circuit = MockBlueprint(3) + circuit.compose(qc, inplace=True) + + reference = QuantumCircuit(3) + reference.rx(list(circuit.parameters)[0], 0) + reference.h([0, 1, 2]) + reference.x([0, 1, 2]) + + self.assertEqual(reference, circuit) + if __name__ == '__main__': unittest.main()