Path: blob/main/crates/polars-plan/src/plans/python/utils.rs
8354 views
use polars_core::error::{PolarsResult, polars_err};1use polars_core::frame::DataFrame;2use polars_core::schema::SchemaRef;3use polars_ffi::version_0::SeriesExport;4use polars_utils::python_convert_registry::get_python_convert_registry;5use pyo3::intern;6use pyo3::prelude::*;78pub fn python_df_to_rust(py: Python, df: Bound<PyAny>) -> PolarsResult<DataFrame> {9let err = |_| polars_err!(ComputeError: "expected a polars.DataFrame; got {}", df);10let pydf = df.getattr(intern!(py, "_df")).map_err(err)?;1112// Try to convert without going through FFI first.13let converted = get_python_convert_registry().from_py.df;14if let Ok(any_df) = converted(pydf.clone().unbind()) {15return Ok(*any_df.downcast::<DataFrame>().unwrap());16}1718// Might be foreign Polars, try with FFI.19let width = pydf.call_method0(intern!(py, "width")).unwrap();20let width = width.extract::<usize>().unwrap();2122// Don't resize the Vec<> so that the drop of the SeriesExport will not be caleld.23let mut export: Vec<SeriesExport> = Vec::with_capacity(width);24let location = export.as_mut_ptr();2526let _ = pydf27.call_method1(intern!(py, "_export_columns"), (location as usize,))28.unwrap();2930unsafe { polars_ffi::version_0::import_df(location, width) }31}3233pub(crate) fn python_schema_to_rust(py: Python, schema: Bound<PyAny>) -> PolarsResult<SchemaRef> {34let err = |_| polars_err!(ComputeError: "expected a polars.Schema; got {}", schema);35let df = schema.call_method0("to_frame").map_err(err)?;36python_df_to_rust(py, df).map(|df| df.schema().clone())37}383940