Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions newsfragments/3379.doc.rst
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions src/trio/_file_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
28 changes: 28 additions & 0 deletions src/trio/_tests/test_file_io.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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")
Expand Down
Loading