Skip to content

Commit 0c3be96

Browse files
authored
bpo-31145: Use dataclasses to create a prioritization wrapper (#5153)
1 parent 02556fb commit 0c3be96

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Doc/library/heapq.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,17 @@ a tie-breaker so that two tasks with the same priority are returned in the order
187187
they were added. And since no two entry counts are the same, the tuple
188188
comparison will never attempt to directly compare two tasks.
189189

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+
190201
The remaining challenges revolve around finding a pending task and making
191202
changes to its priority or removing it entirely. Finding a task can be done
192203
with a dictionary pointing to an entry in the queue.

Doc/library/queue.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ The :mod:`queue` module defines the following classes and exceptions:
5656
one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
5757
is a tuple in the form: ``(priority_number, data)``.
5858

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)
5969

6070
.. exception:: Empty
6171

0 commit comments

Comments
 (0)