Tpt commented on code in PR #9439:
URL: https://github.com/apache/arrow-rs/pull/9439#discussion_r2954406493
##########
arrow-pyarrow/src/lib.rs:
##########
@@ -606,21 +595,52 @@ impl FromPyArrow for Table {
/// Convert a [`Table`] into `pyarrow.Table`.
impl IntoPyArrow for Table {
fn into_pyarrow(self, py: Python) -> PyResult<Bound<PyAny>> {
- let module = py.import(intern!(py, "pyarrow"))?;
- let class = module.getattr(intern!(py, "Table"))?;
-
let py_batches = PyList::new(py,
self.record_batches.into_iter().map(PyArrowType))?;
let py_schema = PyArrowType(Arc::unwrap_or_clone(self.schema));
let kwargs = PyDict::new(py);
kwargs.set_item("schema", py_schema)?;
- let reader = class.call_method("from_batches", (py_batches,),
Some(&kwargs))?;
+ let reader = table_class(py)?.call_method("from_batches",
(py_batches,), Some(&kwargs))?;
Ok(reader)
}
}
+fn array_class(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
+ static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
+ TYPE.import(py, "pyarrow", "Array")
Review Comment:
> I thought that Python cached the import anyways on the C side, so it was
unnecessary to do it on the pyo3 side
Yes, cpython does not reinitialize the module each time (I guess this what
you mean by "cache the import", sorry for the dumb answer if it's not the
case). However, doing `py.import(my_module)?.getattr(my_class)?` requires at
least two map lookups, one to fetch the module object from its path and one to
fetch the class from the module. The cache allows to skip these lookups and
directly use the type object. If the GIL is enabled there is no synchronization
cost to do that (`PyOnceLock` use the GIL as lock).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]