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

Guido van Rossum guido at python.org
Wed Apr 26 01:18:17 CEST 2006


On 4/25/06, Phillip J. Eby <pje at telecommunity.com> wrote:
> At 11:37 AM 4/25/2006 -0700, Guido van Rossum wrote:
> >But what's the use case? Have we actually got an example where it
> >makes sense to use the "thing with __enter__ and __exit__ methods" in
> >a with-statement, other than the (many) examples where the original
> >__context__ method returns "self"?
>
> Objects returned by @contextfactory-decorated functions must have __enter__
> and __exit__ (so @contextfactory can be used to define __context__ methods)
> *and* they must also have __context__, so they can be used directly in a
> "with" statement.

That doesn't make sense. *Except* for cases where __context__()
returns self, when would I ever use the object returned by
__context__() in a with statement? That would mean that I would have
to write code like this:

  A = B.__context__()                  # Here, A is not B
  with A:
      <whatever>

I don't see any reason to write such code!!!

The more I think about it the more I believe the parallel with
__iter__ is a fallacy. There are many ways to get an iterator in your
hands without calling X.__iter__(): not just iter(X), but also
X.iterkeys(), enumerate(X), and so on. It makes total sense (in fact
it is sometimes the only use case) to pass those things to a for loop
for iteration, which implies calling iter() on them, which implies
calling __iter__() method.

But (again, *excluding* objects whose __context__ returns self!) I
don't see any use cases for calling __context__() explicitly -- that
is *always* done by a with-statement.

So, again, I'm asking for a real use case, similar to the one provided
by enumerate() or iterkeys().

> I think that in all cases where you want this (enter/exit implies context
> method availability), it's going to be the case that you want the context
> method to return self, just as iterating an object with a next() method
> normally returns that object.

Yeah, of course, just like for iterators. But the question remains,
under what circumstances is it convenient to call __context__()
explicit, and pass the result to a with-statement?

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


More information about the Python-Dev mailing list