[Python-Dev] Possible context managers in stdlib (original) (raw)

Terry Reedy tjreedy at udel.edu
Tue Jul 12 21:38:44 CEST 2005


"Nick Coghlan" <ncoghlan at gmail.com> wrote in message news:42D3A766.90705 at gmail.com...

The main outcome of the PEP 343 terminology discussion was some proposed documentation I put on the Sourceforge patch tracker ([1]).

Is this a proposal for the Language Reference manual?

[1] http://www.python.org/sf/1234057 ========================================== With Statements and Context Management

A frequent need in programming ... A simpler way to achieve this in Python is to use the 'with' statement along with the appropriate context manager.

Somewhere about here we need the syntax itself.

Context managers define an... the contained suite starts. If the 'as' clause of the 'with'

Else this does not mean much. ...

The simplest use of context management is to strictly control the handling of key resources (such as files, generators, database connections, synchronisation locks).

I have a little trouble seeing generators (as opposed to iterables) as resources needing management.

For example, the following context manager allows prompt closure of any resource with a 'close' method (e.g. a generator or file):

And I was not aware that they had close methods. You mean a iterable (not just a file) with both an associated generator and a close? Or are generators gaining close methods (which make no sense to me). Or are you using 'generator' in a different sense?

class closing(object): def init(self, resource): self.resource = resource

def enter(self): return self.resource def exit(self, *excinfo): self.resource.close()

with closing(mygenerator()) as g: # mygenerator() is assigned to g via call to enter() for item in g: print item # g is closed as the with statement ends

To me, this should be with closing(my_iterable())... with 'for' calling g.iter to get the iterator that is possibly a generator. Otherwise, I don't understand it.

The rest is pretty clear.

Terry J. Reedy



More information about the Python-Dev mailing list