bpo-31145: Use dataclasses to create a prioritization wrapper (#5153) · python/cpython@0c3be96 (original) (raw)
2 files changed
lines changed
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -187,6 +187,17 @@ a tie-breaker so that two tasks with the same priority are returned in the order | ||
187 | 187 | they were added. And since no two entry counts are the same, the tuple |
188 | 188 | comparison will never attempt to directly compare two tasks. |
189 | 189 | |
190 | +Another solution to the problem of non-comparable tasks is to create a wrapper | |
191 | +class that ignores the task item and only compares the priority field:: | |
192 | + | |
193 | + from dataclasses import dataclass, field | |
194 | + from typing import Any | |
195 | + | |
196 | + @dataclass(order=True) | |
197 | + class PrioritizedItem: | |
198 | + priority: int | |
199 | + item: Any=field(compare=False) | |
200 | + | |
190 | 201 | The remaining challenges revolve around finding a pending task and making |
191 | 202 | changes to its priority or removing it entirely. Finding a task can be done |
192 | 203 | with a dictionary pointing to an entry in the queue. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -56,6 +56,16 @@ The :mod:`queue` module defines the following classes and exceptions: | ||
56 | 56 | one returned by ``sorted(list(entries))[0]``). A typical pattern for entries |
57 | 57 | is a tuple in the form: ``(priority_number, data)``. |
58 | 58 | |
59 | + If the *data* elements are not comparable, the data can be wrapped in a class | |
60 | + that ignores the data item and only compares the priority number:: | |
61 | + | |
62 | + from dataclasses import dataclass, field | |
63 | + from typing import Any | |
64 | + | |
65 | + @dataclass(order=True) | |
66 | + class PrioritizedItem: | |
67 | + priority: int | |
68 | + item: Any=field(compare=False) | |
59 | 69 | |
60 | 70 | .. exception:: Empty |
61 | 71 |