Skip to content

Commit

Permalink
pyembed: adjust lifetime return value from acquire_gil()
Browse files Browse the repository at this point in the history
See the inline comments for more.

Closes #345.
  • Loading branch information
indygreg committed Dec 30, 2020
1 parent b4d3e09 commit 22ebf7d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
3 changes: 3 additions & 0 deletions docs/history.rst
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ Bug Fixes
to be equivalent to the parent package to partially emulate CPython's
behavior. See :ref:`oxidized_importer_dunder_init_module_names` for more.
(#317)
* The lifetime of ``pyembed::MainPythonInterpreter.acquire_gil()``'s return
value has been adjusted so the Rust compiler will refuse to compile code
that could crash due to attempting to use a finalized interpreter. (#345)

New Features
^^^^^^^^^^^^
Expand Down
7 changes: 6 additions & 1 deletion pyembed/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,12 @@ impl<'python, 'interpreter, 'resources> MainPythonInterpreter<'python, 'interpre
}

/// Ensure the Python GIL is acquired, returning a handle on the interpreter.
pub fn acquire_gil(&mut self) -> Result<Python<'python>, &'static str> {
///
/// The returned value has a lifetime of the `MainPythonInterpreter`
/// instance. This is because `MainPythonInterpreter.drop()` finalizes
/// the interpreter. The borrow checker should refuse to compile code
/// where the returned `Python` outlives `self`.
pub fn acquire_gil(&mut self) -> Result<Python<'_>, &'static str> {
match self.interpreter_state {
InterpreterState::NotStarted => {
return Err("interpreter not initialized");
Expand Down
13 changes: 5 additions & 8 deletions pyembed/src/test/main_python_interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,12 @@ use {

rusty_fork_test! {
#[test]
#[should_panic]
fn test_instantiate_interpreter() {
let py = {
let mut config = OxidizedPythonInterpreterConfig::default();
config.interpreter_config.parse_argv = Some(false);
config.set_missing_path_configuration = false;
let mut interp = MainPythonInterpreter::new(config).unwrap();
interp.acquire_gil().unwrap()
};
let mut config = OxidizedPythonInterpreterConfig::default();
config.interpreter_config.parse_argv = Some(false);
config.set_missing_path_configuration = false;
let mut interp = MainPythonInterpreter::new(config).unwrap();
let py = interp.acquire_gil().unwrap();
py.import("sys").unwrap();
}
}

0 comments on commit 22ebf7d

Please sign in to comment.