From 038f4d640da73d6b702f20ac781f2ef9a08546fc Mon Sep 17 00:00:00 2001 From: Agustin Borgna Date: Thu, 9 Nov 2023 16:58:45 +0000 Subject: [PATCH] feat!: non-locking python conversion calls `from_tket1` and `to_tket1` now receive the Global Interpreter Lock (GIL) as a parameter rather than adquiring it internally. The locking methods are kept as utility functions. BREAKING CHANGE: Renamed `SerialCircuit::to_tket1` to `to_tket1_with_gil`, and `_from_tket1` to `from_tket1_with_gil`. --- src/pytket.rs | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/src/pytket.rs b/src/pytket.rs index 03b7995..df56c68 100644 --- a/src/pytket.rs +++ b/src/pytket.rs @@ -4,24 +4,34 @@ use crate::circuit_json::SerialCircuit; use pyo3::prelude::*; use pythonize::{depythonize, pythonize}; -// #[pymethods] impl SerialCircuit { /// Create a new `SerialCircuit` from a `pytket.Circuit`. - pub fn _from_tket1(c: Py) -> Self { - Python::with_gil(|py| depythonize(c.call_method0(py, "to_dict").unwrap().as_ref(py))) - .unwrap() + pub fn from_tket1(circ: &PyAny) -> PyResult { + let circ = depythonize(circ.call_method0("to_dict").unwrap())?; + Ok(circ) + } + + /// Create a new `SerialCircuit` from a `pytket.Circuit`. + /// + /// Utility function that calls [`SerialCircuit::from_tket1`] after acquiring the GIL. + pub fn from_tket1_with_gil(circ: Py) -> PyResult { + Python::with_gil(|py| Self::from_tket1(circ.as_ref(py))) } /// Convert a `SerialCircuit` to a `pytket.Circuit`. - pub fn to_tket1(&self) -> PyResult> { - Python::with_gil(|py| { - let dict = pythonize(py, self).unwrap(); - let circ_module = PyModule::import(py, "pytket.circuit")?; + pub fn to_tket1<'py>(&self, py: Python<'py>) -> PyResult<&'py PyAny> { + let dict = pythonize(py, self).unwrap(); + let circ_module = PyModule::import(py, "pytket.circuit")?; - Ok(circ_module - .getattr("Circuit")? - .call_method1("from_dict", (dict,))? - .into()) - }) + circ_module + .getattr("Circuit")? + .call_method1("from_dict", (dict,)) + } + + /// Convert a `SerialCircuit` to a `pytket.Circuit`. + /// + /// Utility function that calls [`SerialCircuit::to_tket1`] after acquiring the GIL. + pub fn to_tket1_with_gil(&self) -> PyResult> { + Python::with_gil(|py| self.to_tket1(py).map(|x| x.into())) } }