[Python-ideas] Adding a thin wrapper class around the functions in stdlib.heapq

Sebastian Kreft skreft at gmail.com
Mon Nov 20 21:38:18 EST 2017


This has been brought up multiple times. Last time was on this thread
https://mail.python.org/pipermail/python-ideas/2016-October/043024.html.

On Tue, Nov 21, 2017 at 3:13 AM, bunslow <bunslow at gmail.com> wrote:

> Nothing so bombastic this time. The heapq functions are basically all
> named "heapsomething", and basically all take a "heap" for their first
> argument, with supplementary args coming after. It's a textbook example of
> the (hypothetical) Object Oriented Manifesto™ where defining a class
> increases type safety and programmers' conceptual clarity. There're
> practically no drawbacks, and the code to be added would be very simple.
> Updating the tests and docs would probably be harder.
>
> In pure Python, such a class would look like this:
>
> class Heap(list):
>
>     def __init__(self, iterable=None):
>         if iterable:
>             super().__init__(iterable)
>         else:
>             super().__init__()
>
>         self.heapify()
>
>     push = heapq.heappush
>     pop = heapq.heappop
>     pushpop = heapq.heappushpop
>     replace = heapq.heapreplace
>     heapify = heapq.heapify
>
>     # This could be a simple wrapper as well, but I had the following
> thoughts anyways, so here they are
>     def nsmallest(self, n, key=None):
>         # heapq.nsmallest makes a *max* heap of the first n elements,
>         # while we know that self is already a min heap, so we can
>         # make the max heap construction faster
>         self[:n] = reversed(self[:n])
>         return heapq.nsmallest(n, self, key)
>
>     # do we define nlargest on a minheap??
>
>
> Wrapping around the C builtin functions (which aren't descriptors) would
> be a bit harder, but not much so:
>
> from functools import partial
>
> class Heap(list):
>     def __init__(self, iterable=None):
>         if iterable:
>             super().__init__(iterable)
>         else:
>             super().__init__()
>
>         self.heapify = partial(heapq.heapify, self)
>         self.push = partial(heapq.heappush, self)
>         ...
>
>         self.heapify()
>
>
> Thoughts?
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>


-- 
Sebastian Kreft
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171121/22472b8b/attachment-0001.html>


More information about the Python-ideas mailing list