This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 514778e646 feat(bindings/python): support exclusive create mode in 
open (#8749)
514778e646 is described below

commit 514778e646e14a69dcca80e25cc502924f3cf1a4
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 07:15:10 2026 +0800

    feat(bindings/python): support exclusive create mode in open (#8749)
    
    * feat(bindings/python): support exclusive create open mode
    
    * fix(bindings/python): preserve open mode condition errors
---
 bindings/python/docs/index.md               |   8 +-
 bindings/python/python/opendal/operator.pyi |  32 ++++--
 bindings/python/python/opendal/options.py   |   4 +-
 bindings/python/src/errors.rs               |  12 +++
 bindings/python/src/file.rs                 |   6 +-
 bindings/python/src/operator.rs             |  69 ++++++++++---
 bindings/python/tests/test_open_modes.py    | 155 ++++++++++++++++++++++++++--
 dev/src/generate/python.rs                  |   2 +-
 8 files changed, 246 insertions(+), 42 deletions(-)

diff --git a/bindings/python/docs/index.md b/bindings/python/docs/index.md
index ab8c88fbf6..d7f216f558 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 synchronous 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 synchronous 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:
@@ -183,3 +185,5 @@ async def main():
 
 asyncio.run(main())
 ```
+
+`AsyncFile` reads and writes bytes. Encode text with `str.encode()` and decode 
reads with `bytes.decode()`; `io.TextIOWrapper` only works with the blocking 
`File`.
diff --git a/bindings/python/python/opendal/operator.pyi 
b/bindings/python/python/opendal/operator.pyi
index f2136d16fd..38918d5e28 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`. `AsyncFile` writes bytes, so encode text
+            with `str.encode()` and decode reads with `bytes.decode()`.
         **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()`, `flush()`, 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/errors.rs b/bindings/python/src/errors.rs
index 6f36f9b855..78532e558b 100644
--- a/bindings/python/src/errors.rs
+++ b/bindings/python/src/errors.rs
@@ -115,6 +115,18 @@ pub fn format_pyerr(err: ocore::Error) -> PyErr {
     format_pyerr_impl(&err)
 }
 
+/// Format an error from a file write or flush.
+///
+/// Conditional failures keep their OpenDAL exception so callers can catch
+/// `ConditionNotMatch`. Other failures remain `OSError`, matching raw I/O.
+pub fn format_pyerr_from_write_error(err: ocore::Error) -> PyErr {
+    if err.kind() == ocore::ErrorKind::ConditionNotMatch {
+        format_pyerr_impl(&err)
+    } else {
+        PyIOError::new_err(err.to_string())
+    }
+}
+
 /// Format a std::io::Error into a PyErr, checking if it wraps an OpenDAL error
 pub fn format_pyerr_from_io_error(err: std::io::Error) -> PyErr {
     // Check if this io::Error wraps an OpenDAL error
diff --git a/bindings/python/src/file.rs b/bindings/python/src/file.rs
index af6735345a..0527da310d 100644
--- a/bindings/python/src/file.rs
+++ b/bindings/python/src/file.rs
@@ -291,7 +291,7 @@ impl File {
         let runtime = get_runtime()?;
         py.detach(|| runtime.handle().block_on(writer.send(bs)))
             .map(|_| len)
-            .map_err(|err| PyIOError::new_err(err.to_string()))
+            .map_err(format_pyerr_from_write_error)
     }
 
     /// Change the position of this file to the given byte offset.
@@ -429,7 +429,7 @@ impl File {
             let runtime = get_runtime()?;
             match py.detach(|| runtime.handle().block_on(w.flush())) {
                 Ok(_) => Ok(()),
-                Err(e) => Err(std::io::Error::from(e).into()),
+                Err(e) => Err(format_pyerr_from_write_error(e)),
             }
         } else {
             Ok(())
@@ -798,7 +798,7 @@ impl AsyncFile {
                 .send(bs)
                 .await
                 .map(|_| len)
-                .map_err(|err| PyIOError::new_err(err.to_string()))
+                .map_err(format_pyerr_from_write_error)
         })
     }
 
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index 9069ad1074..7a1e5885d7 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()`, `flush()`, 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`. `AsyncFile` writes bytes, so encode text
+    ///     with `str.encode()` and decode reads with `bytes.decode()`.
     /// **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..c9e88ff77c 100644
--- a/bindings/python/tests/test_open_modes.py
+++ b/bindings/python/tests/test_open_modes.py
@@ -15,10 +15,12 @@
 # specific language governing permissions and limitations
 # under the License.
 
+import contextlib
+
 import pytest
 
 import opendal
-from opendal.exceptions import Unsupported
+from opendal.exceptions import ConditionNotMatch, Unsupported
 
 
 @pytest.fixture
@@ -36,6 +38,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 +62,64 @@ 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"
+
+
+def test_sync_open_create_existing_file_large_write(service_name, tmp_path):
+    if service_name != "fs":
+        pytest.skip("requires the fs service")
+    op = opendal.Operator("fs", root=str(tmp_path))
+    if not op.capability().write_with_if_not_exists:
+        pytest.skip("requires write_with_if_not_exists")
+    op.write("data", b"old contents")
+
+    file = op.open("data", "xb", chunk=64 * 1024)
+    try:
+        with pytest.raises(ConditionNotMatch):
+            file.write(b"new" * (100 * 1024))
+        with pytest.raises(ConditionNotMatch):
+            file.flush()
+    finally:
+        with contextlib.suppress(ConditionNotMatch):
+            file.close()
+    assert op.read("data") == b"old contents"
+
+
 @pytest.mark.asyncio
 @pytest.mark.parametrize(("read", "write", "append"), BINARY_MODES)
 async def test_async_open_modes(local_operator, read, write, append):
@@ -76,21 +140,88 @@ 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"
+
+
[email protected]
+async def test_async_open_create_existing_file_large_write(service_name, 
tmp_path):
+    if service_name != "fs":
+        pytest.skip("requires the fs service")
+    op = opendal.AsyncOperator("fs", root=str(tmp_path))
+    if not op.capability().write_with_if_not_exists:
+        pytest.skip("requires write_with_if_not_exists")
+    await op.write("data", b"old contents")
+
+    file = await op.open("data", "xb", chunk=64 * 1024)
+    try:
+        with pytest.raises(ConditionNotMatch):
+            await file.write(b"new" * (100 * 1024))
+    finally:
+        with contextlib.suppress(ConditionNotMatch):
+            await file.close()
+    assert await op.read("data") == b"old contents"
+
+
 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 +241,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");

Reply via email to