Files and exceptions
Exceptions instead of error codes: try/except/else/finally, the class hierarchy, EAFP, exception groups and notes; with and context managers; text, bytes and encodings, the file as a buffered iterator, pathlib, CSV and JSON on a small metrics file.
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.
Raising and catching
An exception is an object that describes an error. raise ValueError("loss is empty") creates one and abandons the normal flow of the program. To handle an exception, put the code that may fail in a try statement:
def parse_loss(text):
try:
value = float(text)
except ValueError as err:
print("except:", err)
return None
else:
print("else:", value)
return value
finally:
print("finally")
print(parse_loss("0.58"))
print(parse_loss(""))else: 0.58
finally
0.58
except: could not convert string to float: ''
finally
NoneThe rules behind this output:
- The body of
tryruns. If it raises nothing,elseruns, thenfinally. - If it raises, the
exceptclauses are tested in order. The first whose class matches runs, witherrbound to the exception. Thenfinallyruns. - If no clause matches,
finallyruns and the exception goes on to the caller. finallyruns even when the body or a handler leaves throughreturn,breakorcontinue. Here it printed before the caller'sprintreceived the value.
The else clause keeps the try body down to the one line that can fail. The name err is deleted when its clause ends.
Where does an unhandled exception go? Each call has a frame on the call stack (see the topic Functions). Python looks for a matching handler in the current frame. If there is none, it discards the frame and looks in the caller, and so on up the stack. The traceback lists the frames it passed through. If no frame handles the exception, the interpreter prints the traceback and stops, as in the topic Running Python. Since Python 3.11 a try costs nothing while nothing is raised.
A bare raise inside a handler re-raises the exception being handled. raise New(...) from err raises a new one and records the old one as its cause, and the traceback shows both:
def get_setting(config, key):
try:
return config[key]
except KeyError as err:
raise RuntimeError(f"missing setting {key!r}") from err
get_setting({"epochs": 3}, "lr")Traceback (most recent call last):
...
KeyError: 'lr'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
...
RuntimeError: missing setting 'lr'Two changes in Python 3.14. except ValueError, TypeError: may list several classes without parentheses when there is no as (PEP 758). A return, break or continue that leaves a finally block now draws a SyntaxWarning, because it silently throws away any exception in flight (PEP 765).
Which errors to catch
Exceptions are classes in one hierarchy rooted at BaseException. except C catches instances of C and of all its subclasses. Here is a small part of the tree:
BaseException
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ └── ZeroDivisionError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── OSError
│ ├── FileNotFoundError
│ └── PermissionError
├── TypeError
└── ValueError
└── UnicodeError
└── UnicodeDecodeErrorThe middle layer holds categories worth catching whole: LookupError for any failed [] lookup, OSError for any failure reported by the operating system, ValueError for a value of the right type with the wrong content. A missing dict key is a KeyError, so a handler for the whole category catches it:
config = {"epochs": 3}
try:
config["lr"]
except LookupError as err:
print(type(err).__name__, err)KeyError 'lr'KeyboardInterrupt (Ctrl-C) and SystemExit (from sys.exit()) sit outside Exception on purpose, so that a handler for program errors lets them through.
The mistakes. A bare except: or except BaseException: catches Ctrl-C too, and the program refuses to stop. except Exception: around a large block hides bugs, such as a NameError from a typo, behind the handling meant for one expected failure. Catch the narrowest class that describes the failure you expect, around the fewest lines that can raise it. A library defines its own errors as subclasses, for example class MetricsError(ValueError): pass. The topic Classes and objects explains what class means.
There are two styles of handling an operation that may fail. LBYL ("look before you leap") checks first: if key in d: use(d[key]). EAFP ("easier to ask forgiveness than permission") tries and handles the failure. Python leans to EAFP, especially for files:
from pathlib import Path
path = Path("runs/exp2/metrics.csv")
try:
text = path.read_text(encoding="utf-8")
except FileNotFoundError as err:
print("no file:", err.filename)
text = ""no file: runs/exp2/metrics.csvFor anything outside the program, a check can go stale. The file can change between the check and the use, a time-of-check to time-of-use race. The cost depends on how often the operation fails. A try is free when nothing is raised, but raising and catching costs extra: on one laptop a missing dict key cost about 130 ns with try/except KeyError against 40–50 ns with in or dict.get (timings depend on the machine). When failure is common, as with missing keys, dict.get and defaultdict from the topic Dictionaries and sets are the better tools.
Several errors at once
Sometimes several unrelated errors happen at once: a check of one CSV row finds two bad values and a missing column. Raising only the first one hides the rest. Python 3.11 added ExceptionGroup, an exception that carries a list of exceptions:
def check(row):
errors = []
if float(row["loss"]) < 0:
errors.append(ValueError("loss must be non-negative"))
if not 0 <= float(row["accuracy"]) <= 1:
errors.append(ValueError("accuracy must be in [0, 1]"))
if "epoch" not in row:
errors.append(KeyError("epoch"))
if errors:
raise ExceptionGroup("bad row", errors)The except* clause handles the members of a group by class:
try:
check({"loss": "-0.1", "accuracy": "1.2"})
except* ValueError as eg:
print("values:", [str(e) for e in eg.exceptions])
except* KeyError as eg:
print("keys:", [str(e) for e in eg.exceptions])values: ['loss must be non-negative', 'accuracy must be in [0, 1]']
keys: ["'epoch'"]Each except* C receives the subgroup of members that match C, itself an exception group. The clauses run one after another, so one raise can trigger several of them, unlike except. Members that no clause matches are raised again together. A plain except ValueError does not catch the group at all, because an ExceptionGroup is not a ValueError. Unhandled, a group prints as a tree with one branch per member. The topic Concurrency: threads, processes and asyncio meets groups again: asyncio.TaskGroup raises one for the tasks that failed.
A note adds context to an exception without changing its type. An error raised deep inside a parser rarely says which file and which line it came from. Since Python 3.11, err.add_note(text) attaches a line that the traceback prints after the message:
try:
float("0,49")
except ValueError as err:
err.add_note("metrics.csv, line 5")
raiseTraceback (most recent call last):
...
ValueError: could not convert string to float: '0,49'
metrics.csv, line 5The standard library does this too. In Python 3.14, json.dumps({"tags": {"a"}}) fails on the set with the note when serializing dict item 'tags', which points at the culprit inside a large structure.
Clean-up that always runs
A file must be closed even when the code that writes to it fails. try/finally can do it:
f = open("run.log", "w", encoding="utf-8")
try:
f.write("epoch 1\n")
1 / 0
finally:
f.close()This works, but every caller has to remember the clean-up. A context manager packages the set-up and the clean-up in one object, and the with statement applies it:
with open("run.log", "w", encoding="utf-8") as f:
f.write("epoch 1\n")The rule: with expr as name: body evaluates expr to a context manager and calls its __enter__(). The result is bound to name, and the body runs. Then Python calls the manager's __exit__(exc_type, exc, tb) however the body ended: with the type, value and traceback of the exception, or with three Nones. If __exit__ returns a true value, the exception is suppressed; otherwise it goes on. A file's __enter__ returns the file itself, and its __exit__ closes it. with A() as a, B() as b: is the same as nesting the with for B inside the one for A.
Writing __enter__ and __exit__ as methods of our own type waits for the topics Classes and objects and The data model. There is a shortcut that needs only a generator. contextlib.contextmanager turns a generator function with one yield into a context manager. The code before yield is the set-up, the yielded value is what as binds, and a finally around the yield is the clean-up:
from contextlib import contextmanager
@contextmanager
def stage(name):
print("start", name)
try:
yield name.upper()
finally:
print("end", name)
with stage("train") as label:
print("inside", label)
1 / 0start train
inside TRAIN
end train
Traceback (most recent call last):
...
ZeroDivisionError: division by zero__enter__ runs the generator up to its yield. __exit__ resumes it there, throwing in the exception if the body raised one, so the finally runs and the exception goes on. It is the generator protocol put to a new use. contextlib.suppress(E) is a ready-made manager whose __exit__ returns true for exceptions of class E. Other common managers: threading.Lock, tempfile.TemporaryDirectory, and torch.no_grad(), which the Deep Learning course uses to switch off gradient recording.
Text and bytes
open(path, mode, encoding=..., newline=...) returns a file object. The mode combines r (read, the default), w (write, emptying the file first), a (append), x (create, failing if the file exists), + (read and write), and t (text, the default) or b (binary). A text file reads and writes str, decoding and encoding with the given encoding. A binary file reads and writes bytes unchanged.
from pathlib import Path
p = Path("models.csv")
with open(p, "w", encoding="utf-8") as f:
print(f.write("model,loss\n"))
print(f.write("naïve-bayes,0.58\n"))
data = p.read_bytes()
print(data)
print(len(data))11
17
b'model,loss\nna\xc3\xafve-bayes,0.58\n'
29write returns the number of characters written, 28 in total. The file holds bytes, and in UTF-8 the ï takes two of them (topic Strings and text), so the file is 29 bytes long. Bytes mean nothing without the encoding that produced them. Read with the wrong one, the same file is garbled or refused:
with open("models.csv", encoding="latin-1") as f:
print(f.read(), end="")
with open("models.csv", encoding="ascii") as f:
f.read()model,loss
naïve-bayes,0.58
Traceback (most recent call last):
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128)Latin-1 maps every byte to some character, so it never fails and silently produces nonsense. ASCII knows only bytes below 128 and stops at the first other one.
The mistake is to leave encoding out. Python 3.14 then uses the locale's encoding, locale.getencoding(). That is UTF-8 on most macOS and Linux machines and often a legacy code page such as cp1252 on Windows, so one script reads one file differently on two machines. Always pass encoding="utf-8" for text. python -X warn_default_encoding warns wherever it is missing, and Python 3.15 makes UTF-8 the default (PEP 686).
Binary mode is for data that is not text: images, archives, NumPy's .npy files, model weights. In text mode, line endings \r\n are turned into \n on reading; the csv module handles them itself and asks for newline="".
What an open file is
What is the object that open returns? A text file is three objects stacked on top of each other:
f = open("models.csv", encoding="utf-8")
print(f)
print(type(f.buffer).__name__, type(f.buffer.raw).__name__, f.fileno())
print(iter(f) is f)
for line in f:
print(repr(line))
f.close()<_io.TextIOWrapper name='models.csv' mode='r' encoding='utf-8'>
BufferedReader FileIO 3
True
'model,loss\n'
'naïve-bayes,0.58\n'FileIOat the bottom holds the operating system's file descriptor, a small number: 3 here, since 0, 1 and 2 are the standard streams. Each of its reads is one request to the operating system.BufferedReaderasks for large blocks, 128 KiB by default in 3.14 (io.DEFAULT_BUFFER_SIZE), and hands them out in small pieces. Reading line by line does not cost one request per line.TextIOWrapperdecodes the bytes intostrwith the encoding.
Writing is buffered too. Data written to a file may sit in memory until the buffer fills, f.flush() is called or the file is closed. Read the file from elsewhere before that, and it looks empty. That is the practical reason for with open(...): closing flushes the buffer and returns the descriptor, even when the body fails. A program that opens thousands of files and never closes them runs out of descriptors. Reading from a closed file raises ValueError: I/O operation on closed file.
A file object is an iterator over its lines, as iter(f) is f shows: the protocol from the topic Iteration, comprehensions and generators. f.read() returns the whole file as one string and f.readlines() a list of all lines. for line in f returns one line at a time and reads the next block only when the buffer runs out. next(f) takes a single line, handy for a header. Measured with tracemalloc on one machine, f.read() on a 6 MB CSV peaked at about 12.7 MB, the bytes and the decoded string at once. The loop stayed near 0.15 MB, mostly the buffer, whatever the size of the file. That is how a file larger than memory feeds a generator pipeline.
Paths, CSV and JSON
pathlib.Path makes a path an object rather than a string. The / operator joins parts with the right separator for the system, and the parts of a name are attributes. On macOS and Linux a path is a PosixPath:
from pathlib import Path
path = Path("runs") / "exp1" / "metrics.csv"
print(repr(path))
print(path.name, path.stem, path.suffix, path.parent)
print(path.exists(), sorted(str(p) for p in Path("runs").rglob("*.csv")))PosixPath('runs/exp1/metrics.csv')
metrics.csv metrics .csv runs/exp1
True ['runs/exp1/metrics.csv']read_text and write_text open, read or write, and close in one call; glob and rglob find files by pattern, the second in all subdirectories. A relative path is resolved against the current working directory, where the program was started, not the folder of the script. A script that must find its own files builds paths from Path(__file__).parent.
CSV. Splitting lines on commas breaks as soon as a field holds a quoted comma, so use the csv module. csv.DictReader yields one dict per row, keyed by the header:
import csv
from pathlib import Path
path = Path("runs") / "exp1" / "metrics.csv"
with open(path, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print(rows[0])
best = min(rows, key=lambda r: float(r["loss"]))
print(best["epoch"], best["loss"]){'epoch': '1', 'loss': '0.92', 'accuracy': '0.61'}
3 0.58Every field comes back as a string and must be converted. The topic Data frames with pandas reads CSV with pd.read_csv, which infers the types.
JSON stores nested data, and its values map to Python types: objects to dict, arrays to list, strings to str, numbers to int or float, true/false to bool, null to None. json.dumps and json.loads convert to and from strings, json.dump and json.load to and from files:
import json
config = {"lr": 0.001, "layers": (64, 32), "dropout": None, "seeds": {0: "a"}}
text = json.dumps(config)
print(text)
back = json.loads(text)
print(back == config, back["layers"], back["seeds"]){"lr": 0.001, "layers": [64, 32], "dropout": null, "seeds": {"0": "a"}}
False [64, 32] {'0': 'a'}The round trip changed the data: the tuple came back as a list and the key 0 as the string "0". Sets and NumPy arrays need a conversion before they can be written at all. JSON is not Python syntax either: json.loads("{'lr': 1}") raises json.JSONDecodeError, a subclass of ValueError, because JSON strings need double quotes.
Now everything at once. This generator reads the metrics lazily, closes the file through with, and adds the line number to any bad value:
import csv
def read_metrics(path):
with open(path, newline="", encoding="utf-8") as f:
for line_no, row in enumerate(csv.DictReader(f), start=2):
try:
yield int(row["epoch"]), float(row["loss"])
except ValueError as err:
err.add_note(f"{path.name}, line {line_no}")
raiseWith path the Path of the file above, min(read_metrics(path), key=lambda pair: pair[1]) gives (3, 0.58). Append a row 4,,0.79 with an empty loss, and list(read_metrics(path)) ends with:
ValueError: could not convert string to float: ''
metrics.csv, line 5This closes the module on data structures. Several objects in it behaved like built-ins because they follow a protocol: iterators have __iter__ and __next__, context managers have __enter__ and __exit__. Exception types are classes, so except ValueError also catches its subclasses. A file object is an instance of TextIOWrapper. And each row is a plain dict, so nothing stops a typo like row["los"] until it fails at run time. The next topic, Classes and objects, shows how to write such types ourselves: how an instance is made, where its attributes live and how one class extends another.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.