[Python-Dev] Merging PEP 310 and PEP 340-redux?

Nick Coghlan ncoghlan at gmail.com
Wed May 11 12:41:16 CEST 2005


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


More information about the Python-Dev mailing list