An async version of pathlib.Path that uses asyncio.to_thread for filesystem operations. This class inherits from PurePath for path manipulation and adds async filesystem methods.
| 19 | |
| 20 | |
| 21 | class AsyncPath(PurePath): |
| 22 | """ |
| 23 | An async version of pathlib.Path that uses asyncio.to_thread for filesystem operations. |
| 24 | |
| 25 | This class inherits from PurePath for path manipulation and adds async filesystem methods. |
| 26 | """ |
| 27 | |
| 28 | def __new__(cls, *args: Any, **kwargs: Any) -> Self: |
| 29 | # Create the path using the same logic as PurePath |
| 30 | path_cls: type[AsyncPath] |
| 31 | if cls is AsyncPath: |
| 32 | path_cls = AsyncWindowsPath if os.name == "nt" else AsyncPosixPath |
| 33 | else: |
| 34 | path_cls = cls |
| 35 | return super().__new__(path_cls, *args, **kwargs) # type: ignore |
| 36 | |
| 37 | def __truediv__(self, other: StrPath) -> AsyncPath: |
| 38 | # Override to return AsyncPath instance |
| 39 | result = super().__truediv__(other) |
| 40 | return self.__class__(result) |
| 41 | |
| 42 | def __rtruediv__(self, other: StrPath) -> AsyncPath: |
| 43 | # Override to return AsyncPath instance |
| 44 | result = super().__rtruediv__(other) |
| 45 | return self.__class__(result) |
| 46 | |
| 47 | @property |
| 48 | def _path(self) -> Path: |
| 49 | """Get the synchronous Path equivalent.""" |
| 50 | return Path(self) |
| 51 | |
| 52 | # Async filesystem operations |
| 53 | |
| 54 | async def exists(self) -> bool: |
| 55 | """Return True if the path exists.""" |
| 56 | return await asyncio.to_thread(self._path.exists) |
| 57 | |
| 58 | async def is_file(self) -> bool: |
| 59 | """Return True if the path is a regular file.""" |
| 60 | return await asyncio.to_thread(self._path.is_file) |
| 61 | |
| 62 | async def is_dir(self) -> bool: |
| 63 | """Return True if the path is a directory.""" |
| 64 | return await asyncio.to_thread(self._path.is_dir) |
| 65 | |
| 66 | async def is_symlink(self) -> bool: |
| 67 | """Return True if the path is a symbolic link.""" |
| 68 | return await asyncio.to_thread(self._path.is_symlink) |
| 69 | |
| 70 | async def stat(self) -> os.stat_result: |
| 71 | """Return stat info for the path.""" |
| 72 | return await asyncio.to_thread(self._path.stat) |
| 73 | |
| 74 | async def lstat(self) -> os.stat_result: |
| 75 | """Return lstat info for the path (doesn't follow symlinks).""" |
| 76 | return await asyncio.to_thread(self._path.lstat) |
| 77 | |
| 78 | async def chmod(self, mode: int) -> None: |
no outgoing calls
searching dependent graphs…