]> granicus.if.org Git - python/commitdiff
bpo-31145: Use dataclasses to create a prioritization wrapper (#5153)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Fri, 12 Jan 2018 06:06:34 +0000 (22:06 -0800)
committerGitHub <noreply@github.com>
Fri, 12 Jan 2018 06:06:34 +0000 (22:06 -0800)
Doc/library/heapq.rst
Doc/library/queue.rst

index e36ca8d7b34b1338eb69c62e6d054cd3bf6e46c8..0b1a3c8b00ceb5a90f6b68021ae2a49a11046578 100644 (file)
@@ -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 ignores the task item and only compares the priority field::
+
+    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.
index bd0fc2d8f3c735d6b82e444b1d25fdc171972725..f9a43bbac3bcc678d147868fb72e36dc265e794c 100644 (file)
@@ -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