From 086b1ccf6dbb28cf481e7e6e8027de947a5e767c Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Thu, 11 Jan 2018 00:48:50 -0800 Subject: [PATCH 1/2] Use dataclasses to create a prioritization wrapper --- Doc/library/heapq.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Doc/library/heapq.rst b/Doc/library/heapq.rst index e36ca8d7b34b133..b8495143505ada2 100644 --- a/Doc/library/heapq.rst +++ b/Doc/library/heapq.rst @@ -187,6 +187,17 @@ a tie-breaker so that two tasks with the same priority are returned in the order they were added. And since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks. +Another solution to the problem of non-comparable tasks is to create a wrapper +class that only compares the priority and ignores the task item: + + from dataclasses import dataclass, field + from typing import Any + + @dataclass(order=True) + class PrioritizedItem: + priority: int + item: Any=field(compare=False) + The remaining challenges revolve around finding a pending task and making changes to its priority or removing it entirely. Finding a task can be done with a dictionary pointing to an entry in the queue. From a4316a55cd4ae94c22fea57d5d0ed7f9552e8641 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Thu, 11 Jan 2018 21:51:25 -0800 Subject: [PATCH 2/2] Fix markup and add entry to the queue docs --- Doc/library/heapq.rst | 2 +- Doc/library/queue.rst | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Doc/library/heapq.rst b/Doc/library/heapq.rst index b8495143505ada2..0b1a3c8b00ceb5a 100644 --- a/Doc/library/heapq.rst +++ b/Doc/library/heapq.rst @@ -188,7 +188,7 @@ they were added. And since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks. Another solution to the problem of non-comparable tasks is to create a wrapper -class that only compares the priority and ignores the task item: +class that ignores the task item and only compares the priority field:: from dataclasses import dataclass, field from typing import Any diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst index bd0fc2d8f3c735d..f9a43bbac3bcc67 100644 --- a/Doc/library/queue.rst +++ b/Doc/library/queue.rst @@ -56,6 +56,16 @@ The :mod:`queue` module defines the following classes and exceptions: one returned by ``sorted(list(entries))[0]``). A typical pattern for entries is a tuple in the form: ``(priority_number, data)``. + If the *data* elements are not comparable, the data can be wrapped in a class + that ignores the data item and only compares the priority number:: + + from dataclasses import dataclass, field + from typing import Any + + @dataclass(order=True) + class PrioritizedItem: + priority: int + item: Any=field(compare=False) .. exception:: Empty