by contravariant · 8y ago · 0 comments
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.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.
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.
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")