[Python-ideas] __len__() for map()
Greg Ewing
greg.ewing at canterbury.ac.nz
Sat Dec 1 05:44:07 EST 2018
Adam Johnson wrote:
> def takewhile_lessthan4(x):
> if x < 4:
> return x
> raise StopIteration
>
> tuple(map(takewhile_lessthan4, range(9)))
> # (0, 1, 2, 3)
>
> I really don't understand why this is true, under 'normal' usage, map
> shouldn't have any reason to silently swallow a StopIteration raised
> _within_ the mapped function.
It's not -- the StopIteration isn't terminating the map,
it's terminating the iteration being performed by tuple().
It's easy to show that map() is not swallowing the
StopIteration:
>>> m = map(takewhile_lessthan4, range(9))
>>> next(m)
0
>>> next(m)
1
>>> next(m)
2
>>> next(m)
3
>>> next(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in takewhile_lessthan4
StopIteration
--
Greg
More information about the Python-ideas
mailing list