Introducing context managers
Context managers are explained in detail in PEP 343: The "with" statement (http://www.python.org/dev/peps/pep-0343/). You shouldn't bother reading it unless you really care about the intricacies of Python itself. In simple terms, it adds the with
keyword to Python, so statements like the following are possible:
>>> with open('myfile.txt') as f: ... text = f.read()
These two lines open a file for reading, and assign the contents of the file to the text
variable. It uses the open
function as a context manager. It is almost equivalent to these three lines:
>>> f = open('myfile.txt') >>> text = f.read() >>> f.close()
This naive code harbors a potential problem. If calling f.read()
raises an exception, the file's close
method is never called. The file may be opened and locked by Python until the process dies. Ideally, we'd want to make sure the file is closed if an error happens. We...