Phillip J. Eby wrote: > Of course, it's not *really* that simple, because __try__ doesn't exactly > correspond to 'try:', and it has to return something, but it sure is > simpler than the mental gymnastics I'd go through to convert > except/else/finally into "if" statements inside an __exit__. You don't need to make that translation, though. Instead, you can just reraise the passed in exception inside the __exit__() method: def __exit__(self, *exc_info): try: try: if exc_info: raise exc_info[0], exc_info[1], exc_info[2] except: pass else: pass finally: pass However, the __exit__() method does allow you to switch to using if statements if that makes more sense (or would be more efficient). For instance, these are possible __exit__ methods for a locking() statement template and a transaction() statement template: # locking's exit method def __exit__(self, *exc_info): self.lock.release() if exc_info: raise exc_info[0], exc_info[1], exc_info[2] # transaction's exit method def __exit__(self, *exc_info): if exc_info: self.db.rollback() raise exc_info[0], exc_info[1], exc_info[2] else: self.db.commit() I've posted draft 1.4 of my PEP 310/PEP 340 merger PEP (PEP 650, maybe?): http://members.iinet.net.au/~ncoghlan/public/pep-3XX.html This version cleans up the semantics a lot, so that the examples actually work as intended, and there is One Obvious Way to do things like suppressing exceptions (i.e. don't reraise them in the __exit__() method). It also specifically addresses the question of using two methods in the protocol versus four, and shows how an arbitrary try statement can be converted to a statement template. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.blogspot.com
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4