Context managers
Context managers
A context manager is a Python object which controls (to a certain extent) what occurs within a with
statement. Context managers relieve some of the burden placed on programmers. For example, if we open a file, and for some reason something goes wrong and an exception is raised, we still want to ensure that the file is closed. Before the introduction of the with
statement (in Python 2.5, almost twenty years ago), programmers often used try/finally statements (we’ll see more about try
when we get to exception handling).
We introduce with
and context managers in the context of file i/o, because this approach simplifies our code and ensures that when we’re done reading from or writing to a file that the file is closed automatically, without any need to explicitly call the .close()
method. The idiom we’ll follow is:
with open("somefile.txt") as fh:
# read from file
= fh.read() s
When we exit this block (that is, when all the indented code has executed), Python will close the file automatically. Without this context manager, we’d need to call .close()
explicitly, and failure to do so can lead to unexpected and undesirable results.
with
and as
are Python keywords. Here, with
creates the context manager, and as
is used to give a name to our file object. So once the file is opened, we may refer to it by the name given with as
—in this instance fh
(a common abbreviation for “file handle”).
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.