O'Reilly logo

Practical Maya Programming with Python by Robert Galanakis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required