Debian Codegraph @

src/trio/_core/_unbounded_queue.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING, Generic, TypeVar
4
5 import attrs
6
7 from .. import _core
8 from .._deprecate import deprecated
9 from .._util import final
10
11 T = TypeVar("T")
12
13 if TYPE_CHECKING:
14 from typing_extensions import Self
15
16
17 @attrs.frozen
18 class UnboundedQueueStatistics:
19 """An object containing debugging information.
20
21 Currently, the following fields are defined:
22
23 * ``qsize``: The number of items currently in the queue.
24 * ``tasks_waiting``: The number of tasks blocked on this queue's
25 :meth:`get_batch` method.
26
27 """
28
29 qsize: int
30 tasks_waiting: int
31
32
33 @final
34 class UnboundedQueue(Generic[T]):
35 """An unbounded queue suitable for certain unusual forms of inter-task
36 communication.
37
38 This class is designed for use as a queue in cases where the producer for
39 some reason cannot be subjected to back-pressure, i.e., :meth:`put_nowait`
40 has to always succeed. In order to prevent the queue backlog from actually
41 growing without bound, the consumer API is modified to dequeue items in
42 "batches". If a consumer task processes each batch without yielding, then
43 this helps achieve (but does not guarantee) an effective bound on the
44 queue's memory use, at the cost of potentially increasing system latencies
45 in general. You should generally prefer to use a memory channel
46 instead if you can.
47
48 Currently each batch completely empties the queue, but `this may change in
49 the future <https://github.com/python-trio/trio/issues/51>`__.
50
51 A :class:`UnboundedQueue` object can be used as an asynchronous iterator,
52 where each iteration returns a new batch of items. I.e., these two loops
53 are equivalent::
54
55 async for batch in queue:
56 ...
57
58 while True:
59 obj = await queue.get_batch()
60 ...
61
62 """
63
64 @deprecated(
65 "0.9.0",
66 issue=497,
67 thing="trio.lowlevel.UnboundedQueue",
68 instead="trio.open_memory_channel(math.inf)",
69 use_triodeprecationwarning=True,
70 )
71 def __init__(self) -> None:
72 self._lot = _core.ParkingLot()
73 self._data: list[T] = []
74 # used to allow handoff from put to the first task in the lot
75 self._can_get = False
76
77 def __repr__(self) -> str:
78 return f"<UnboundedQueue holding {len(self._data)} items>"
79
80 def qsize(self) -> int:
81 """Returns the number of items currently in the queue."""
82 return len(self._data)
83
84 def empty(self) -> bool:
85 """Returns True if the queue is empty, False otherwise.
86
87 There is some subtlety to interpreting this method's return value: see
88 `issue #63 <https://github.com/python-trio/trio/issues/63>`__.
89
90 """
91 return not self._data
92
93 @_core.enable_ki_protection
94 def put_nowait(self, obj: T) -> None:
95 """Put an object into the queue, without blocking.
96
97 This always succeeds, because the queue is unbounded. We don't provide
98 a blocking ``put`` method, because it would never need to block.
99
100 Args:
101 obj (object): The object to enqueue.
102
103 """
104 if not self._data:
105 assert not self._can_get
106 if self._lot:
107 self._lot.unpark(count=1)
108 else:
109 self._can_get = True
110 self._data.append(obj)
111
112 def _get_batch_protected(self) -> list[T]:
113 data = self._data.copy()
114 self._data.clear()
115 self._can_get = False
116 return data
117
118 def get_batch_nowait(self) -> list[T]:
119 """Attempt to get the next batch from the queue, without blocking.
120
121 Returns:
122 list: A list of dequeued items, in order. On a successful call this
123 list is always non-empty; if it would be empty we raise
124 :exc:`~trio.WouldBlock` instead.
125
126 Raises:
127 ~trio.WouldBlock: if the queue is empty.
128
129 """
130 if not self._can_get:
131 raise _core.WouldBlock
132 return self._get_batch_protected()
133
134 async def get_batch(self) -> list[T]:
135 """Get the next batch from the queue, blocking as necessary.
136
137 Returns:
138 list: A list of dequeued items, in order. This list is always
139 non-empty.
140
141 """
142 await _core.checkpoint_if_cancelled()
143 if not self._can_get:
144 await self._lot.park()
145 return self._get_batch_protected()
146 else:
147 try:
148 return self._get_batch_protected()
149 finally:
150 await _core.cancel_shielded_checkpoint()
151
152 def statistics(self) -> UnboundedQueueStatistics:
153 """Return an :class:`UnboundedQueueStatistics` object containing debugging information."""
154 return UnboundedQueueStatistics(
155 qsize=len(self._data),
156 tasks_waiting=self._lot.statistics().tasks_waiting,
157 )
158
159 def __aiter__(self) -> Self:
160 return self
161
162 async def __anext__(self) -> list[T]:
163 return await self.get_batch()