[Tutor] special attributes naming confusion

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Jun 7 19:07:29 CEST 2012


> >> 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.
> 

I never call __iter__ and rarely call iter; usually I just let
Python handle all that.

> 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]

Does this access not use __getitem__()? Not that I would ever
use this in reality, but it is interesting to note.

>          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)

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list