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

Guido van Rossum guido at python.org
Thu Apr 20 14:41:59 CEST 2006


On 4/20/06, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Phillip J. Eby wrote:
> > At 11:41 PM 4/19/2006 +1000, Nick Coghlan wrote:
> >> Given that naming though, I think contextlib.contextmanager should be
> >> renamed to contextlib.context.
> >
> > The name is actually correct under this terminology arrangement.
> > @contextmanager *returns* a context manager.
>
> That's like saying we should describe the result of calling a generator
> function as a generator-iterable because it has an __iter__ method.
>
> The longer name made sense when "context manager" was the term for the object
> with __enter__ and __exit__ methods (the way I originally wrote it when
> updating the PEP after the addition of the __context__ method).
>
> While I agree that flipping the terminology the other way around makes sense,
> it *also* flips the effect of calling a decorated generator function so that
> what it returns is now appropriately termed a generator-context (since it
> provides __enter__ and __exit__ methods directly).
>
> These contexts are context managers only in the same sense that iterators are
> also iterables. We shouldn't break the parallels between iterable-iterator and
> context manager-context without a good reason - and so far I haven't heard one.

Sorry Nick, but you've still got it backwards. The name of the
decorator shouldn't indicate the type of the return value (of calling
the decorated generator) -- it should indicate how we think about the
function. Compare @staticmethod and @classmethod -- the return type
doesn't enter into it. I think of the function/generator itself as the
context manager; it returns a context.

(Yet another analogy: if generators had to be decorated explicitly,
we'd name it @generator, even though what it returns when called is
properly an iterator.)

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list