3 ms·
> The for loop in python is a try/except catching StopIteration in a trench coat. That's...horrifying, both from a computational efficiency perspective (due to
by fouric 5y ago
> The for loop in python is a try/except catching StopIteration in a trench coat.
That's...horrifying, both from a computational efficiency perspective (due to the overhead of exceptions) and from a "beauty" perspective (exceptions are supposed to be exceptional, darn it!). Why is it implemented this way? Why not just use a normal loop and check a return value from the iterator?
- dragonwriter 5y ago> Why not just use a normal loop and check a return value from the iterator? Because an iterator needs to be able to return any python value, and if you did that, there would be at least one python value that an iterator could not actually return. Unless you required the iterator to wrap real return values in a container (basically, an optional/maybe monad) but then you have unwrapping overhead on every real return value, which is worse.
- fouric 5y agoCouldn't the runtime just allocate a specific Python object representing the case where the iterator is complete? Make that object implementation-specific, hide it as best as you can, write documentation stating that users should not use this value directly, and if they do - they voided the warranty, and should expect evil to befall them. (ultimately, you can't prevent the user from doing really dumb things e.g. editing the Python binary directly)
- dragonwriter 5y agoYou do that with one thing, okay, maybe it works. You do that with two or more of the protocols that Python has that use return values for return values ans exceptions for flow control signals and...you make it a lot harder to work with them, especially in conjunction.
- fouric 5y agoCan you give an example of this? I can't think of any myself - generators also raise a StopIteration exception, for instance, so they could use the same value.
- Scramblejams 5y agoexceptions are supposed to be exceptional, darn it This feeling is at odds with what is generally considered idiomatic Python, for better or worse. Upthread BiteCode mentioned EAFP. See, for example: https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/ https://devblogs.microsoft.com/python/idiomatic-python-eafp-... (It's certainly not unanimous. Guido himself is on the record as saying EAFP isn't better than LBYL, but in most of the Python I've cruised through these last umpteen years [that wasn't some other language written in Python], I've certainly seen an overall preference for EAFP. Naturally YMMV.)
- fouric 5y agoI think that implies that either "exceptions" are misnamed in Python (as in every other language with that name, they're meant to be exactly that - exceptional - so whatever Python calls "exceptions" isn't the same as in other languages), or that that particular idiom is wrong, and needs to be rethought.