This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/feat-python-open-modes in repository https://gitbox.apache.org/repos/asf/opendal.git
commit a86d322f9bb58c86e948e848bc0394dc9511ba6d Author: Xuanwo <[email protected]> AuthorDate: Sun Nov 22 23:44:17 2026 +0100 feat(bindings/python): support exclusive create open mode --- bindings/python/docs/index.md | 6 +- bindings/python/python/opendal/operator.pyi | 32 +++++--- bindings/python/python/opendal/options.py | 4 +- bindings/python/src/operator.rs | 69 ++++++++++++----- bindings/python/tests/test_open_modes.py | 114 ++++++++++++++++++++++++++-- dev/src/generate/python.rs | 2 +- 6 files changed, 188 insertions(+), 39 deletions(-) diff --git a/bindings/python/docs/index.md b/bindings/python/docs/index.md index ab8c88fbf6..8a26d19c21 100644 --- a/bindings/python/docs/index.md +++ b/bindings/python/docs/index.md @@ -111,7 +111,7 @@ This again yields b'baz' ``` -Again, note that all reads with OpenDAL return bytes, so specifying a mode of `"r"` will raise an exception. +Again, note that all reads with OpenDAL return bytes. `"r"` and `"rb"` are both binary; wrap the file with `io.TextIOWrapper` if you need text. ### Writing @@ -153,7 +153,9 @@ This again yields: my amazing data ``` -Again, note that all writing happens in bytes and a mode of `"w"` will raise an exception. +Again, note that all writing happens in bytes. `"w"` and `"wb"` are both binary; wrap the file with `io.TextIOWrapper` if you need text. + +`open` supports the binary modes `"r"`, `"w"`, `"a"`, and `"x"`, each with an optional `b` before or after the letter. It rejects text modes such as `"rt"` and update modes such as `"r+"`. ## Async OpenDAL supports async operation on all operator methods. One can simply replace the `Operator` with an `AsyncOperator` and await on method calls. The below example illustrates this behavior: diff --git a/bindings/python/python/opendal/operator.pyi b/bindings/python/python/opendal/operator.pyi index f2136d16fd..85a5336450 100644 --- a/bindings/python/python/opendal/operator.pyi +++ b/bindings/python/python/opendal/operator.pyi @@ -336,9 +336,11 @@ class AsyncOperator: path : str The path to the file. mode : str - `"r"` to read, `"w"` to write (overwrite by default), or `"a"` to append. - An optional `"b"` can appear before or after the letter. All supported - modes are binary. + `"r"` to read, `"w"` to write (overwrite by default), `"a"` to append, + or `"x"` to create a new file. An optional `"b"` can appear before or + after the letter. All supported modes are binary; text modes such as + `"rt"` raise `ValueError`. Wrap the returned file with + `io.TextIOWrapper` to read or write text. **kwargs : dict Additional options for the underlying reader or writer. @@ -346,9 +348,13 @@ class AsyncOperator: ------ ValueError If the mode is invalid or unsupported, including text (`"t"`) and - update (`"+"`) modes, or if append mode is combined with `append=False`. + update (`"+"`) modes, or if the mode conflicts with `append` or + `if_not_exists` in `**kwargs`. + ConditionNotMatch + If create mode (`"x"`) targets an existing file. The failure can + surface from `write()` or `close()`. Unsupported - If the service does not support append mode. + If the service does not support append or `if_not_exists` writes. Returns ------- @@ -1047,9 +1053,11 @@ class Operator: path : str The path to the file. mode : str - `"r"` to read, `"w"` to write (overwrite by default), or `"a"` to append. - An optional `"b"` can appear before or after the letter. All supported - modes are binary. + `"r"` to read, `"w"` to write (overwrite by default), `"a"` to append, + or `"x"` to create a new file. An optional `"b"` can appear before or + after the letter. All supported modes are binary; text modes such as + `"rt"` raise `ValueError`. Wrap the returned file with + `io.TextIOWrapper` to read or write text. **kwargs Additional options for the underlying reader or writer. @@ -1057,9 +1065,13 @@ class Operator: ------ ValueError If the mode is invalid or unsupported, including text (`"t"`) and - update (`"+"`) modes, or if append mode is combined with `append=False`. + update (`"+"`) modes, or if the mode conflicts with `append` or + `if_not_exists` in `**kwargs`. + ConditionNotMatch + If create mode (`"x"`) targets an existing file. The failure can + surface from `write()` or `close()`. Unsupported - If the service does not support append mode. + If the service does not support append or `if_not_exists` writes. Returns ------- diff --git a/bindings/python/python/opendal/options.py b/bindings/python/python/opendal/options.py index 812216e034..08aafebee1 100644 --- a/bindings/python/python/opendal/options.py +++ b/bindings/python/python/opendal/options.py @@ -174,8 +174,8 @@ class OpenKwargs(ReadKwargs, WriteKwargs, total=False): """Keyword arguments for `Operator.open` and `AsyncOperator.open`. The `content_type`, `cache_control`, and `content_disposition` options - apply when writing or appending. Use the operator's `read()` method to - supply response header overrides. + apply when writing, appending, or creating. Use the operator's `read()` + method to supply response header overrides. """ diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs index 9069ad1074..0abe08fe51 100644 --- a/bindings/python/src/operator.rs +++ b/bindings/python/src/operator.rs @@ -36,6 +36,7 @@ enum OpenMode { Read, Write, Append, + Create, } impl OpenMode { @@ -44,20 +45,42 @@ impl OpenMode { "r" | "rb" | "br" => Ok(Self::Read), "w" | "wb" | "bw" => Ok(Self::Write), "a" | "ab" | "ba" => Ok(Self::Append), + "x" | "xb" | "bx" => Ok(Self::Create), _ => Err(PyValueError::new_err(format!( - "unsupported file mode {mode:?}. Use 'r', 'w', or 'a' with an optional 'b' for binary I/O" + "unsupported file mode {mode:?}. Use 'r', 'w', 'a', or 'x' with an optional 'b' for binary I/O" ))), } } fn apply_write_options(&self, options: &mut WriteOptions) -> PyResult<()> { - if matches!(self, Self::Append) { - if options.append == Some(false) { - return Err(PyValueError::new_err( - "append file mode cannot be combined with append=False", - )); + match self { + Self::Read | Self::Write => {} + Self::Append => { + if options.append == Some(false) { + return Err(PyValueError::new_err( + "append file mode cannot be combined with append=False", + )); + } + if options.if_not_exists == Some(true) { + return Err(PyValueError::new_err( + "append file mode cannot be combined with if_not_exists=True", + )); + } + options.append = Some(true); + } + Self::Create => { + if options.if_not_exists == Some(false) { + return Err(PyValueError::new_err( + "create file mode cannot be combined with if_not_exists=False", + )); + } + if options.append == Some(true) { + return Err(PyValueError::new_err( + "create file mode cannot be combined with append=True", + )); + } + options.if_not_exists = Some(true); } - options.append = Some(true); } Ok(()) } @@ -415,9 +438,11 @@ impl Operator { /// path : str /// The path to the file. /// mode : str - /// `"r"` to read, `"w"` to write (overwrite by default), or `"a"` to append. - /// An optional `"b"` can appear before or after the letter. All supported - /// modes are binary. + /// `"r"` to read, `"w"` to write (overwrite by default), `"a"` to append, + /// or `"x"` to create a new file. An optional `"b"` can appear before or + /// after the letter. All supported modes are binary; text modes such as + /// `"rt"` raise `ValueError`. Wrap the returned file with + /// `io.TextIOWrapper` to read or write text. /// **kwargs /// Additional options for the underlying reader or writer. /// @@ -425,9 +450,13 @@ impl Operator { /// ------ /// ValueError /// If the mode is invalid or unsupported, including text (`"t"`) and - /// update (`"+"`) modes, or if append mode is combined with `append=False`. + /// update (`"+"`) modes, or if the mode conflicts with `append` or + /// `if_not_exists` in `**kwargs`. + /// ConditionNotMatch + /// If create mode (`"x"`) targets an existing file. The failure can + /// surface from `write()` or `close()`. /// Unsupported - /// If the service does not support append mode. + /// If the service does not support append or `if_not_exists` writes. /// /// Returns /// ------- @@ -1280,9 +1309,11 @@ impl AsyncOperator { /// path : str /// The path to the file. /// mode : str - /// `"r"` to read, `"w"` to write (overwrite by default), or `"a"` to append. - /// An optional `"b"` can appear before or after the letter. All supported - /// modes are binary. + /// `"r"` to read, `"w"` to write (overwrite by default), `"a"` to append, + /// or `"x"` to create a new file. An optional `"b"` can appear before or + /// after the letter. All supported modes are binary; text modes such as + /// `"rt"` raise `ValueError`. Wrap the returned file with + /// `io.TextIOWrapper` to read or write text. /// **kwargs : dict /// Additional options for the underlying reader or writer. /// @@ -1290,9 +1321,13 @@ impl AsyncOperator { /// ------ /// ValueError /// If the mode is invalid or unsupported, including text (`"t"`) and - /// update (`"+"`) modes, or if append mode is combined with `append=False`. + /// update (`"+"`) modes, or if the mode conflicts with `append` or + /// `if_not_exists` in `**kwargs`. + /// ConditionNotMatch + /// If create mode (`"x"`) targets an existing file. The failure can + /// surface from `write()` or `close()`. /// Unsupported - /// If the service does not support append mode. + /// If the service does not support append or `if_not_exists` writes. /// /// Returns /// ------- diff --git a/bindings/python/tests/test_open_modes.py b/bindings/python/tests/test_open_modes.py index 1ad7987dea..9109687774 100644 --- a/bindings/python/tests/test_open_modes.py +++ b/bindings/python/tests/test_open_modes.py @@ -18,7 +18,7 @@ import pytest import opendal -from opendal.exceptions import Unsupported +from opendal.exceptions import ConditionNotMatch, Unsupported @pytest.fixture @@ -36,6 +36,10 @@ BINARY_MODES = [ ("br", "bw", "ba"), ] +APPEND_MODES = ["a", "ab", "ba"] + +CREATE_MODES = ["x", "xb", "bx"] + @pytest.mark.parametrize(("read", "write", "append"), BINARY_MODES) def test_sync_open_modes(local_operator, read, write, append): @@ -56,6 +60,44 @@ def test_sync_open_modes(local_operator, read, write, append): assert op.read("data") == b"new" [email protected]("mode", APPEND_MODES) +def test_sync_open_append_creates_file(local_operator, mode): + op = local_operator + if not op.capability().write_can_append: + with pytest.raises(Unsupported, match="append"): + op.open("created", mode) + assert not op.exists("created") + return + + with op.open("created", mode) as file: + assert file.writable() + assert not file.readable() + assert not file.seekable() + assert file.write(b"data") == 4 + assert op.read("created") == b"data" + + [email protected]("mode", CREATE_MODES) +def test_sync_open_create_mode(local_operator, mode): + op = local_operator + if not op.capability().write_with_if_not_exists: + with pytest.raises(Unsupported, match="if_not_exists"): + op.open("new", mode) + assert not op.exists("new") + return + + with op.open("new", mode) as file: + assert file.writable() + assert not file.readable() + assert not file.seekable() + assert file.write(b"first") == 5 + assert op.read("new") == b"first" + + with pytest.raises(ConditionNotMatch), op.open("new", mode) as file: + file.write(b"second") + assert op.read("new") == b"first" + + @pytest.mark.asyncio @pytest.mark.parametrize(("read", "write", "append"), BINARY_MODES) async def test_async_open_modes(local_operator, read, write, append): @@ -76,21 +118,69 @@ async def test_async_open_modes(local_operator, read, write, append): assert await op.read("data") == b"new" [email protected] [email protected]("mode", APPEND_MODES) +async def test_async_open_append_creates_file(local_operator, mode): + op = local_operator.to_async_operator() + if not op.capability().write_can_append: + with pytest.raises(Unsupported, match="append"): + await op.open("created", mode) + assert not await op.exists("created") + return + + async with await op.open("created", mode) as file: + assert await file.writable() + assert not await file.readable() + assert not await file.seekable() + assert await file.write(b"data") == 4 + assert await op.read("created") == b"data" + + [email protected] [email protected]("mode", CREATE_MODES) +async def test_async_open_create_mode(local_operator, mode): + op = local_operator.to_async_operator() + if not op.capability().write_with_if_not_exists: + with pytest.raises(Unsupported, match="if_not_exists"): + await op.open("new", mode) + assert not await op.exists("new") + return + + async with await op.open("new", mode) as file: + assert await file.writable() + assert not await file.readable() + assert not await file.seekable() + assert await file.write(b"first") == 5 + assert await op.read("new") == b"first" + + with pytest.raises(ConditionNotMatch): + async with await op.open("new", mode) as file: + await file.write(b"second") + assert await op.read("new") == b"first" + + INVALID_MODES = [ "", "b", "t", "rt", "wt", + "at", + "xt", + "tx", "rbt", "r+", "w+", + "a+", "a+b", "x+", + "xb+", "rw", "rr", + "xx", "rbb", "rbz", + "xbz", "rb\x00", " rb", ] @@ -110,13 +200,23 @@ async def test_async_open_invalid_mode(local_operator, mode): await op.open("data", mode) -def test_sync_open_conflicting_append_option(local_operator): - with pytest.raises(ValueError, match="append=False"): - local_operator.open("data", "ab", append=False) +CONFLICTING_OPEN_OPTIONS = [ + ("ab", {"append": False}, "append=False"), + ("ab", {"if_not_exists": True}, "if_not_exists=True"), + ("xb", {"if_not_exists": False}, "if_not_exists=False"), + ("xb", {"append": True}, "append=True"), +] + + [email protected](("mode", "kwargs", "match"), CONFLICTING_OPEN_OPTIONS) +def test_sync_open_conflicting_options(local_operator, mode, kwargs, match): + with pytest.raises(ValueError, match=match): + local_operator.open("data", mode, **kwargs) @pytest.mark.asyncio -async def test_async_open_conflicting_append_option(local_operator): [email protected](("mode", "kwargs", "match"), CONFLICTING_OPEN_OPTIONS) +async def test_async_open_conflicting_options(local_operator, mode, kwargs, match): op = local_operator.to_async_operator() - with pytest.raises(ValueError, match="append=False"): - await op.open("data", "ab", append=False) + with pytest.raises(ValueError, match=match): + await op.open("data", mode, **kwargs) diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs index 5c258df751..b75db5b274 100644 --- a/dev/src/generate/python.rs +++ b/dev/src/generate/python.rs @@ -561,7 +561,7 @@ fn generate_options_py(workspace_dir: &Path) -> Result<()> { // TypedDict inherits both. kwargs_names.push("OpenKwargs".to_string()); out.push_str( - "\n\nclass OpenKwargs(ReadKwargs, WriteKwargs, total=False):\n \"\"\"Keyword arguments for `Operator.open` and `AsyncOperator.open`.\n\n The `content_type`, `cache_control`, and `content_disposition` options\n apply when writing or appending. Use the operator's `read()` method to\n supply response header overrides.\n \"\"\"\n", + "\n\nclass OpenKwargs(ReadKwargs, WriteKwargs, total=False):\n \"\"\"Keyword arguments for `Operator.open` and `AsyncOperator.open`.\n\n The `content_type`, `cache_control`, and `content_disposition` options\n apply when writing, appending, or creating. Use the operator's `read()`\n method to supply response header overrides.\n \"\"\"\n", ); out.push_str("\n\n__all__ = [\n");
