4 ms·
Interestingly, Python uses exceptions for basic control flow, like end of for-loop.
by eru 3y ago
Interestingly, Python uses exceptions for basic control flow, like end of for-loop.
- callamdelaney 3y agoWell it uses exceptions in the case your generator is at the end, not usually at the end of a for loop because a for loop by definition iterates over a list until the list is finished. The exception actually occurs when you call next() on a generator which cannot return any more values, or is finished, in which case `StopIteration` is usually raised.
- oasisaimlessly 3y agoAll Python iterators raise StopIteration at the end of iteration. For-loops always use the iterator protocol. Neither generators nor lists are special in this regard. >>> next(iter([])) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> next(iter((lambda: (yield 5) if False else None)())) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
- koliber 3y agoSemantically, Python separates Exceptions and Errors. The mechanism for throwing and catching them is the same. Here's a quick description from somewhere on the interwebs: An error is an issue in a program that prevents the program from completing its task. In comparison, an exception is a condition that interrupts the normal flow of the program. Then there is StopIteration, which does not fit well into either of the two above. It's a wart I've learned to treat as a beauty mark.
- eru 3y agoWell, by your definition of Exceptions and Errors, errors are something that Python, the formal language as understood by the computer, doesn't know anything about. It's a concept for humans that they can use when analysing programs. And different analyses might come to different conclusions. [0] You could signal errors via eg returning None or False or throwing an exception. But not throwing an exception could also be an error. (Eg if your for-loop never ends, that might be an error. And that would be synonymous with StopIteration never being thrown.) [0] Eg for a program like 'cat' it would normally be considered an error, when the file being read doesn't exist. But perhaps in my particular usage, that's expected to occur quite often, and is a normal part of my operation. You can translate this example to Python: FileNotFound might be an error, or a normal condition.