[Python-Dev] PEP 310 and exceptions

Aahz aahz at pythoncraft.com
Sat Apr 23 15:50:02 CEST 2005

On Sat, Apr 23, 2005, 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
>             else:
>                 raise
>         else:
>             if hasattr(x, '__else__'):
>                 x.__else__()
>     finally:
>         if hasattr(x, '__exit__'):
>             x.__exit__()

+1, but prior to reading this post I was thinking along similar lines
with your __exit__ named __finally__ and your __else__ named __exit__.
My reasoning for that is that most of the time, people want their exit
condition aborted if an exception is raised; having the "normal" exit
routine called __else__ would be confusing except to people who do lots
of exception handling.

(I'm a bit sensitive to that right now; this week I wasted an hour
because I didn't understand exceptions as well as I thought I did,
although it was related more to the precise mechanics of raising and
catching exceptions.  Perhaps I'll submit a doc bug; I didn't find this
explained in _Learning Python_ or Nutshell...)
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"It's 106 miles to Chicago.  We have a full tank of gas, a half-pack of
cigarettes, it's dark, and we're wearing sunglasses."  "Hit it."

More information about the Python-Dev mailing list