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

Paul Moore p.f.moore at gmail.com
Wed Apr 26 10:56:10 CEST 2006


On 4/26/06, Guido van Rossum <guido at python.org> wrote:
> 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.

You've just hit the problem that sucked me into all this....

You either need two decorator names for the 2 different uses of
contextfactory, or you need to require everything providing
__enter__/__exit__ to also provide __context__, or you need to accept
that @contextfactory has a bit of implementation-level magic, that
people shouldn't really care about.

Changing the name to contextfactory made me happy with the
"implementation magic" approach, but Nick still felt the need for the
stronger method requirement (IIRC, he cited the parallel with
iterators, but I don't want to misrepresent his position, so I'll
leave him to speak for himself). Phillip and I conceded this, as (in
my case) it didn't feel like a big thing, and we were close to a
workable compromise.

Beyond this bit of history, I don't really have a strong opinion either way.

Paul.


More information about the Python-Dev mailing list