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

Guido van Rossum guido at python.org
Wed Apr 26 05:09:34 CEST 2006


On 4/25/06, Phillip J. Eby <pje at telecommunity.com> wrote:
> At 05:20 PM 4/25/2006 -0700, Guido van Rossum wrote:
> >I would augment #1 to clarify that if you have __enter__ and __exit__
> >you may not have __context__ at all; if you have all three,
> >__context__ must return self.
>
> Well, requiring the __context__ allows us to ditch the otherwise complex
> problem of why @contextfactory functions' return value is usable by "with",
> without having to explain it separately.

Really? I thought that that was due to the magic in the decorator (and
in the class it uses). In this case the use of magic is fine by me; I
know I could reconstruct it from scratch if I had to (with only one or
two bugs :-) but it's convenient to have it in the library. The
primary use case is this:

  @contextfactory
  def foo(): ...

  with foo():
      ...

but a secondary one is this:

  class C:
      ...
      @contextfactory
      def __context__(self):
          ...

  with C():
      ....

Because of these two different uses it makes sense for @contextfactory
to return an object that has both __context__ and __enter__/__exit__
methods.

But that *still* doesn't explain why we are recommending that
everything providing __enter__/__exit__ must also provide __context__!
I still think we should take it out.

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


More information about the Python-Dev mailing list