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 ...

Get Practical Maya Programming with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.