At 05:15 PM 10/3/2005 -0400, Jason Orendorff wrote: >Phillip J. Eby writes: > > You didn't offer any reasons why this would be useful and/or good. > >It makes it dramatically easier to write Python classes that correctly >support 'with'. I don't see any simple way to do this under PEP 343; >the only sane thing to do is write a separate @contextmanager >generator, as all of the examples do.
Wha? For locks (the example you originally gave), this is trivial. >Consider: > > # decimal.py > class Context: > ... > def __enter__(self): > ??? > def __exit__(self, t, v, tb): > ??? > > DefaultContext = Context(...) > >Kindly implement __enter__() and __exit__(). Make sure your >implementation is thread-safe (not easy, even though >decimal.getcontext/.setcontext are thread-safe!). Also make sure it >supports nested 'with DefaultContext:' blocks (I don't mean lexically >nested, of course; I mean nested at runtime.) > >The answer requires thread-local storage and a separate stack of saved >context objects per thread. It seems a little ridiculous to me. Okay, it was completely non-obvious from your post that this was the problem you're trying to solve. >Whereas: > > class Context: > ... > def __with__(self): > old = decimal.getcontext() > decimal.setcontext(self) > try: > yield > finally: > decimal.setcontext(old) This could also be done with a Context.replace() @contextmanager method. On the whole, I'm torn. I definitely like the additional flexibility this gives. On the other hand, it seems to me that __with__ and the additional C baggage violates the "if the implementation is hard to explain" rule. Also, people have already put a lot of effort into implementation and documentation patches based on an accepted PEP. That's not enough to override "the right thing to do", especially if it comes with a volunteer willing to update the work, but in this case the amount of additional goodness seems small, and it's not immediately apparent that you're volunteering to help change this even if Guido blessed it. _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com