From generators to files
The topic Iteration, comprehensions and generators built lazy pipelines: a data loader generator that pulls records one at a time and cuts them into batches. Every item in that topic was produced inside the program, and the topic ended on a row n/a,1 that stopped the pipeline with a ValueError. Real data lives in files: the metrics a training run writes, a JSON config, a corpus of text.
The running example of this topic is a small metrics file, metrics.csv:
epoch,loss,accuracy
1,0.92,0.61
2,0.71,0.70
3,0.58,0.76Reading it brings two problems that generators could ignore. Operations fail for reasons the program does not control: the file is missing, the disk is full, a field is empty where a number should be. And an open file is a resource that the operating system lends to the program, so it must be given back however the code that uses it ends.
Python answers the first problem with exceptions and the second with context managers and the with statement.
Why exceptions at all? The alternative is to report failure through the return value. str.find works this way: it returns the position of a substring, or -1 if there is none.
name = "metrics.csv"
print(name.find(".json"))
print(name[name.find(".json")])
print(name.index(".json"))-1
v
Traceback (most recent call last):
...
ValueError: substring not foundNothing forced the caller to check the -1. Used as an index, it silently picked the last character, because negative indices count from the end. str.index does the same search but raises an exception, so the program cannot go on as if the search had succeeded. In this topic, ... in a traceback stands for the lines with file names and positions.