[Tutor] special attributes naming confusion

Steven D'Aprano steve at pearwood.info
Thu Jun 7 01:28:07 CEST 2012


Prasad, Ramit wrote:
>> That is, for loops first try to build an iterator by calling __iter__, and if
>> that fails they try the sequence protocol obj[0], obj[1], obj[2], ...
> 
> So...I could instead write __getitem__ for the same effect?


Er, no... __getitem__ and __iter__ do very different things. __getitem__ 
returns individual items, and __iter__ returns an iterator object which, when 
passed to the next() builtin, returns the next item.

I trust you aren't calling __iter__ explicitly! Always call it from the 
built-in function iter(), or better still, don't call it at all and let the 
for loop do so.

For the record, here is pseudo-code emulating how Python for-loops work.
"for x in obj: do_something(x)" becomes something similar to this:

try:
     # Try the iterator protocol first.
     it = iter(x)
except TypeError:
     # Fall back on the old-fashioned sequence protocol.
     counter = 0
     while True:
         try:
             x = obj[counter]
         except IndexError:
             # We must be past the end of the sequence.
             del counter
             break
         do_something(x)
         counter += 1
else:
     # Iterator protocol.
     while True:
         try:
             x = next(it)
         except StopIteration:
             # We're done.
             del it
             break
         do_something(x)



-- 
Steven



More information about the Tutor mailing list