Skip to content

Commit a59e8b8

Browse files
authored
Avoid mutating user backend config (#1076)
1 parent c3bc25a commit a59e8b8

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

qumat/qumat.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,12 @@ def __init__(self, backend_config):
6060
"Please provide a dictionary with backend-specific options "
6161
)
6262

63-
self.backend_config = backend_config
64-
self.backend_name = backend_config["backend_name"]
63+
self.backend_config = backend_config.copy()
64+
self.backend_name = self.backend_config["backend_name"]
6565
self.backend_module = import_module(
6666
f".{self.backend_name}_backend", package="qumat"
6767
)
68-
self.backend = self.backend_module.initialize_backend(backend_config)
68+
self.backend = self.backend_module.initialize_backend(self.backend_config)
6969
self.circuit = None
7070
self.num_qubits = None
7171
self.parameters = {}

testing/qumat/test_parameter_binding.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,35 @@ def test_partially_bound_parameters_error(self, backend_name):
220220
# This should raise ValueError
221221
with pytest.raises(ValueError, match="unbound parameters"):
222222
qumat.execute_circuit(parameter_values={"theta0": math.pi})
223+
224+
@pytest.mark.parametrize("backend_name", TESTING_BACKENDS)
225+
def test_execute_circuit_does_not_mutate_backend_config(self, backend_name):
226+
"""Test that execute_circuit does not mutate the user's backend_config across all backends."""
227+
backend_config = get_backend_config(backend_name).copy()
228+
original_config = backend_config.copy()
229+
230+
qumat = QuMat(backend_config)
231+
qumat.create_empty_circuit(num_qubits=1)
232+
qumat.apply_rx_gate(0, "theta")
233+
qumat.execute_circuit(parameter_values={"theta": math.pi})
234+
235+
assert backend_config == original_config, (
236+
f"backend_config was mutated in {backend_name}; "
237+
"parameter_values or other keys must not be added."
238+
)
239+
240+
@pytest.mark.parametrize("backend_name", TESTING_BACKENDS)
241+
def test_get_final_state_vector_does_not_mutate_backend_config(self, backend_name):
242+
"""Test that get_final_state_vector does not mutate the user's backend_config across all backends."""
243+
backend_config = get_backend_config(backend_name).copy()
244+
original_config = backend_config.copy()
245+
246+
qumat = QuMat(backend_config)
247+
qumat.create_empty_circuit(num_qubits=1)
248+
qumat.apply_rx_gate(0, "theta")
249+
qumat.bind_parameters({"theta": math.pi / 2})
250+
qumat.get_final_state_vector()
251+
252+
assert backend_config == original_config, (
253+
f"backend_config was mutated by get_final_state_vector in {backend_name}."
254+
)

0 commit comments

Comments
 (0)