Skip to content

Commit

Permalink
feat: Support pathlib.Path as input to open
Browse files Browse the repository at this point in the history
  • Loading branch information
nvictus committed Apr 12, 2024
1 parent fd4fb67 commit fa8f099
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions pybigtools/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2123,6 +2123,13 @@ fn open(py: Python, path_url_or_file_like: PyObject, mode: Option<String>) -> Py
return open_path_or_url(py, string_ref.to_str().unwrap().to_owned(), iswrite);
}

// If pathlib.Path, convert to string and try to open
let path_class = py.import("pathlib")?.getattr("Path")?;
if path_url_or_file_like.as_ref(py).is_instance(path_class)? {
let path_str = path_url_or_file_like.as_ref(py).str()?.to_str()?;
return open_path_or_url(py, path_str.to_owned(), iswrite);
}

if iswrite {
return Err(PyErr::new::<exceptions::PyValueError, _>(format!(
"Writing only supports file names",
Expand Down
6 changes: 6 additions & 0 deletions pybigtools/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ def test_open_close():
b.close()
assert pytest.raises(pybigtools.BBIFileClosed, b.chroms)

# Works with pathlib.Path
path = REPO_ROOT / "bigtools/resources/test/valid.bigWig"
b = pybigtools.open(path, "r")
b.close()
assert pytest.raises(pybigtools.BBIFileClosed, b.chroms)

# Files are closed when exiting a context manager
with pybigtools.open(path, "r") as b:
pass
Expand Down

0 comments on commit fa8f099

Please sign in to comment.