diff --git a/python/python_calamine/_python_calamine.pyi b/python/python_calamine/_python_calamine.pyi index 37e0e03..c4e0402 100644 --- a/python/python_calamine/_python_calamine.pyi +++ b/python/python_calamine/_python_calamine.pyi @@ -76,7 +76,7 @@ class CalamineWorkbook: - IO (must imlpement read/seek methods). """ @classmethod - def from_path(cls, path: str) -> "CalamineWorkbook": + def from_path(cls, path: str | PathLike) -> "CalamineWorkbook": """Reading file from path. Parameters diff --git a/src/types/workbook.rs b/src/types/workbook.rs index dd1dc00..fe80878 100644 --- a/src/types/workbook.rs +++ b/src/types/workbook.rs @@ -3,6 +3,7 @@ use std::io::{BufReader, Cursor, Read}; use std::path::PathBuf; use calamine::{open_workbook_auto, open_workbook_auto_from_rs, Error, Reader, Sheets}; +use pyo3::exceptions::PyTypeError; use pyo3::prelude::*; use pyo3::types::{PyString, PyType}; use pyo3_file::PyFileLikeObject; @@ -88,8 +89,18 @@ impl CalamineWorkbook { #[classmethod] #[pyo3(name = "from_path")] - fn py_from_path(_cls: &PyType, py: Python<'_>, path: &str) -> PyResult { - py.allow_threads(|| Self::from_path(path)) + fn py_from_path(_cls: &PyType, py: Python<'_>, path: PyObject) -> PyResult { + if let Ok(string_ref) = path.downcast::(py) { + let path = string_ref.to_string_lossy().to_string(); + return py.allow_threads(|| Self::from_path(&path)); + } + + if let Ok(string_ref) = path.extract::(py) { + let path = string_ref.to_string_lossy().to_string(); + return py.allow_threads(|| Self::from_path(&path)); + } + + Err(PyTypeError::new_err("")) } #[pyo3(name = "get_sheet_by_name")] diff --git a/tests/test_base.py b/tests/test_base.py index d8e6b25..1b1c1ec 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -219,13 +219,19 @@ def test_nrows(): @pytest.mark.parametrize( - "obj", + "path", [ + PATH / "base.xlsx", (PATH / "base.xlsx").as_posix(), ], ) -def test_path(obj): - CalamineWorkbook.from_path(obj) +def test_path(path): + CalamineWorkbook.from_path(path) + + +def test_path_error(): + with pytest.raises(TypeError): + CalamineWorkbook.from_path(object()) @pytest.mark.parametrize(