The with statement is actually a quite general construct, allowing you to use so-called context managers. A context manager is an object that supports two methods: __enter__ and __exit__. Like:
class controlled_execution:
def __enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear thing down
with controlled_execution() as thing:
some code
The __enter__ method takes no arguments. It is called when entering the with statement, and the return value is bound to the variable after the as keyword.
The __exit__ method takes three arguments: an exception type, an exception object, and an exception traceback. It is called when leaving the method (with any exception raised supplied through the parameters). If __exit__ returns false, any exceptions are suppressed.
Files may be used as context managers. Their __enter__ methods return the file objects themselves, while their __exit__ methods close the files.
with open("somefile.txt") as somefile: #somefile is a file-like object returned by open()
do_something(somefile)
For more information about this powerful, yet rather advanced, feature, check out the description of context managers in the Python Reference Manual.