| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
from collections.abc import Callable, Iterable |
| 5 |
from functools import partial |
| 6 |
from typing import ( |
| 7 |
IO, |
| 8 |
TYPE_CHECKING, |
| 9 |
Any, |
| 10 |
AnyStr, |
| 11 |
BinaryIO, |
| 12 |
Generic, |
| 13 |
Literal, |
| 14 |
TypeVar, |
| 15 |
Union, |
| 16 |
overload, |
| 17 |
) |
| 18 |
|
| 19 |
import trio |
| 20 |
|
| 21 |
from ._util import async_wraps |
| 22 |
from .abc import AsyncResource |
| 23 |
|
| 24 |
if TYPE_CHECKING: |
| 25 |
from _typeshed import ( |
| 26 |
OpenBinaryMode, |
| 27 |
OpenBinaryModeReading, |
| 28 |
OpenBinaryModeUpdating, |
| 29 |
OpenBinaryModeWriting, |
| 30 |
OpenTextMode, |
| 31 |
StrOrBytesPath, |
| 32 |
) |
| 33 |
|
| 34 |
from ._sync import CapacityLimiter |
| 35 |
|
| 36 |
# This list is also in the docs, make sure to keep them in sync |
| 37 |
_FILE_SYNC_ATTRS: set[str] = { |
| 38 |
"closed", |
| 39 |
"encoding", |
| 40 |
"errors", |
| 41 |
"fileno", |
| 42 |
"isatty", |
| 43 |
"newlines", |
| 44 |
"readable", |
| 45 |
"seekable", |
| 46 |
"writable", |
| 47 |
# not defined in *IOBase: |
| 48 |
"buffer", |
| 49 |
"raw", |
| 50 |
"line_buffering", |
| 51 |
"closefd", |
| 52 |
"name", |
| 53 |
"mode", |
| 54 |
"getvalue", |
| 55 |
"getbuffer", |
| 56 |
} |
| 57 |
|
| 58 |
# This list is also in the docs, make sure to keep them in sync |
| 59 |
_FILE_ASYNC_METHODS: set[str] = { |
| 60 |
"flush", |
| 61 |
"read", |
| 62 |
"read1", |
| 63 |
"readall", |
| 64 |
"readinto", |
| 65 |
"readline", |
| 66 |
"readlines", |
| 67 |
"seek", |
| 68 |
"tell", |
| 69 |
"truncate", |
| 70 |
"write", |
| 71 |
"writelines", |
| 72 |
# not defined in *IOBase: |
| 73 |
"readinto1", |
| 74 |
"peek", |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
FileT = TypeVar("FileT") |
| 79 |
FileT_co = TypeVar("FileT_co", covariant=True) |
| 80 |
T = TypeVar("T") |
| 81 |
T_co = TypeVar("T_co", covariant=True) |
| 82 |
T_contra = TypeVar("T_contra", contravariant=True) |
| 83 |
AnyStr_co = TypeVar("AnyStr_co", str, bytes, covariant=True) |
| 84 |
AnyStr_contra = TypeVar("AnyStr_contra", str, bytes, contravariant=True) |
| 85 |
|
| 86 |
# This is a little complicated. IO objects have a lot of methods, and which are available on |
| 87 |
# different types varies wildly. We want to match the interface of whatever file we're wrapping. |
| 88 |
# This pile of protocols each has one sync method/property, meaning they're going to be compatible |
| 89 |
# with a file class that supports that method/property. The ones parameterized with AnyStr take |
| 90 |
# either str or bytes depending. |
| 91 |
|
| 92 |
# The wrapper is then a generic class, where the typevar is set to the type of the sync file we're |
| 93 |
# wrapping. For generics, adding a type to self has a special meaning - properties/methods can be |
| 94 |
# conditional - it's only valid to call them if the object you're accessing them on is compatible |
| 95 |
# with that type hint. By using the protocols, the type checker will be checking to see if the |
| 96 |
# wrapped type has that method, and only allow the methods that do to be called. We can then alter |
| 97 |
# the signature however it needs to match runtime behaviour. |
| 98 |
# More info: https://mypy.readthedocs.io/en/stable/more_types.html#advanced-uses-of-self-types |
| 99 |
if TYPE_CHECKING: |
| 100 |
from typing_extensions import Buffer, Protocol |
| 101 |
|
| 102 |
# fmt: off |
| 103 |
|
| 104 |
class _HasClosed(Protocol): |
| 105 |
@property |
| 106 |
def closed(self) -> bool: ... |
| 107 |
|
| 108 |
class _HasEncoding(Protocol): |
| 109 |
@property |
| 110 |
def encoding(self) -> str: ... |
| 111 |
|
| 112 |
class _HasErrors(Protocol): |
| 113 |
@property |
| 114 |
def errors(self) -> str | None: ... |
| 115 |
|
| 116 |
class _HasFileNo(Protocol): |
| 117 |
def fileno(self) -> int: ... |
| 118 |
|
| 119 |
class _HasIsATTY(Protocol): |
| 120 |
def isatty(self) -> bool: ... |
| 121 |
|
| 122 |
class _HasNewlines(Protocol[T_co]): |
| 123 |
# Type varies here - documented to be None, tuple of strings, strings. Typeshed uses Any. |
| 124 |
@property |
| 125 |
def newlines(self) -> T_co: ... |
| 126 |
|
| 127 |
class _HasReadable(Protocol): |
| 128 |
def readable(self) -> bool: ... |
| 129 |
|
| 130 |
class _HasSeekable(Protocol): |
| 131 |
def seekable(self) -> bool: ... |
| 132 |
|
| 133 |
class _HasWritable(Protocol): |
| 134 |
def writable(self) -> bool: ... |
| 135 |
|
| 136 |
class _HasBuffer(Protocol): |
| 137 |
@property |
| 138 |
def buffer(self) -> BinaryIO: ... |
| 139 |
|
| 140 |
class _HasRaw(Protocol): |
| 141 |
@property |
| 142 |
def raw(self) -> io.RawIOBase: ... |
| 143 |
|
| 144 |
class _HasLineBuffering(Protocol): |
| 145 |
@property |
| 146 |
def line_buffering(self) -> bool: ... |
| 147 |
|
| 148 |
class _HasCloseFD(Protocol): |
| 149 |
@property |
| 150 |
def closefd(self) -> bool: ... |
| 151 |
|
| 152 |
class _HasName(Protocol): |
| 153 |
@property |
| 154 |
def name(self) -> str: ... |
| 155 |
|
| 156 |
class _HasMode(Protocol): |
| 157 |
@property |
| 158 |
def mode(self) -> str: ... |
| 159 |
|
| 160 |
class _CanGetValue(Protocol[AnyStr_co]): |
| 161 |
def getvalue(self) -> AnyStr_co: ... |
| 162 |
|
| 163 |
class _CanGetBuffer(Protocol): |
| 164 |
def getbuffer(self) -> memoryview: ... |
| 165 |
|
| 166 |
class _CanFlush(Protocol): |
| 167 |
def flush(self) -> None: ... |
| 168 |
|
| 169 |
class _CanRead(Protocol[AnyStr_co]): |
| 170 |
def read(self, size: int | None = ..., /) -> AnyStr_co: ... |
| 171 |
|
| 172 |
class _CanRead1(Protocol): |
| 173 |
def read1(self, size: int | None = ..., /) -> bytes: ... |
| 174 |
|
| 175 |
class _CanReadAll(Protocol[AnyStr_co]): |
| 176 |
def readall(self) -> AnyStr_co: ... |
| 177 |
|
| 178 |
class _CanReadInto(Protocol): |
| 179 |
def readinto(self, buf: Buffer, /) -> int | None: ... |
| 180 |
|
| 181 |
class _CanReadInto1(Protocol): |
| 182 |
def readinto1(self, buffer: Buffer, /) -> int: ... |
| 183 |
|
| 184 |
class _CanReadLine(Protocol[AnyStr_co]): |
| 185 |
def readline(self, size: int = ..., /) -> AnyStr_co: ... |
| 186 |
|
| 187 |
class _CanReadLines(Protocol[AnyStr]): |
| 188 |
def readlines(self, hint: int = ..., /) -> list[AnyStr]: ... |
| 189 |
|
| 190 |
class _CanSeek(Protocol): |
| 191 |
def seek(self, target: int, whence: int = 0, /) -> int: ... |
| 192 |
|
| 193 |
class _CanTell(Protocol): |
| 194 |
def tell(self) -> int: ... |
| 195 |
|
| 196 |
class _CanTruncate(Protocol): |
| 197 |
def truncate(self, size: int | None = ..., /) -> int: ... |
| 198 |
|
| 199 |
class _CanWrite(Protocol[T_contra]): |
| 200 |
def write(self, data: T_contra, /) -> int: ... |
| 201 |
|
| 202 |
class _CanWriteLines(Protocol[T_contra]): |
| 203 |
# The lines parameter varies for bytes/str, so use a typevar to make the async match. |
| 204 |
def writelines(self, lines: Iterable[T_contra], /) -> None: ... |
| 205 |
|
| 206 |
class _CanPeek(Protocol[AnyStr_co]): |
| 207 |
def peek(self, size: int = 0, /) -> AnyStr_co: ... |
| 208 |
|
| 209 |
class _CanDetach(Protocol[T_co]): |
| 210 |
# The T typevar will be the unbuffered/binary file this file wraps. |
| 211 |
def detach(self) -> T_co: ... |
| 212 |
|
| 213 |
class _CanClose(Protocol): |
| 214 |
def close(self) -> None: ... |
| 215 |
|
| 216 |
|
| 217 |
# FileT needs to be covariant for the protocol trick to work - the real IO types are effectively a |
| 218 |
# subtype of the protocols. |
| 219 |
class AsyncIOWrapper(AsyncResource, Generic[FileT_co]): |
| 220 |
"""A generic :class:`~io.IOBase` wrapper that implements the :term:`asynchronous |
| 221 |
file object` interface. Wrapped methods that could block are executed in |
| 222 |
:meth:`trio.to_thread.run_sync`. |
| 223 |
|
| 224 |
All properties and methods defined in :mod:`~io` are exposed by this |
| 225 |
wrapper, if they exist in the wrapped file object. |
| 226 |
""" |
| 227 |
|
| 228 |
def __init__(self, file: FileT_co) -> None: |
| 229 |
self._wrapped = file |
| 230 |
|
| 231 |
@property |
| 232 |
def wrapped(self) -> FileT_co: |
| 233 |
"""object: A reference to the wrapped file object""" |
| 234 |
|
| 235 |
return self._wrapped |
| 236 |
|
| 237 |
if not TYPE_CHECKING: |
| 238 |
|
| 239 |
def __getattr__(self, name: str) -> object: |
| 240 |
if name in _FILE_SYNC_ATTRS: |
| 241 |
return getattr(self._wrapped, name) |
| 242 |
if name in _FILE_ASYNC_METHODS: |
| 243 |
meth = getattr(self._wrapped, name) |
| 244 |
|
| 245 |
@async_wraps(self.__class__, self._wrapped.__class__, name) |
| 246 |
async def wrapper( |
| 247 |
*args: Callable[..., T], |
| 248 |
**kwargs: object | str | bool | CapacityLimiter | None, |
| 249 |
) -> T: |
| 250 |
func = partial(meth, *args, **kwargs) |
| 251 |
return await trio.to_thread.run_sync(func) |
| 252 |
|
| 253 |
# cache the generated method |
| 254 |
setattr(self, name, wrapper) |
| 255 |
return wrapper |
| 256 |
|
| 257 |
raise AttributeError(name) |
| 258 |
|
| 259 |
def __dir__(self) -> Iterable[str]: |
| 260 |
attrs = set(super().__dir__()) |
| 261 |
attrs.update(a for a in _FILE_SYNC_ATTRS if hasattr(self.wrapped, a)) |
| 262 |
attrs.update(a for a in _FILE_ASYNC_METHODS if hasattr(self.wrapped, a)) |
| 263 |
return attrs |
| 264 |
|
| 265 |
def __aiter__(self) -> AsyncIOWrapper[FileT_co]: |
| 266 |
return self |
| 267 |
|
| 268 |
async def __anext__(self: AsyncIOWrapper[_CanReadLine[AnyStr]]) -> AnyStr: |
| 269 |
line = await self.readline() |
| 270 |
if line: |
| 271 |
return line |
| 272 |
else: |
| 273 |
raise StopAsyncIteration |
| 274 |
|
| 275 |
async def detach(self: AsyncIOWrapper[_CanDetach[T]]) -> AsyncIOWrapper[T]: |
| 276 |
"""Like :meth:`io.BufferedIOBase.detach`, but async. |
| 277 |
|
| 278 |
This also re-wraps the result in a new :term:`asynchronous file object` |
| 279 |
wrapper. |
| 280 |
|
| 281 |
""" |
| 282 |
|
| 283 |
raw = await trio.to_thread.run_sync(self._wrapped.detach) |
| 284 |
return wrap_file(raw) |
| 285 |
|
| 286 |
async def aclose(self: AsyncIOWrapper[_CanClose]) -> None: |
| 287 |
"""Like :meth:`io.IOBase.close`, but async. |
| 288 |
|
| 289 |
This is also shielded from cancellation; if a cancellation scope is |
| 290 |
cancelled, the wrapped file object will still be safely closed. |
| 291 |
|
| 292 |
""" |
| 293 |
|
| 294 |
# ensure the underling file is closed during cancellation |
| 295 |
with trio.CancelScope(shield=True): |
| 296 |
await trio.to_thread.run_sync(self._wrapped.close) |
| 297 |
|
| 298 |
await trio.lowlevel.checkpoint_if_cancelled() |
| 299 |
|
| 300 |
if TYPE_CHECKING: |
| 301 |
# fmt: off |
| 302 |
# Based on typing.IO and io stubs. |
| 303 |
@property |
| 304 |
def closed(self: AsyncIOWrapper[_HasClosed]) -> bool: ... |
| 305 |
@property |
| 306 |
def encoding(self: AsyncIOWrapper[_HasEncoding]) -> str: ... |
| 307 |
@property |
| 308 |
def errors(self: AsyncIOWrapper[_HasErrors]) -> str | None: ... |
| 309 |
@property |
| 310 |
def newlines(self: AsyncIOWrapper[_HasNewlines[T]]) -> T: ... |
| 311 |
@property |
| 312 |
def buffer(self: AsyncIOWrapper[_HasBuffer]) -> BinaryIO: ... |
| 313 |
@property |
| 314 |
def raw(self: AsyncIOWrapper[_HasRaw]) -> io.RawIOBase: ... |
| 315 |
@property |
| 316 |
def line_buffering(self: AsyncIOWrapper[_HasLineBuffering]) -> int: ... |
| 317 |
@property |
| 318 |
def closefd(self: AsyncIOWrapper[_HasCloseFD]) -> bool: ... |
| 319 |
@property |
| 320 |
def name(self: AsyncIOWrapper[_HasName]) -> str: ... |
| 321 |
@property |
| 322 |
def mode(self: AsyncIOWrapper[_HasMode]) -> str: ... |
| 323 |
|
| 324 |
def fileno(self: AsyncIOWrapper[_HasFileNo]) -> int: ... |
| 325 |
def isatty(self: AsyncIOWrapper[_HasIsATTY]) -> bool: ... |
| 326 |
def readable(self: AsyncIOWrapper[_HasReadable]) -> bool: ... |
| 327 |
def seekable(self: AsyncIOWrapper[_HasSeekable]) -> bool: ... |
| 328 |
def writable(self: AsyncIOWrapper[_HasWritable]) -> bool: ... |
| 329 |
def getvalue(self: AsyncIOWrapper[_CanGetValue[AnyStr]]) -> AnyStr: ... |
| 330 |
def getbuffer(self: AsyncIOWrapper[_CanGetBuffer]) -> memoryview: ... |
| 331 |
async def flush(self: AsyncIOWrapper[_CanFlush]) -> None: ... |
| 332 |
async def read(self: AsyncIOWrapper[_CanRead[AnyStr]], size: int | None = -1, /) -> AnyStr: ... |
| 333 |
async def read1(self: AsyncIOWrapper[_CanRead1], size: int | None = -1, /) -> bytes: ... |
| 334 |
async def readall(self: AsyncIOWrapper[_CanReadAll[AnyStr]]) -> AnyStr: ... |
| 335 |
async def readinto(self: AsyncIOWrapper[_CanReadInto], buf: Buffer, /) -> int | None: ... |
| 336 |
async def readline(self: AsyncIOWrapper[_CanReadLine[AnyStr]], size: int = -1, /) -> AnyStr: ... |
| 337 |
async def readlines(self: AsyncIOWrapper[_CanReadLines[AnyStr]]) -> list[AnyStr]: ... |
| 338 |
async def seek(self: AsyncIOWrapper[_CanSeek], target: int, whence: int = 0, /) -> int: ... |
| 339 |
async def tell(self: AsyncIOWrapper[_CanTell]) -> int: ... |
| 340 |
async def truncate(self: AsyncIOWrapper[_CanTruncate], size: int | None = None, /) -> int: ... |
| 341 |
async def write(self: AsyncIOWrapper[_CanWrite[T]], data: T, /) -> int: ... |
| 342 |
async def writelines(self: AsyncIOWrapper[_CanWriteLines[T]], lines: Iterable[T], /) -> None: ... |
| 343 |
async def readinto1(self: AsyncIOWrapper[_CanReadInto1], buffer: Buffer, /) -> int: ... |
| 344 |
async def peek(self: AsyncIOWrapper[_CanPeek[AnyStr]], size: int = 0, /) -> AnyStr: ... |
| 345 |
|
| 346 |
|
| 347 |
# Type hints are copied from builtin open. |
| 348 |
_OpenFile = Union["StrOrBytesPath", int] |
| 349 |
_Opener = Callable[[str, int], int] |
| 350 |
|
| 351 |
|
| 352 |
@overload |
| 353 |
async def open_file( |
| 354 |
file: _OpenFile, |
| 355 |
mode: OpenTextMode = "r", |
| 356 |
buffering: int = -1, |
| 357 |
encoding: str | None = None, |
| 358 |
errors: str | None = None, |
| 359 |
newline: str | None = None, |
| 360 |
closefd: bool = True, |
| 361 |
opener: _Opener | None = None, |
| 362 |
) -> AsyncIOWrapper[io.TextIOWrapper]: ... |
| 363 |
|
| 364 |
|
| 365 |
@overload |
| 366 |
async def open_file( |
| 367 |
file: _OpenFile, |
| 368 |
mode: OpenBinaryMode, |
| 369 |
buffering: Literal[0], |
| 370 |
encoding: None = None, |
| 371 |
errors: None = None, |
| 372 |
newline: None = None, |
| 373 |
closefd: bool = True, |
| 374 |
opener: _Opener | None = None, |
| 375 |
) -> AsyncIOWrapper[io.FileIO]: ... |
| 376 |
|
| 377 |
|
| 378 |
@overload |
| 379 |
async def open_file( |
| 380 |
file: _OpenFile, |
| 381 |
mode: OpenBinaryModeUpdating, |
| 382 |
buffering: Literal[-1, 1] = -1, |
| 383 |
encoding: None = None, |
| 384 |
errors: None = None, |
| 385 |
newline: None = None, |
| 386 |
closefd: bool = True, |
| 387 |
opener: _Opener | None = None, |
| 388 |
) -> AsyncIOWrapper[io.BufferedRandom]: ... |
| 389 |
|
| 390 |
|
| 391 |
@overload |
| 392 |
async def open_file( |
| 393 |
file: _OpenFile, |
| 394 |
mode: OpenBinaryModeWriting, |
| 395 |
buffering: Literal[-1, 1] = -1, |
| 396 |
encoding: None = None, |
| 397 |
errors: None = None, |
| 398 |
newline: None = None, |
| 399 |
closefd: bool = True, |
| 400 |
opener: _Opener | None = None, |
| 401 |
) -> AsyncIOWrapper[io.BufferedWriter]: ... |
| 402 |
|
| 403 |
|
| 404 |
@overload |
| 405 |
async def open_file( |
| 406 |
file: _OpenFile, |
| 407 |
mode: OpenBinaryModeReading, |
| 408 |
buffering: Literal[-1, 1] = -1, |
| 409 |
encoding: None = None, |
| 410 |
errors: None = None, |
| 411 |
newline: None = None, |
| 412 |
closefd: bool = True, |
| 413 |
opener: _Opener | None = None, |
| 414 |
) -> AsyncIOWrapper[io.BufferedReader]: ... |
| 415 |
|
| 416 |
|
| 417 |
@overload |
| 418 |
async def open_file( |
| 419 |
file: _OpenFile, |
| 420 |
mode: OpenBinaryMode, |
| 421 |
buffering: int, |
| 422 |
encoding: None = None, |
| 423 |
errors: None = None, |
| 424 |
newline: None = None, |
| 425 |
closefd: bool = True, |
| 426 |
opener: _Opener | None = None, |
| 427 |
) -> AsyncIOWrapper[BinaryIO]: ... |
| 428 |
|
| 429 |
|
| 430 |
@overload |
| 431 |
async def open_file( # type: ignore[explicit-any] # Any usage matches builtins.open(). |
| 432 |
file: _OpenFile, |
| 433 |
mode: str, |
| 434 |
buffering: int = -1, |
| 435 |
encoding: str | None = None, |
| 436 |
errors: str | None = None, |
| 437 |
newline: str | None = None, |
| 438 |
closefd: bool = True, |
| 439 |
opener: _Opener | None = None, |
| 440 |
) -> AsyncIOWrapper[IO[Any]]: ... |
| 441 |
|
| 442 |
|
| 443 |
async def open_file( |
| 444 |
file: _OpenFile, |
| 445 |
mode: str = "r", |
| 446 |
buffering: int = -1, |
| 447 |
encoding: str | None = None, |
| 448 |
errors: str | None = None, |
| 449 |
newline: str | None = None, |
| 450 |
closefd: bool = True, |
| 451 |
opener: _Opener | None = None, |
| 452 |
) -> AsyncIOWrapper[object]: |
| 453 |
"""Asynchronous version of :func:`open`. |
| 454 |
|
| 455 |
Returns: |
| 456 |
An :term:`asynchronous file object` |
| 457 |
|
| 458 |
Example:: |
| 459 |
|
| 460 |
async with await trio.open_file(filename) as f: |
| 461 |
async for line in f: |
| 462 |
pass |
| 463 |
|
| 464 |
assert f.closed |
| 465 |
|
| 466 |
See also: |
| 467 |
:func:`trio.Path.open` |
| 468 |
|
| 469 |
""" |
| 470 |
file_ = wrap_file( |
| 471 |
await trio.to_thread.run_sync( |
| 472 |
io.open, |
| 473 |
file, |
| 474 |
mode, |
| 475 |
buffering, |
| 476 |
encoding, |
| 477 |
errors, |
| 478 |
newline, |
| 479 |
closefd, |
| 480 |
opener, |
| 481 |
), |
| 482 |
) |
| 483 |
return file_ |
| 484 |
|
| 485 |
|
| 486 |
def wrap_file(file: FileT) -> AsyncIOWrapper[FileT]: |
| 487 |
"""This wraps any file object in a wrapper that provides an asynchronous |
| 488 |
file object interface. |
| 489 |
|
| 490 |
Args: |
| 491 |
file: a :term:`file object` |
| 492 |
|
| 493 |
Returns: |
| 494 |
An :term:`asynchronous file object` that wraps ``file`` |
| 495 |
|
| 496 |
Example:: |
| 497 |
|
| 498 |
async_file = trio.wrap_file(StringIO('asdf')) |
| 499 |
|
| 500 |
assert await async_file.read() == 'asdf' |
| 501 |
|
| 502 |
""" |
| 503 |
|
| 504 |
def has(attr: str) -> bool: |
| 505 |
return hasattr(file, attr) and callable(getattr(file, attr)) |
| 506 |
|
| 507 |
if not (has("close") and (has("read") or has("write"))): |
| 508 |
raise TypeError( |
| 509 |
f"{file} does not implement required duck-file methods: " |
| 510 |
"close and (read or write)", |
| 511 |
) |
| 512 |
|
| 513 |
return AsyncIOWrapper(file) |