[Python-Dev] Must objects with __enter__/__exit__ also supply __context__?

Nick Coghlan ncoghlan at gmail.com
Tue Apr 25 05:38:24 CEST 2006


Phillip J. Eby wrote:
> At 09:35 PM 4/24/2006 +0100, Paul Moore wrote:
>> The current, alpha 2, documentation insists that objects with
>> __enter__ and __exit__ methods must also define __context__ in such a
>> way that it returns self.
>>
>> I don't understand why that is necessary.

It's not necessary at all. It's a deliberate design decision in the PEP, 
deliberately copying the semantics of the iterator protocol.

>> I can understand that it is convenient, in cases where __context__
>> doesn't need to create a new object each time, but is it *necessary*?
>>
>> Specifically, is there a use case where you need to say "with x" where
>> x is the return value of a __context__ method, or where you call
>> __context__ on something you got from __context__? I can't find one in
>> the PEP or in the code for contextlib...

There aren't any current use cases that require it, no. But how much harder 
would it have been to develop itertools if the "all iterators are iterables" 
identity hadn't been part of the original design?

Requiring that all context managers also be context specifiers is harmless. 
Not requiring it breaks the parallel with iterators and iterables, which means 
that parallel can't be leveraged to explain how things work anymore.

> The only benefit to this is that it allows us to have only one 
> decorator.  If the decorator is defined as returning a thing with 
> __enter__ and __exit__, and such things must also have a __context__, 
> then there is no need for a separate decorator that's defined as 
> returning things that have __context__, nor to tweak the docs to explain 
> that the single decorator does both, nor to have two names for the same 
> decorator.
> 
> So, it's sort of a documentation hack.  :)

It's a deliberate design decision to parallel the existing model provided by 
iterators and iterables.

Otherwise, you have to have three concepts:

   context specifiers (have __context__ method)
   context managers (have __enter__/__exit__ methods)
   combined specifier/managers (which have all three)

There was no need for iterators to be iterables, either - that was a 
deliberate design decision taken at the time iterators were introduced. I 
merely copied that pre-existing approach for PEP 343.

Cheers,
Nick.

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


More information about the Python-Dev mailing list