Path: blob/main/crates/polars-utils/src/python_convert_registry.rs
8394 views
use std::any::Any;1use std::ops::Deref;2use std::sync::{Arc, LazyLock, RwLock};34use pyo3::types::PyAnyMethods;5use pyo3::{Py, PyAny, PyResult, Python};67pub type FromPython = Arc<dyn Fn(Py<PyAny>) -> PyResult<Box<dyn Any>> + Send + Sync>;8pub type ToPython = Arc<dyn for<'a> Fn(&'a dyn Any) -> PyResult<Py<PyAny>> + Send + Sync>;910#[derive(Clone)]11pub struct FromPythonConvertRegistry {12pub file_provider_result: FromPython,13pub series: FromPython,14pub df: FromPython,15pub dsl_plan: FromPython,16pub schema: FromPython,17}1819#[derive(Clone)]20pub struct ToPythonConvertRegistry {21pub df: ToPython,22pub series: ToPython,23pub dsl_plan: ToPython,24pub schema: ToPython,25}2627impl ToPythonConvertRegistry {28/// Convert a Rust `DataFrame` to a Python `pl.DataFrame` object.29pub fn df_to_wrapped_pydf(&self, df: &dyn Any) -> PyResult<Py<PyAny>> {30static WRAP_DF: LazyLock<Py<PyAny>> = LazyLock::new(|| {31Python::attach(|py| {32py.import("polars._utils.wrap")33.unwrap()34.getattr("wrap_df")35.unwrap()36.unbind()37})38});3940let pydf = (self.df)(df)?;4142Python::attach(|py| WRAP_DF.call1(py, (pydf,)))43}44}4546#[derive(Clone)]47pub struct PythonConvertRegistry {48pub from_py: FromPythonConvertRegistry,49pub to_py: ToPythonConvertRegistry,50}5152impl PythonConvertRegistry {53pub fn py_file_provider_args_dataclass(&self) -> &'static Py<PyAny> {54static CLS: LazyLock<Py<PyAny>> = LazyLock::new(|| {55Python::attach(|py| {56py.import("polars.io.partition")57.unwrap()58.getattr("FileProviderArgs")59.unwrap()60.unbind()61})62});6364&CLS65}66}6768static PYTHON_CONVERT_REGISTRY: LazyLock<RwLock<Option<PythonConvertRegistry>>> =69LazyLock::new(Default::default);7071pub fn get_python_convert_registry() -> PythonConvertRegistry {72PYTHON_CONVERT_REGISTRY73.deref()74.read()75.unwrap()76.as_ref()77.unwrap()78.clone()79}8081pub fn register_converters(registry: PythonConvertRegistry) {82*PYTHON_CONVERT_REGISTRY.deref().write().unwrap() = Some(registry);83}848586