4 ms·
For what it's worth you could also write that as: result = '' for b in file_bytes_iterator: if b == '\0': break result += b if b != '\0
by contravariant 8y ago
For what it's worth you could also write that as:
result = ''
for b in file_bytes_iterator:
if b == '\0': break
result += b
if b != '\0':
throw ValueError("String is unterminated")
And while we're one the subject, I would also really like to have a construction like:
result = ''
while b != '\0' for b in file_bytes_iterator:
result += b
if b != '\0':
throw ValueError("String is unterminated")
but I fear opinion might be divided on that one.
- kd5bjo 8y agoIt's a syntax sugar feature, so its presence or absence will make little difference in the grand scheme of things -- there will always be a relatively easy way to rewrite code without it. Personally, I would prefer the loop iteration variable to only be in scope within the loop body, and generally write code as if that were true. Also, repeating the sentinel test is asking for a future edit to change one and miss the other.
- fyi1183 8y agoYour suggested replacement duplicates the break condition, which is not ideal for maintainability. Also, it only happens to work due to Python's variable scoping rules. I have wished for a for-else construct in C and C++ many times: having to broaden the scope of a loop iteration variable just to duplicate a loop break check really sucks.
- kd5bjo 8y agoAfter letting it steep overnight, I came up with this variant which addresses most of the issues that have come up in this thread: try: result = '' while (b = next(file_bytes_iterator)) != '\0': result += b # maybe parse more of the file here except StopIteration: throw ValueError("Unexpected end of file")