On Sat, Apr 23, 2005 at 13:41 +1000, Nick Coghlan wrote: > Nick Coghlan wrote: > In light of Alex's comments, I'd actually like to suggest the below as a > potential new definition for PEP 310 (making __exit__ optional, and adding > an __else__ handler): > > if hasattr(x, '__enter__'): > x.__enter__() > try: > try: > # Contents of 'with' block > except: > if hasattr(x, '__except__'): > if not x.__except__(*sys.exc_info()): # [1] > raise
On a side note, I don't see too much point in having __except__ return something when it is otherwise easy to say: def __except__(self, typ, val, tb): self.abort_transaction() raise typ, val, tb But actually i'd like to to mention some other than transaction-use cases for __except__, for example with class MyObject: def __except__(self, typ, val, tb): if isinstance(val, KeyboardInterrupt): raise # process exception and swallow it you can use it like: x = MyObject(): # do some long running stuff and MyObject() can handle internal problems appropriately and present clean Exceptions to the outside without changing the "calling side". With my implementation i also played with little things like: def __getattr__(self, name): Key2AttributeError: return self._cache[key] ... with an obvious __except__() implementation for Key2AttributeError. Similar to what Alex points out i generally think that being able to define API/object specific exception handling in *one* place is a great thing. I am willing to help with the PEP and implementation, btw. cheers, holger _______________________________________________ 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