diff --git a/newsfragments/3379.doc.rst b/newsfragments/3379.doc.rst new file mode 100644 index 0000000000..6b80559de5 --- /dev/null +++ b/newsfragments/3379.doc.rst @@ -0,0 +1,3 @@ +Documented how ``trio.wrap_file`` treats the file it wraps: closing the +wrapped file also closes the original file, dropping the wrapped file does +not close anything, and the original file stays usable while it is wrapped. diff --git a/src/trio/_file_io.py b/src/trio/_file_io.py index 354d048385..dd5c3c7260 100644 --- a/src/trio/_file_io.py +++ b/src/trio/_file_io.py @@ -487,6 +487,12 @@ def wrap_file(file: FileT) -> AsyncIOWrapper[FileT]: """This wraps any file object in a wrapper that provides an asynchronous file object interface. + Closing the wrapped file also closes the file you passed in, so only + close the wrapped file when you are done with both. The wrapped file + has no destructor, so if you drop it without closing it, the file you + passed in stays open. You can keep using the file you passed in while + it is wrapped. + Args: file: a :term:`file object` diff --git a/src/trio/_tests/test_file_io.py b/src/trio/_tests/test_file_io.py index 390a81ce61..966204b7ca 100644 --- a/src/trio/_tests/test_file_io.py +++ b/src/trio/_tests/test_file_io.py @@ -1,9 +1,11 @@ from __future__ import annotations +import gc import importlib import io import os import re +import weakref from typing import TYPE_CHECKING from unittest import mock from unittest.mock import sentinel @@ -240,6 +242,32 @@ async def test_async_iter() -> None: assert result == expected +async def test_wrap_file_close_and_gc() -> None: + # Closing the wrapped file also closes the sync file. + sync_file = io.StringIO("hello") + async_file = trio.wrap_file(sync_file) + await async_file.aclose() + assert sync_file.closed + + # Dropping the wrapped file without closing it does not close the + # sync file, because AsyncIOWrapper has no destructor. + sync_file = io.StringIO("hello") + async_file = trio.wrap_file(sync_file) + ref = weakref.ref(async_file) + del async_file + gc.collect() + assert ref() is None + assert not sync_file.closed + + # The sync file stays usable while it is wrapped. + sync_file.seek(0) + async_file = trio.wrap_file(sync_file) + assert await async_file.read() == "hello" + sync_file.seek(0) + assert sync_file.read() == "hello" + await async_file.aclose() + + async def test_aclose_cancelled(path: pathlib.Path) -> None: with _core.CancelScope() as cscope: f = await trio.open_file(path, "w")