Skip to content

Commit

Permalink
feat!: non-locking python conversion calls (#25)
Browse files Browse the repository at this point in the history
`from_tket1` and `to_tket1` now receive the Global Interpreter Lock
(GIL) as a parameter rather than adquiring it internally.
This is more composable in cases where we want to reuse the GIL.

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`.
  • Loading branch information
aborgna-q authored Nov 9, 2023
1 parent 318816f commit 494f0c5
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions src/pytket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PyAny>) -> Self {
Python::with_gil(|py| depythonize(c.call_method0(py, "to_dict").unwrap().as_ref(py)))
.unwrap()
pub fn from_tket1(circ: &PyAny) -> PyResult<Self> {
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<PyAny>) -> PyResult<Self> {
Python::with_gil(|py| Self::from_tket1(circ.as_ref(py)))
}

/// Convert a `SerialCircuit` to a `pytket.Circuit`.
pub fn to_tket1(&self) -> PyResult<Py<PyAny>> {
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<Py<PyAny>> {
Python::with_gil(|py| self.to_tket1(py).map(|x| x.into()))
}
}

0 comments on commit 494f0c5

Please sign in to comment.