Debian Codegraph @

src/trio/_path.py

raw
1 from __future__ import annotations
2
3 import os
4 import pathlib
5 import sys
6 from functools import partial, update_wrapper
7 from inspect import cleandoc
8 from typing import (
9 IO,
10 TYPE_CHECKING,
11 Any,
12 BinaryIO,
13 ClassVar,
14 Concatenate,
15 Literal,
16 TypeVar,
17 overload,
18 )
19
20 from trio._file_io import AsyncIOWrapper, wrap_file
21 from trio._util import final
22 from trio.to_thread import run_sync
23
24 if TYPE_CHECKING:
25 from collections.abc import Awaitable, Callable, Iterable
26 from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper
27
28 from _typeshed import (
29 OpenBinaryMode,
30 OpenBinaryModeReading,
31 OpenBinaryModeUpdating,
32 OpenBinaryModeWriting,
33 OpenTextMode,
34 )
35 from typing_extensions import ParamSpec, Self
36
37 P = ParamSpec("P")
38
39 PathT = TypeVar("PathT", bound="Path")
40 T = TypeVar("T")
41
42
43 def _wraps_async( # type: ignore[explicit-any]
44 wrapped: Callable[..., object],
45 ) -> Callable[[Callable[P, T]], Callable[P, Awaitable[T]]]:
46 def decorator(fn: Callable[P, T]) -> Callable[P, Awaitable[T]]:
47 async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
48 return await run_sync(partial(fn, *args, **kwargs))
49
50 update_wrapper(wrapper, wrapped)
51 if wrapped.__doc__:
52 module = wrapped.__module__
53 # these are exported specially from CPython's intersphinx inventory
54 module = module.replace("pathlib._local", "pathlib")
55 module = module.replace("pathlib._abc", "pathlib")
56
57 name = wrapped.__qualname__
58 name = name.replace(
59 "PathBase", "Path"
60 ) # I'm not sure why this is necessary
61
62 wrapper.__doc__ = (
63 f"Like :meth:`~{module}.{name}`, but async.\n"
64 f"\n"
65 f"{cleandoc(wrapped.__doc__)}\n"
66 )
67 return wrapper
68
69 return decorator
70
71
72 def _wrap_method(
73 fn: Callable[Concatenate[pathlib.Path, P], T],
74 ) -> Callable[Concatenate[Path, P], Awaitable[T]]:
75 @_wraps_async(fn)
76 def wrapper(self: Path, /, *args: P.args, **kwargs: P.kwargs) -> T:
77 return fn(self._wrapped_cls(self), *args, **kwargs)
78
79 return wrapper
80
81
82 def _wrap_method_path(
83 fn: Callable[Concatenate[pathlib.Path, P], pathlib.Path],
84 ) -> Callable[Concatenate[PathT, P], Awaitable[PathT]]:
85 @_wraps_async(fn)
86 def wrapper(self: PathT, /, *args: P.args, **kwargs: P.kwargs) -> PathT:
87 return self.__class__(fn(self._wrapped_cls(self), *args, **kwargs))
88
89 return wrapper
90
91
92 def _wrap_method_path_iterable(
93 fn: Callable[Concatenate[pathlib.Path, P], Iterable[pathlib.Path]],
94 ) -> Callable[Concatenate[PathT, P], Awaitable[Iterable[PathT]]]:
95 @_wraps_async(fn)
96 def wrapper(self: PathT, /, *args: P.args, **kwargs: P.kwargs) -> Iterable[PathT]:
97 return map(self.__class__, [*fn(self._wrapped_cls(self), *args, **kwargs)])
98
99 if wrapper.__doc__:
100 wrapper.__doc__ += (
101 f"\n"
102 f"This is an async method that returns a synchronous iterator, so you\n"
103 f"use it like:\n"
104 f"\n"
105 f".. code:: python\n"
106 f"\n"
107 f" for subpath in await mypath.{fn.__name__}():\n"
108 f" ...\n"
109 f"\n"
110 f".. note::\n"
111 f"\n"
112 f" The iterator is loaded into memory immediately during the initial\n"
113 f" call (see `issue #501\n"
114 f" <https://github.com/python-trio/trio/issues/501>`__ for discussion).\n"
115 )
116 return wrapper
117
118
119 class Path(pathlib.PurePath):
120 """An async :class:`pathlib.Path` that executes blocking methods in :meth:`trio.to_thread.run_sync`.
121
122 Instantiating :class:`Path` returns a concrete platform-specific subclass, one of :class:`PosixPath` or
123 :class:`WindowsPath`.
124 """
125
126 __slots__ = ()
127
128 _wrapped_cls: ClassVar[type[pathlib.Path]]
129
130 def __new__(cls, *args: str | os.PathLike[str]) -> Self:
131 if cls is Path:
132 cls = WindowsPath if os.name == "nt" else PosixPath # type: ignore[assignment]
133 return super().__new__(cls, *args)
134
135 @classmethod
136 @_wraps_async(pathlib.Path.cwd)
137 def cwd(cls) -> Self:
138 return cls(pathlib.Path.cwd())
139
140 @classmethod
141 @_wraps_async(pathlib.Path.home)
142 def home(cls) -> Self:
143 return cls(pathlib.Path.home())
144
145 @overload
146 async def open(
147 self,
148 mode: OpenTextMode = "r",
149 buffering: int = -1,
150 encoding: str | None = None,
151 errors: str | None = None,
152 newline: str | None = None,
153 ) -> AsyncIOWrapper[TextIOWrapper]: ...
154
155 @overload
156 async def open(
157 self,
158 mode: OpenBinaryMode,
159 buffering: Literal[0],
160 encoding: None = None,
161 errors: None = None,
162 newline: None = None,
163 ) -> AsyncIOWrapper[FileIO]: ...
164
165 @overload
166 async def open(
167 self,
168 mode: OpenBinaryModeUpdating,
169 buffering: Literal[-1, 1] = -1,
170 encoding: None = None,
171 errors: None = None,
172 newline: None = None,
173 ) -> AsyncIOWrapper[BufferedRandom]: ...
174
175 @overload
176 async def open(
177 self,
178 mode: OpenBinaryModeWriting,
179 buffering: Literal[-1, 1] = -1,
180 encoding: None = None,
181 errors: None = None,
182 newline: None = None,
183 ) -> AsyncIOWrapper[BufferedWriter]: ...
184
185 @overload
186 async def open(
187 self,
188 mode: OpenBinaryModeReading,
189 buffering: Literal[-1, 1] = -1,
190 encoding: None = None,
191 errors: None = None,
192 newline: None = None,
193 ) -> AsyncIOWrapper[BufferedReader]: ...
194
195 @overload
196 async def open(
197 self,
198 mode: OpenBinaryMode,
199 buffering: int = -1,
200 encoding: None = None,
201 errors: None = None,
202 newline: None = None,
203 ) -> AsyncIOWrapper[BinaryIO]: ...
204
205 @overload
206 async def open( # type: ignore[explicit-any] # Any usage matches builtins.open().
207 self,
208 mode: str,
209 buffering: int = -1,
210 encoding: str | None = None,
211 errors: str | None = None,
212 newline: str | None = None,
213 ) -> AsyncIOWrapper[IO[Any]]: ...
214
215 @_wraps_async(pathlib.Path.open)
216 def open(self, *args: Any, **kwargs: Any) -> AsyncIOWrapper[IO[Any]]: # type: ignore[misc, explicit-any] # Overload return mismatch.
217 return wrap_file(self._wrapped_cls(self).open(*args, **kwargs))
218
219 def __repr__(self) -> str:
220 return f"trio.Path({str(self)!r})"
221
222 stat = _wrap_method(pathlib.Path.stat)
223 chmod = _wrap_method(pathlib.Path.chmod)
224 exists = _wrap_method(pathlib.Path.exists)
225 glob = _wrap_method_path_iterable(pathlib.Path.glob)
226 rglob = _wrap_method_path_iterable(pathlib.Path.rglob)
227 is_dir = _wrap_method(pathlib.Path.is_dir)
228 is_file = _wrap_method(pathlib.Path.is_file)
229 is_symlink = _wrap_method(pathlib.Path.is_symlink)
230 is_socket = _wrap_method(pathlib.Path.is_socket)
231 is_fifo = _wrap_method(pathlib.Path.is_fifo)
232 is_block_device = _wrap_method(pathlib.Path.is_block_device)
233 is_char_device = _wrap_method(pathlib.Path.is_char_device)
234 if sys.version_info >= (3, 12):
235 is_junction = _wrap_method(pathlib.Path.is_junction)
236 iterdir = _wrap_method_path_iterable(pathlib.Path.iterdir)
237 lchmod = _wrap_method(pathlib.Path.lchmod)
238 lstat = _wrap_method(pathlib.Path.lstat)
239 mkdir = _wrap_method(pathlib.Path.mkdir)
240 if sys.platform != "win32":
241 owner = _wrap_method(pathlib.Path.owner)
242 group = _wrap_method(pathlib.Path.group)
243 if sys.platform != "win32" or sys.version_info >= (3, 12):
244 is_mount = _wrap_method(pathlib.Path.is_mount)
245 readlink = _wrap_method_path(pathlib.Path.readlink)
246 rename = _wrap_method_path(pathlib.Path.rename)
247 replace = _wrap_method_path(pathlib.Path.replace)
248 resolve = _wrap_method_path(pathlib.Path.resolve)
249 rmdir = _wrap_method(pathlib.Path.rmdir)
250 symlink_to = _wrap_method(pathlib.Path.symlink_to)
251 hardlink_to = _wrap_method(pathlib.Path.hardlink_to)
252 touch = _wrap_method(pathlib.Path.touch)
253 unlink = _wrap_method(pathlib.Path.unlink)
254 absolute = _wrap_method_path(pathlib.Path.absolute)
255 expanduser = _wrap_method_path(pathlib.Path.expanduser)
256 read_bytes = _wrap_method(pathlib.Path.read_bytes)
257 read_text = _wrap_method(pathlib.Path.read_text)
258 samefile = _wrap_method(pathlib.Path.samefile)
259 write_bytes = _wrap_method(pathlib.Path.write_bytes)
260 write_text = _wrap_method(pathlib.Path.write_text)
261 if sys.version_info < (3, 12):
262 link_to = _wrap_method(pathlib.Path.link_to)
263 if sys.version_info >= (3, 13):
264 full_match = _wrap_method(pathlib.Path.full_match)
265
266 def as_uri(self) -> str:
267 return self._wrapped_cls(self).as_uri()
268
269
270 if Path.relative_to.__doc__: # pragma: no branch
271 Path.relative_to.__doc__ = Path.relative_to.__doc__.replace(" `..` ", " ``..`` ")
272
273
274 @final
275 class PosixPath(Path, pathlib.PurePosixPath):
276 """An async :class:`pathlib.PosixPath` that executes blocking methods in :meth:`trio.to_thread.run_sync`."""
277
278 __slots__ = ()
279
280 _wrapped_cls: ClassVar[type[pathlib.Path]] = pathlib.PosixPath
281
282
283 @final
284 class WindowsPath(Path, pathlib.PureWindowsPath):
285 """An async :class:`pathlib.WindowsPath` that executes blocking methods in :meth:`trio.to_thread.run_sync`."""
286
287 __slots__ = ()
288
289 _wrapped_cls: ClassVar[type[pathlib.Path]] = pathlib.WindowsPath