Bug in Python?

Terry Reedy tjreedy at udel.edu
Sat Feb 27 03:55:32 EST 2016


On 2/26/2016 6:07 PM, eryk sun wrote:
>   On Fri, Feb 26, 2016 at 4:08 PM, Sven R. Kunze <srkunze at mail.de> wrote:
>> Python sometimes seems not to hop back and forth between C and Python code.
>> Can somebody explain this?
>
> Normally a C extension would call PySequence_SetItem, which would call
> the type's sq_ass_item, which for MyList is slot_sq_ass_item. The
> latter function bridges the CPython and Python sides by binding and
> calling the overridden __setitem__ method.  However, the _heapq
> extension module uses `PyList_SET_ITEM(heap, 0, lastelt)`. This macro
> expands to `((PyListObject *)(heap))->ob_item[0] = lastelt`. This
> directly modifies the internal ob_item array of the list, so the
> overridden __setitem__ method is never called. I presume it was
> implemented like this with performance in mind, but I don't know
> whether or not that justifies the loss of generality.

In other words, when that doc says *list*, it means a *list*.

"To create a heap, use a list initialized to [], or you can transform a 
populated list into a heap via function heapify()."

Note: when the doc says 'dict' rather than 'dictionary' or 'mapping', it 
is pretty obvious it means builtin dict.  It may sometimes say 'dict or 
dict subclass'.  Ditto for 'str' versus 'string' or 'text'.  However, 
'list' (Python builtin) and generic 'list are easy to confuse.  In this 
case, 'initialized to []' is a hint.  However, the doc could be made 
clearer. How about

"A heap must be an instance of *list* (and not a subclass thereof).  To 
create a heap, start with [] or transform an existing list into a heap 
via function heapify()."

*list* means to display it blue, linked to the list class.


-- 
Terry Jan Reedy




More information about the Python-list mailing list