Note: I am all for not enforcing anything here -- let's keep duck typing alive!
If static type checkers want to be more pedantic, they can be -- that's kinda what they are for :-)
But the OP wrote:
"""
"[i]terators are required to have an
__iter__()
method" which neither `for` nor `iter()` actually enforce.
"""
I'm confused -- as far as I can tell `for` does enforce this -- well, it doesn't enforce it, but it does require it, which is the same thing, yes? But does it need to?
Reminder about how for-loops work:
This:
for x in seq:
<body>
translates (roughly) to this:
_it = iter(seq)
while True:
try:
x = next(_it)
except StopIteration:
break
<body>
exactly -- that call to iter is always made, yes?
The "trick" here is that we want it to be easy to use a for loop with either an iterable or an iterator. Otherwise, we would require people to write:
for i in iter(a_sequence):
...
which I doubt anyone would want, backward compatibility aside.
And since iter() is going to always get called, we need __iter__ methods that return self.
However, I suppose one could do a for loop something like this instead.
_it = seq
while True:
try:
x = next(_it)
except TypeError:
_it = iter(_it)
x = next(_it)
except StopIteration:
break
That is, instead of making every iterator an iterable, keep the two concepts more distinct:
An "Iterator" has a __next__ method that returns an item or raises StopIteration.
An "Iterable" has an __iter__ method that returns an iterator.
That would mean that one couldn't write a single class that is both an iterable and an iterator, and uses (abuses) __iter__ to reset itself. But would that be a bad thing?
Anyway, this is just a mental exercise, I am not suggesting changing anything.
-CHB
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker@noaa.gov