On Dec 11, 2019, at 07:43, Daniel Moisset <dfmoisset@gmail.com> wrote:
I think a solution nobody has proposed in this thread is relaxing the next builtin, so it calls iter() on the argument when it doesn't implement the iterator protocol. That would make next([1, 2]) == 1, and also make next([], "missing") == "missing".
while True:
yield (next(it), next(it))
I’ve seen this in real-life code, and more complicated versions of the same idea. What does it do? It gives you pairs of elements from it (not overlapping ones like pairwise, but adjacent ones). But with your chain, that’s no longer true. It gives you pairs of elements if it is an Iterator, infinite pairs of the first element twice if it’s a container. That’s no longer a useful function.
And consider Steven’s case of processing a file with a header. Even when you don’t need the optional second line of hyphens, it’s still a problem. The standard way to write that is:
def process(lines):
header = next(lines, '')
for line in lines:
do_stuff(header, line)
And with your change, calling it with a container (say because you called readlines, which you should almost never do but people actually do all the time) means it will fail silently and subtly instead of raising.
Compatibility-wise, it potentially turns TypeError raising code into non-raising code, which might make a difference if someone is catching this and doing something special with it, but IMHO I don't think that's something that should happen a lot
If someone is checking for an Iterator by EAFP’ing next instead of LBYL’ing collections.abc.Iterator, this would break their code. I don’t know how often people do that, but I don’t think code that does that would be wrong or bad; using EAFP instead of LBYL is usually considered a good thing in Python.
But also, most of the time, even when you aren’t testing for the error, you’re relying on it. The pairs and process functions above are only correct because of that TypeError. Take it away, and the standard idioms for at least two common things are no longer valid.