[Python-Dev] Re: heaps

Michael Chermside mcherm@mcherm.com
Tue, 6 May 2003 05:32:03 -0700


Zooko writes:
> Shouldn't heapq be a subclass of list?
  [...]
> One thing I don't know how to implement is:
> 
> # This changes mylist itself into a heapq -- it doesn't make a copy of mylist!
> makeheapq(mylist)
> 
> Perhaps this is a limitation of the current object model?  Or is there a way
> to change an object's type at runtime.

To change an object's CLASS, sure, but it's TYPE -- seems impossible to me on 
the face of it since a different type may have a different C layout. Now in
THIS case there's no need for a different C layout, so perhaps there's some
wierd trick I don't know, but I wouldn't think so.

As to your FIRST point though... the choice seems to be between making heapq
a subclass of list or a module for operating on a list. You argue that the
syntax will be cleaner, but comparing your examples:

> heap = []
> heappush(heap, item)
> item = heappop(heap)
> item = heap[0]

> heap = heapq()
> heap.push(item)
> item = heap.pop()
> item = heap[0]

I honestly see little meaningful difference. Since (as per earlier discussion)
heapq is NOT intended to be a abstract heap data type, I tend to prefer the
simpler solution (using a list instead of subclassing).

-- Michael Chermside