Strange range

Rob Gaddi rgaddi at highlandtechnology.invalid
Fri Apr 1 16:21:12 EDT 2016


Marko Rauhamaa wrote:

> Erik <python at lucidity.plus.com>:
>
>> On 01/04/16 15:34, Marko Rauhamaa wrote:
>>> Chris Angelico <rosuav at gmail.com>:
>>>
>>>> *A range object is not an iterator.*
>>>
>>> We now have learned as much.
>>>
>>> However, doesn't that extra level of indirection seem like an odd
>>> choice?
>>
>> [...]
>>
>> If you write your own class which has an __iter__ method, would you
>> [...] expect both iterators to be independent and both return the
>> 'foo', 'bar', 'baz' sequence (where that is the hypothetical result of
>> iterating over your object)?
>>
>> If you now replace MyClass() with range(10), why would you expect the
>> two iterators to be related?
>
> I simply had thought of range() returning an iterator. I would expect an
> iterator to behave like one.
>
> There's a bit of a cognitive dissonance between iterables and iterators.
> On the one hand, they behave identically in many contexts. On the other
> hand, the distinction is crucial in some special cases.

You're missing a key point.  All (well-behaved) iterators are iterables,
with their __iter__ method returning themselves.

for x in y:
  ...

implies:

try:
  _it = iter(y)
  while True:
    x = next(_it)
    ...
except StopIteration:
  pass

That's true for any iterable y, including a y which is itself an
iterator.  You still call iter() on it, and get _it, the iterator over
y, which if y is an iterator is the same thing as y.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list