[Python-Dev] Must objects with enter/exit also supply context? (original) (raw)

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