[Tutor] __getitem__
Alan Gauld
alan.gauld at freenet.co.uk
Tue Jan 17 19:00:36 CET 2006
>>>Nothing unless its implementation uses a while loop
>>>and index, but thats unlikely.
>>
>>
>> But that is pretty close to what actually happens, according to the
>> language ref docs for 'in' (see my previous post).
Only in certain cases. The point I was making (or trying to) is
that both loops actually depend on how iterators work - and
they currently use indexes, but the loops themselves don't. And
its quite possible, likely even, that generic iterator code could
appear that doesn't even store an index at all.
> PySequence_Contains() is implemented in abstract.c. If the container
> implements __contains__, that is called, otherwise
> _PySequence_IterSearch() is used.
And at this point we are out of the loop code and into iterator code
which it where the index is stored.
> So, though the details are complex, I think it is pretty fair to say
> that the implementation uses a while loop (in _PySequence_IterSearch())
> and a counter (wrapped in PySeqIter_Type) to implement 'in' on a
> container that defines __getitem__ but not __iter__.
I'd say the implementation uses a while loop which uses an iterator
and no counter - it relies on the iterator throwing an exception to
detect the end, the loop code has no index and neither does the 'in'
code. The 'in' is two levels of abstraction away from the index.
> By the way the implementation of 'for' also calls PyObject_GetIter(), so
> it uses the same mechanism to generate an iterator for a sequence that
> defines __getitem__().
Which is what I said, it relies on the iterator. (But I didn't know
about the legacy getitem() branch! ) In each case if the way iterators
work changes the loops will carry on as they are. I'm actually
surprised the C implementation uses an index, - I thought it would
just manipulate pointers - but given the getitem mechanism maybe
its not so surprising.
Thanks for doing the research - I was too lazy to do it myself ;-)
Alan G.
More information about the Tutor
mailing list