[Python-Dev] Why are contexts also managers? (was r45544 - peps/trunk/pep-0343.txt)

Nick Coghlan ncoghlan at gmail.com
Sat Apr 22 10:14:43 CEST 2006


Phillip J. Eby wrote:
> If you have a problem with what I did to the PEP, kindly take it up with 
> Guido.  If you have a problem with the documentation I took the time to 
> write and contribute, by all means change it.  At this point, I'm 
> getting pretty tired of people of accusing me of violating procedures 
> around here, and I'm past caring what you do or don't call the bloody 
> objects.  At least I've gotten contextlib and test_contextlib to 
> actually work, and arranged for there to be *some* documentation for the 
> "with" statement and the contextlib module.

I'm not trying to diminish the work you've done to make this happen - I *did* 
review those docs after you put them in, and completely missed the discrepancy 
between them and the wording in the PEP. So the current confusion is at least 
as much my fault as anyone else's :)

The one thing I wasn't sure of after AMK brought it up was whether or not 
there'd been an offline discussion at PyCon that had made the change on purpose.

> Meanwhile, the iterator-iterable analogy is false.  You have to be able 
> to iterate over an iterator, but as AMK pointed out, you don't have to 
> be able to pass a [thing having __enter__/__exit__] to a "with" 
> statement.  So I was wrong to apply that analogy myself, as are you now.

This is only true if we're happy for calling ctx.__context__() explicitly to 
produce something unusable.

i.e., just as these are equivalent:

   for x in iterable:
       pass

   itr = iter(iterable)
   for x in itr:
       pass

I believe these should be equivalent:

   with ctx as foo:
       pass

   ctx_mgr = ctx.__context__()
   with ctx_mgr as foo:
       pass

The only way for that to happen is if context managers all have a 
__context__() method that returns self.

> That having been said, I don't think either you or I or even Guido 
> should be the ones to fix the PEP and the docs at this point, as we've 
> all stared at the bloody thing way too long to see it with fresh eyes.  
> So far, AMK is the one who's finding all our screwups, so maybe he 
> should be the one to explain it all to *us*.  :)

Heh. I actually had to go trawling back through the python-dev archives to 
figure out whether or not I was going nuts :)

Alternatively, I could have a go at clearing it up for next week's alpha2, and 
we can ask Anthony to make an explicit request for review of those docs in the 
announcement. . .

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list