Skip to content

Commit 3e55e5c

Browse files
authored
Use fresh env for qsharp.run with Python interop functions wrapping Q# operations (#2255)
This matches the behavior used for other places when a fresh simulator instance is paired with a fresh environment for isolated execution. Fixes #2253
1 parent bcce021 commit 3e55e5c

File tree

2 files changed

+18
-21
lines changed

2 files changed

+18
-21
lines changed

compiler/qsc/src/interpret.rs

+3-20
Original file line numberDiff line numberDiff line change
@@ -567,8 +567,8 @@ impl Interpreter {
567567
})
568568
}
569569

570-
// Invokes the given callable with the given arguments using the current environment and compilation but with a fresh
571-
// simulator configured with the given noise, if any.
570+
// Invokes the given callable with the given arguments using the current compilation but with a fresh
571+
// environment and simulator configured with the given noise, if any.
572572
pub fn invoke_with_noise(
573573
&mut self,
574574
receiver: &mut impl Receiver,
@@ -580,24 +580,7 @@ impl Interpreter {
580580
Some(noise) => SparseSim::new_with_noise(&noise),
581581
None => SparseSim::new(),
582582
};
583-
qsc_eval::invoke(
584-
self.package,
585-
self.classical_seed,
586-
&self.fir_store,
587-
&mut self.env,
588-
&mut sim,
589-
receiver,
590-
callable,
591-
args,
592-
)
593-
.map_err(|(error, call_stack)| {
594-
eval_error(
595-
self.compiler.package_store(),
596-
&self.fir_store,
597-
call_stack,
598-
error,
599-
)
600-
})
583+
self.invoke_with_sim(&mut sim, receiver, callable, args)
601584
}
602585

603586
/// Runs the given entry expression on a new instance of the environment and simulator,

pip/tests/test_qsharp.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,21 @@ def test_run_with_result(capsys) -> None:
431431

432432
def test_run_with_result_from_callable(capsys) -> None:
433433
qsharp.init()
434-
qsharp.eval('operation Foo() : Result { Message("Hello, world!"); Zero }')
434+
qsharp.eval(
435+
'operation Foo() : Result { Message("Hello, world!"); use q = Qubit(); M(q) }'
436+
)
437+
results = qsharp.run(qsharp.code.Foo, 3)
438+
assert results == [qsharp.Result.Zero, qsharp.Result.Zero, qsharp.Result.Zero]
439+
stdout = capsys.readouterr().out
440+
assert stdout == "Hello, world!\nHello, world!\nHello, world!\n"
441+
442+
443+
def test_run_with_result_from_callable_while_global_qubits_allocated(capsys) -> None:
444+
qsharp.init()
445+
qsharp.eval("use q = Qubit();")
446+
qsharp.eval(
447+
'operation Foo() : Result { Message("Hello, world!"); use q = Qubit(); M(q) }'
448+
)
435449
results = qsharp.run(qsharp.code.Foo, 3)
436450
assert results == [qsharp.Result.Zero, qsharp.Result.Zero, qsharp.Result.Zero]
437451
stdout = capsys.readouterr().out

0 commit comments

Comments
 (0)