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

Phillip J. Eby pje at telecommunity.com
Mon Apr 24 23:27:45 CEST 2006


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.
>
>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...

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.  :)

By the way, I'm now on board with the idea that @contextmanager should be 
renamed, preferably to @contextfactory.  (The objection someone made about 
"factory" implying a factory function is off-base; @contextfactory indeed 
*returns* a factory function that returns a context, so actually the name 
is perfect, and works for both wrapping __context__ methods and standalone 
generators.)



More information about the Python-Dev mailing list