From 09cf49204b70fb9d63f8d06ba6beda46650e2be1 Mon Sep 17 00:00:00 2001 From: Jiseok CHOI Date: Fri, 27 Feb 2026 16:53:17 +0900 Subject: [PATCH] fix: add `flush` method to `BytesIO` (#7235) --- crates/vm/src/stdlib/io.rs | 9 ++++++++ extra_tests/snippets/stdlib_io_bytesio.py | 25 +++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/crates/vm/src/stdlib/io.rs b/crates/vm/src/stdlib/io.rs index 93fe63390..215a9b690 100644 --- a/crates/vm/src/stdlib/io.rs +++ b/crates/vm/src/stdlib/io.rs @@ -4595,6 +4595,15 @@ mod _io { true } + #[pymethod] + fn flush(&self, vm: &VirtualMachine) -> PyResult<()> { + if self.closed.load() { + Err(io_closed_error(vm)) + } else { + Ok(()) + } + } + #[pymethod] fn write(&self, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult { let mut buffer = self.try_resizable(vm)?; diff --git a/extra_tests/snippets/stdlib_io_bytesio.py b/extra_tests/snippets/stdlib_io_bytesio.py index e51177014..ba8ae2001 100644 --- a/extra_tests/snippets/stdlib_io_bytesio.py +++ b/extra_tests/snippets/stdlib_io_bytesio.py @@ -74,6 +74,30 @@ def test_06(): assert f.readline() == b"" +def test_07(): + """ + Tests that flush() returns None when the file is open, + and raises ValueError when the file is closed. + CPython reference: Modules/_io/bytesio.c:325-335 + """ + f = BytesIO(b"Test String 7") + + # flush() on an open BytesIO returns None + assert f.flush() is None + + # flush() is defined directly on BytesIO (not just inherited) + assert "flush" in BytesIO.__dict__ + + f.close() + + # flush() on a closed BytesIO raises ValueError + try: + f.flush() + assert False, "Expected ValueError not raised" + except ValueError: + pass + + if __name__ == "__main__": test_01() test_02() @@ -81,3 +105,4 @@ if __name__ == "__main__": test_04() test_05() test_06() + test_07()