Skip to content

Commit

Permalink
Merge pull request #48 from dimastbk/support-pathlike
Browse files Browse the repository at this point in the history
feat: add support PathLike to from_path
  • Loading branch information
dimastbk committed Jan 6, 2024
2 parents b0bedb8 + 381f524 commit a0b5b30
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
2 changes: 1 addition & 1 deletion python/python_calamine/_python_calamine.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 13 additions & 2 deletions src/types/workbook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -88,8 +89,18 @@ impl CalamineWorkbook {

#[classmethod]
#[pyo3(name = "from_path")]
fn py_from_path(_cls: &PyType, py: Python<'_>, path: &str) -> PyResult<Self> {
py.allow_threads(|| Self::from_path(path))
fn py_from_path(_cls: &PyType, py: Python<'_>, path: PyObject) -> PyResult<Self> {
if let Ok(string_ref) = path.downcast::<PyString>(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::<PathBuf>(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")]
Expand Down
12 changes: 9 additions & 3 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit a0b5b30

Please sign in to comment.