[Python-Dev] Must objects with enter/exit also supply context? (original) (raw)
Guido van Rossum guido at python.org
Wed Apr 26 01🔞17 CEST 2006
- Previous message: [Python-Dev] Must objects with __enter__/__exit__ also supply __context__?
- Next message: [Python-Dev] Must objects with __enter__/__exit__ also supply __context__?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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:
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/)
- Previous message: [Python-Dev] Must objects with __enter__/__exit__ also supply __context__?
- Next message: [Python-Dev] Must objects with __enter__/__exit__ also supply __context__?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]