|
2 | 2 |
|
3 | 3 | __all__ = ["aiopen", "aiexists", "ailistdir"]
|
4 | 4 |
|
| 5 | +import contextlib |
5 | 6 | import io
|
6 | 7 |
|
7 | 8 | try:
|
| 9 | + import aiofiles.os |
8 | 10 | from aiofiles import open as aiopen
|
9 | 11 | from aiofiles.os import listdir as ailistdir
|
10 |
| - from aiofiles.path import exists as aiexists |
| 12 | + |
| 13 | + aiexists = aiofiles.os.path.exists |
11 | 14 | except ImportError:
|
12 | 15 | import os
|
13 | 16 |
|
14 |
| - async def aiopen(*args, **kwargs) -> io.TextIOWrapper: |
15 |
| - """Async > sync wrapper.""" |
16 |
| - f = open(*args, **kwargs) # noqa |
17 |
| - _orig_readlines = f.readlines |
| 17 | + class AsyncFile: |
| 18 | + def __init__(self, file: io.TextIOWrapper): |
| 19 | + self.file = file |
| 20 | + |
| 21 | + async def readlines(self) -> list[str]: |
| 22 | + return self.file.readlines() |
| 23 | + |
| 24 | + async def __aenter__(self): |
| 25 | + return self |
18 | 26 |
|
19 |
| - async def _new_readlines(*args, **kwargs) -> list[str]: |
20 |
| - return _orig_readlines(*args, **kwargs) |
| 27 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 28 | + self.file.close() |
21 | 29 |
|
22 |
| - f.readlines = _new_readlines |
23 |
| - return f |
| 30 | + @contextlib.asynccontextmanager |
| 31 | + async def aiopen(*args, **kwargs) -> AsyncFile: |
| 32 | + yield AsyncFile(open(*args, **kwargs)) |
24 | 33 |
|
25 | 34 | async def aiexists(*args, **kwargs) -> bool:
|
26 | 35 | """Async > sync wrapper."""
|
|
0 commit comments