tags:

views:

488

answers:

2

What is the python keyword "with" used for?

Example from: http://docs.python.org/tutorial/inputoutput.html

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True
+4  A: 

See the proper section in What's new in Python 2.6.

+5  A: 

In python (and C#) the with keyword is used when working with unmanaged resources (like file streams). It creates the resource, performs the code in the block, then it closes the resource. It's similar to the Finally statement in a Try/Catch/Finally block, but without the error handling.

From Python Docs:

The ‘with‘ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The ‘with‘ statement is a control-flow structure whose basic structure is:

with expression [as variable]: with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has enter() and exit() methods).

Rob Allen
What methods are used to close the open resource? What if I made my own file system object that had its own special open/close methods, would the "with" keyword work with those? Or will "with" only work with the built-in Python resource types?
MikeN
In Python it looks like the custom object would have to implement (or inherit from something which implements) the `__enter__` and `__exit__` methods. With IronPython (python on .Net) you can implement from IDisposable and that will cover it. Not sure what is the best way in pure Python or other frameworks.
Rob Allen