Go Back   Rhinocerus > Newsgroup > Newsgroup comp.lang.python

Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old 04-11-2009, 12:19 AM
Terry Reedy
Guest
 
Posts: n/a
Default Re: weird try/finally behaviour

Sylvain Thénault wrote:
> Hi there,
>
> I've encountered the following behaviour which I found surprising:
>
>>>> def test():

> ... for x in ('test', 'tests'):
> ... try:
> ... if True:
> ... print 'return'
> ... return 1
> ... finally:
> ... print 'break'
> ... break
> ... print 'end'
> ...
>>>> test()

> return
> break
> end
>


If you say 'print test()', you shoud see None printed after 'end' (at
least with 3.0) from the function falling off the end.

The 'if True:' line make no difference.

> As you can see, the 'break' in the finally block makes the 'return 1' beeing ignored.
> Is this a known caveat or should it be considered as a bug?


Neither, but it s a bit subtle. If you replace 'break' with 'return 2',
what would you expect? What does happen is that 2, not 1, is returned.
Similarly, the break sends control to "print 'end'" and thence to the
implicit 'return None'.

The try doc on finally says "If the finally clause raises another
exception or executes a return or break statement, the saved exception
is lost." The same is true for saved returns, for the same reason: the
implicit END-FINALLY (an actual byte code) that completes the pending
return/exception is never reached.

When bugs.python.org works again, I will try to remember to suggest a
doc improvement.

Terry Jan Reedy

Reply With Quote
Alt Today
Advertising
 
and become member of Rhinocerus
Standard Sponsored Links

  #2 (permalink)  
Old 04-11-2009, 07:34 AM
Aaron Brady
Guest
 
Posts: n/a
Default Re: weird try/finally behaviour

On Apr 10, 7:19*pm, Terry Reedy <tjre...@udel.edu> wrote:
> Sylvain Thénault wrote:
> > Hi there,

>
> > I've encountered the following behaviour which I found surprising:

-
> If you say 'print test()', you shoud see None printed after 'end' (at
> least with 3.0) from the function falling off the end.
>
> The 'if True:' line make no difference.
>
> > As you can see, the 'break' in the finally block makes the 'return 1' beeing ignored.
> > Is this a known caveat or should it be considered as a bug?

>
> Neither, but it s a bit subtle. *If you replace 'break' with 'return 2'


Ha! Brilliant.
Reply With Quote
 
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off




All times are GMT. The time now is 11:36 AM.


Copyright ©2009

LinkBacks Enabled by vBSEO 3.3.0 RC2 © 2009, Crawlability, Inc.