Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion crates/circuit/src/converters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@ impl<'a, 'py> FromPyObject<'a, 'py> for QuantumCircuitData<'py> {
Ok(QuantumCircuitData {
data: data_borrowed.borrow().inner.clone(),
name: ob.getattr(intern!(py, "name"))?.extract()?,
metadata: ob.getattr(intern!(py, "metadata")).ok(),
metadata: ob.getattr(intern!(py, "metadata")).ok().and_then(|m| {
if m.is_none() {
None
} else {
m.call_method0(intern!(py, "copy")).ok()
}
}),
transpile_layout: ob.getattr(intern!(py, "layout")).ok(),
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This place (Rust-space extraction of the fields from a Python-space object) is most likely not the right place to put this - that's going to cause the copy in the wrong places, I think. It so happens that circuit_to_dag calls this right now (I think?), but that's just one of the users.

})
}
Expand Down
2 changes: 1 addition & 1 deletion qiskit/converters/dag_to_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def dag_to_circuit(dag, copy_operations=True):
name=name,
global_phase=dag.global_phase,
)
circuit.metadata = dag.metadata or {}
circuit.metadata = dag.metadata.copy() if dag.metadata else {}
circuit._data = circuit_data
circuit._duration = dag._duration
circuit._unit = dag._unit
Expand Down
13 changes: 13 additions & 0 deletions test/python/converters/test_circuit_to_dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,19 @@ def test_wire_order_failures(self):
with self.assertRaisesRegex(ValueError, "does not contain exactly the same"):
circuit_to_dag(qc, clbit_order=cr[[0, 1, 1]])

def test_circuit_to_dag_metadata_is_copied(self):
"""circuit_to_dag should return a DAG with a copy of the metadata, not a reference."""
qc = QuantumCircuit(1, metadata={"key": "original"})
dag = circuit_to_dag(qc)
self.assertIsNot(dag.metadata, qc.metadata)
self.assertEqual(dag.metadata, qc.metadata)

def test_dag_to_circuit_metadata_is_copied(self):
"""dag_to_circuit should return a circuit with a copy of the metadata, not a reference."""
qc = QuantumCircuit(1, metadata={"key": "original"})
result = dag_to_circuit(circuit_to_dag(qc))
self.assertIsNot(result.metadata, qc.metadata)


if __name__ == "__main__":
unittest.main(verbosity=2)