[issue45890] Add tests for tracing try-except-finally blocks

2021-12-07 Thread Irit Katriel


Change by Irit Katriel :


--
resolution:  -> fixed
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue45890] Add tests for tracing try-except-finally blocks

2021-12-07 Thread Mark Shannon


New submission from Mark Shannon :


New changeset a310fd83a014484b8c680de83540c4908b344c6c by Irit Katriel in 
branch 'main':
bpo-45890: Add tests for tracing try-except-finally blocks (GH-29746)
https://github.com/python/cpython/commit/a310fd83a014484b8c680de83540c4908b344c6c


--
nosy: +Mark.Shannon

___
Python tracker 
<https://bugs.python.org/issue45890>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue45890] Add tests for tracing try-except-finally blocks

2021-11-24 Thread Irit Katriel


Change by Irit Katriel :


--
keywords: +patch
pull_requests: +27983
stage:  -> patch review
pull_request: https://github.com/python/cpython/pull/29746

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue45890] Add tests for tracing try-except-finally blocks

2021-11-24 Thread Irit Katriel


Change by Irit Katriel :


--
assignee: iritkatriel
components: Interpreter Core, Tests
nosy: iritkatriel
priority: normal
severity: normal
status: open
title: Add tests for tracing try-except-finally blocks
type: enhancement
versions: Python 3.11

___
Python tracker 
<https://bugs.python.org/issue45890>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue43458] Tutorial should mention about variable scope in try/except/finally

2021-03-12 Thread Éric Araujo

Éric Araujo  added the comment:

The only blocks that create scopes are modules, class and functions.
if, try, with, for, while, etc are blocks but not new scopes.

For the tutorial it could be nice to have an explicit mention and example of 
this.

--
nosy: +eric.araujo

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue43458] Tutorial should mention about variable scope in try/except/finally

2021-03-09 Thread Marek M


New submission from Marek M :

It can be helpful to mention that variables defined in try block are visible in 
except/finally block as well. I did not find this info in Python tutorial and 
for me (having C++ background) this is quite unexpected feature.

--
assignee: docs@python
components: Documentation
messages: 388407
nosy: deekox, docs@python
priority: normal
severity: normal
status: open
title: Tutorial should mention about variable scope in try/except/finally
type: enhancement
versions: Python 3.9

___
Python tracker 
<https://bugs.python.org/issue43458>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2021-02-01 Thread Mark Shannon


Mark Shannon  added the comment:

Sorry. I forgot the close the issue when it was fixed.

--
resolution:  -> fixed
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2021-02-01 Thread Ned Batchelder


Ned Batchelder  added the comment:

This problem no longer appears with master (commit 9eb11a139f).

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2021-02-01 Thread Pablo Galindo Salgado


Pablo Galindo Salgado  added the comment:

Friendly reminder that this issue is currently blocking the 3.10a5 release. If 
you are ok with waiting for the next release to include the fix, please say so 
here or drop me an email/

--
nosy: +pablogsal

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-21 Thread Mark Shannon


Mark Shannon  added the comment:


New changeset f2dbfd7e20431f0bcf2b655aa876afec7fe03c6f by Mark Shannon in 
branch 'master':
bpo-42634: Mark reraise after except blocks as artificial. (GH-23877)
https://github.com/python/cpython/commit/f2dbfd7e20431f0bcf2b655aa876afec7fe03c6f


--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-21 Thread Mark Shannon


Change by Mark Shannon :


--
pull_requests: +22740
stage: resolved -> patch review
pull_request: https://github.com/python/cpython/pull/23877

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-21 Thread Mark Shannon


Change by Mark Shannon :


--
resolution: fixed -> 

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-20 Thread Ned Batchelder


Ned Batchelder  added the comment:

(Rather: line 8 isn't executed, and so should not be traced.)

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-20 Thread Ned Batchelder


Ned Batchelder  added the comment:

I checked on this with CPython commit c95f8bc270.  The code above is fixed, but 
this code has a similar problem:

a, b, c = 1, 1, 1
try:
try:
a = 4/0 # ZeroDivisionError
except ValueError:
b = 6
except IndexError:
a = 8   # Line 8
finally:
c = 10
except ZeroDivisionError:
pass
assert a == 1 and b == 1 and c == 10


Using a simple trace program 
(https://github.com/nedbat/coveragepy/blob/master/lab/run_trace.py), it 
produces this output:

call  1 @-1
line  1 @0
line  2 @10
line  3 @12
line  4 @16
exception  4 @20
line  5 @28
line  7 @48
line  8 @68
line  10 @78
line  11 @88
line  12 @100
line  13 @106
return  13 @136

Line 8 should never be executed.

--
status: closed -> open

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-14 Thread Mark Shannon


Change by Mark Shannon :


--
resolution:  -> fixed
stage: patch review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-14 Thread Mark Shannon


Change by Mark Shannon :


--
keywords: +patch
pull_requests: +22616
stage: needs patch -> patch review
pull_request: https://github.com/python/cpython/pull/23760

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue42634] Incorrect line number in bytecode for try-except-finally

2020-12-13 Thread Mark Shannon


New submission from Mark Shannon :

The following code, when traced, produces a spurious line event for line 5:

a, b, c = 1, 1, 1
try:
a = 3
except:
b = 5
finally:
c = 7
assert a == 3 and b == 1 and c == 7

Bug reported by Ned Batchelder 
https://gist.github.com/nedbat/6c5dedde9df8d2de13de8a6a39a5f112

--
assignee: Mark.Shannon
messages: 382958
nosy: Mark.Shannon, nedbat
priority: release blocker
severity: normal
stage: needs patch
status: open
title: Incorrect line number in bytecode for try-except-finally
type: behavior
versions: Python 3.10

___
Python tracker 
<https://bugs.python.org/issue42634>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: try/except/finally

2014-06-11 Thread alister
On Wed, 11 Jun 2014 00:00:49 +, Steven D'Aprano wrote:

 On Wed, 11 Jun 2014 06:37:01 +1000, Chris Angelico wrote:
 
 I don't know a single piece of programming advice which, if taken as an
 inviolate rule, doesn't at some point cause suboptimal code.
 
 Don't try to program while your cat is sleeping on the keyboard.

My cat is a better programmer than I am !



-- 
Hors d'oeuvres -- a ham sandwich cut into forty pieces.
-- Jack Benny
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-11 Thread Roy Smith
In article NxUlv.352165$uI3.258913@fx18.am4,
 alister alister.nospam.w...@ntlworld.com wrote:

 On Wed, 11 Jun 2014 00:00:49 +, Steven D'Aprano wrote:
 
  On Wed, 11 Jun 2014 06:37:01 +1000, Chris Angelico wrote:
  
  I don't know a single piece of programming advice which, if taken as an
  inviolate rule, doesn't at some point cause suboptimal code.
  
  Don't try to program while your cat is sleeping on the keyboard.
 
 My cat is a better programmer than I am !

My girlfriend's cat is smarter than me!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Thomas Rachel

Am 08.06.2014 05:58 schrieb Rustom Mody:


Some people¹ think that gotos are a code-smell.
 ¹ I am not exactly those people.
A chap called E W Dijkstra made the statement: Goto statement considered
harmful and became famous.


And became widely misunderstood. If anybody would read the whole what he 
wrote, people would learn that he doesn't criticise the *use* of goto, 
but he wants the *replacement* of goto with something else (like 
exceptions).


As C doesn't have exceptions, goto is in many cases the simplest and 
easiest way of handling errors.


Essentially, you can write both good and bad code both with and without 
goto.



Thomaas
--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Marko Rauhamaa
Thomas Rachel 
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa...@spamschutz.glglgl.de:

 Essentially, you can write both good and bad code both with and
 without goto.

Point is, choose tasteful idioms in your code.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Rustom Mody
On Tuesday, June 10, 2014 12:57:29 PM UTC+5:30, Thomas Rachel wrote:
 Am 08.06.2014 05:58 schrieb Rustom Mody:

  Some people� think that gotos are a code-smell.
   � I am not exactly those people.
  A chap called E W Dijkstra made the statement: Goto statement considered
  harmful and became famous.

 And became widely misunderstood. If anybody would read the whole what he 
 wrote, people would learn that he doesn't criticise the *use* of goto, 
 but he wants the *replacement* of goto with something else (like 
 exceptions).

 As C doesn't have exceptions, goto is in many cases the simplest and 
 easiest way of handling errors.

 Essentially, you can write both good and bad code both with and without 
 goto.

Here is Dijkstra:
http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html

First statement:
| For a number of years I have been familiar with the observation that
| the quality of programmers is a decreasing function of the density of
| go to statements in the programs they produce.

And here is Hoare, not identical to Dijkstra but with similar areas of 
interest and similar views on correctness etc, very unambiguously
criticising exceptions:

| Ada has a plethora of features and notational conventions, many of them
| unnecessary and some of them, like exception handling, even
| dangerous.  Do not allow this language in its present state to be
| used in applications where reliability is critical

http://en.wikipedia.org/wiki/Exception_handling#Criticism
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Skip Montanaro
 Here is Dijkstra:
 http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html
...
 And here is Hoare...

 | Ada has a plethora of features and notational conventions, many of them
 | unnecessary and some of them, like exception handling, even
 | dangerous.  Do not allow this language in its present state to be
 | used in applications where reliability is critical.

Would be interesting to get their collective take on C++...

Are there any good parts? It appears the book was cancelled (note the
remarks):

https://www.matthewsbooks.com/productdetail.aspx?productid=4493SAT1969returnurl=%2Fforthcomingtitles.aspx%3Fsort%3D0%26images%3D1%26print%3Dtrue

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Mark Lawrence

On 10/06/2014 08:27, Thomas Rachel wrote:

Am 08.06.2014 05:58 schrieb Rustom Mody:


Some people¹ think that gotos are a code-smell.
 ¹ I am not exactly those people.
A chap called E W Dijkstra made the statement: Goto statement considered
harmful and became famous.


And became widely misunderstood. If anybody would read the whole what he
wrote, people would learn that he doesn't criticise the *use* of goto,
but he wants the *replacement* of goto with something else (like
exceptions).

As C doesn't have exceptions, goto is in many cases the simplest and
easiest way of handling errors.

Essentially, you can write both good and bad code both with and without
goto.

Thomaas


I entirely agree.  I find it incredible that some people find it so 
difficult to differentiate having tens or even hundreds of gotos leaping 
around willy nilly to a similar number of labels, and a similar number 
of gotos targetted at one label called SNAFU or whatever.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Grant Edwards
On 2014-06-10, Mark Lawrence breamore...@yahoo.co.uk wrote:

 I entirely agree.  I find it incredible that some people find it so 
 difficult to differentiate having tens or even hundreds of gotos
 leaping around willy nilly to a similar number of labels, and a
 similar number of gotos targetted at one label called SNAFU or
 whatever.

I've seen some amazingly convoluted C code where people got themselves
wrapped around the axle six different ways in order to avoid using
goto fail or goto retry.  Invariably I was looking at the code
because it didn't work right and needed to be fixed.  Usually the
addition of a 'fail' label and a few gotos allowed me to throw out all
sorts of complexly nested if/else blocks, status flags, and
unnecessary while loops.  Usually you can reduce the number of lines
of code (sometimes by half or more) while also reducing the number and
nesting of control structures.  And when you're done it works right!

-- 
Grant Edwards   grant.b.edwardsYow! LOOK!!  Sullen
  at   American teens wearing
  gmail.comMADRAS shorts and Flock of
   Seagulls HAIRCUTS!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread alister
On Tue, 10 Jun 2014 19:14:18 +0100, Mark Lawrence wrote:

 On 10/06/2014 08:27, Thomas Rachel wrote:
 Am 08.06.2014 05:58 schrieb Rustom Mody:

 Some people¹ think that gotos are a code-smell.
  ¹ I am not exactly those people.
 A chap called E W Dijkstra made the statement: Goto statement
 considered harmful and became famous.

 And became widely misunderstood. If anybody would read the whole what
 he wrote, people would learn that he doesn't criticise the *use* of
 goto, but he wants the *replacement* of goto with something else (like
 exceptions).

 As C doesn't have exceptions, goto is in many cases the simplest and
 easiest way of handling errors.

 Essentially, you can write both good and bad code both with and without
 goto.

 Thomaas
 
 I entirely agree.  I find it incredible that some people find it so
 difficult to differentiate having tens or even hundreds of gotos leaping
 around willy nilly to a similar number of labels, and a similar number
 of gotos targetted at one label called SNAFU or whatever.



once the compiler gets hold of it all the CPU has to work with are goto 
variants, jump if equal etc.(I don't know the actual x86 assembler but it 
is the same on all processors)
-- 
(It is an old Debian tradition to leave at least twice a year ...)
-- Sven Rudolph
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Chris Angelico
On Wed, Jun 11, 2014 at 4:48 AM, Grant Edwards invalid@invalid.invalid wrote:
 I've seen some amazingly convoluted C code where people got themselves
 wrapped around the axle six different ways in order to avoid using
 goto fail or goto retry.  Invariably I was looking at the code
 because it didn't work right and needed to be fixed.  Usually the
 addition of a 'fail' label and a few gotos allowed me to throw out all
 sorts of complexly nested if/else blocks, status flags, and
 unnecessary while loops.  Usually you can reduce the number of lines
 of code (sometimes by half or more) while also reducing the number and
 nesting of control structures.  And when you're done it works right!

Yeah. As soon as you take on board a hard-and-fast rule, you open
yourself up to stupid cases where the rule ought to have been broken.
I don't know a single piece of programming advice which, if taken as
an inviolate rule, doesn't at some point cause suboptimal code.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Roy Smith
In article mailman.10972.1402432630.18130.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 Yeah. As soon as you take on board a hard-and-fast rule, you open
 yourself up to stupid cases where the rule ought to have been broken.
 I don't know a single piece of programming advice which, if taken as
 an inviolate rule, doesn't at some point cause suboptimal code.

How about, Don't use PHP?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Chris Angelico
On Wed, Jun 11, 2014 at 6:38 AM, Roy Smith r...@panix.com wrote:
 In article mailman.10972.1402432630.18130.python-l...@python.org,
  Chris Angelico ros...@gmail.com wrote:

 Yeah. As soon as you take on board a hard-and-fast rule, you open
 yourself up to stupid cases where the rule ought to have been broken.
 I don't know a single piece of programming advice which, if taken as
 an inviolate rule, doesn't at some point cause suboptimal code.

 How about, Don't use PHP?

Actually, that one might fit now. In years past, that advice would
often lead you to write very expensive code, because it couldn't be
run on a cheap web host - if you write something in Python, you have
to pay through the nose, but any piece-of-rubbish host will give you
PHP. That may now be changing, though.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Ethan Furman

On 06/10/2014 01:38 PM, Roy Smith wrote:

 Chris Angelico wrote:
#

Yeah. As soon as you take on board a hard-and-fast rule, you open
yourself up to stupid cases where the rule ought to have been broken.
I don't know a single piece of programming advice which, if taken as
an inviolate rule, doesn't at some point cause suboptimal code.


How about, Don't use PHP?


Sounds like the exception that proves the rule!  ;)

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Mark Lawrence

On 10/06/2014 21:43, Ethan Furman wrote:

On 06/10/2014 01:38 PM, Roy Smith wrote:

 Chris Angelico wrote:
#

Yeah. As soon as you take on board a hard-and-fast rule, you open
yourself up to stupid cases where the rule ought to have been broken.
I don't know a single piece of programming advice which, if taken as
an inviolate rule, doesn't at some point cause suboptimal code.


How about, Don't use PHP?


Sounds like the exception that proves the rule!  ;)

--
~Ethan~


After that one please consider yourself fortunate that the UK, amongst 
other countries, no longer has the death penalty.  I guess that The 
Comfy Chair will have to suffice :)


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Steven D'Aprano
On Wed, 11 Jun 2014 06:37:01 +1000, Chris Angelico wrote:

 I don't know
 a single piece of programming advice which, if taken as an inviolate
 rule, doesn't at some point cause suboptimal code.

Don't try to program while your cat is sleeping on the keyboard.



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Chris Angelico
On Wed, Jun 11, 2014 at 10:00 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Wed, 11 Jun 2014 06:37:01 +1000, Chris Angelico wrote:

 I don't know
 a single piece of programming advice which, if taken as an inviolate
 rule, doesn't at some point cause suboptimal code.

 Don't try to program while your cat is sleeping on the keyboard.

Hmm. I've never actually heard that one. Is it commonly taught in
programming classes? Because I haven't taken any.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Roy Smith
 On Wed, Jun 11, 2014 at 10:00 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
  Don't try to program while your cat is sleeping on the keyboard.

In article mailman.10989.1402445543.18130.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:
 Hmm. I've never actually heard that one. Is it commonly taught in
 programming classes? Because I haven't taken any.

A picture of a cat sleeping on your keyboard...

$ ps l
F   UID   PID  PPID PRI  NIVSZ   RSS WCHAN  STAT TTYTIME COMMAND
0  1010  4768  4660  20   0   5904   352 n_tty_ S+   pts/1  0:00 cat
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Tim Delaney
On 11 June 2014 10:00, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info
 wrote:

 On Wed, 11 Jun 2014 06:37:01 +1000, Chris Angelico wrote:

  I don't know
  a single piece of programming advice which, if taken as an inviolate
  rule, doesn't at some point cause suboptimal code.

 Don't try to program while your cat is sleeping on the keyboard.


Lying down, the weight is spread across the whole keyboard so you're
unlikely to suffer extra keypresses due to the cat. So if you're a
touch-typist that one may not be too bad (depending on how easily their fur
gets up your nose).

Now, a cat *standing* on the keyboard, between you and the monitor, and
rubbing his head against your hands, is a whole other matter.

Tim Delaney
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Mark Lawrence

On 11/06/2014 01:40, Tim Delaney wrote:

On 11 June 2014 10:00, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info
mailto:steve+comp.lang.pyt...@pearwood.info wrote:

On Wed, 11 Jun 2014 06:37:01 +1000, Chris Angelico wrote:

  I don't know
  a single piece of programming advice which, if taken as an inviolate
  rule, doesn't at some point cause suboptimal code.

Don't try to program while your cat is sleeping on the keyboard.


Lying down, the weight is spread across the whole keyboard so you're
unlikely to suffer extra keypresses due to the cat. So if you're a
touch-typist that one may not be too bad (depending on how easily their
fur gets up your nose).

Now, a cat *standing* on the keyboard, between you and the monitor, and
rubbing his head against your hands, is a whole other matter.

Tim Delaney




Does it make any difference if the cat is European or African?

--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Chris Angelico
On Wed, Jun 11, 2014 at 10:53 AM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 Does it make any difference if the cat is European or African?

What? I don't know. ARGH!

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Mark Lawrence

On 11/06/2014 02:00, Chris Angelico wrote:

On Wed, Jun 11, 2014 at 10:53 AM, Mark Lawrence breamore...@yahoo.co.uk wrote:

Does it make any difference if the cat is European or African?


What? I don't know. ARGH!

ChrisA



Awfully sorry, it's 2 a.m. here, next time I'll try to remember to 
mention cats from other continents like America, Asia and Antartica. 
Did I get all of them? :)


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-10 Thread Rustom Mody
On Tuesday, June 10, 2014 11:41:45 PM UTC+5:30, Skip Montanaro wrote:
 Would be interesting to get their collective take on C++...

 Are there any good parts? It appears the book was cancelled

 https://www.matthewsbooks.com/productdetail.aspx?productid=4493SAT1969returnurl=%2Fforthcomingtitles.aspx%3Fsort%3D0%26images%3D1%26print%3Dtrue

 (note the remarks):

And — if ‘i’≡‘y’ — the author.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-09 Thread Philip Shaw
On 2014-06-08, Dave Angel da...@davea.name wrote:
 Frank B fbick...@gmail.com Wrote in message:
 Ok; this is a bit esoteric.
 
 So finally is executed regardless of whether an exception occurs, so states 
 the docs.
 
 But, I thought, if I return from my function first, that should take 
 precedence.
 
 au contraire
 
 Turns out that if you do this:
 
 try:
   failingthing()
 except FailException:
   return 0
 finally:
   return 1
 
 Then finally really is executed regardless... even though you told it to 
 return.
 
 That seems odd to me.
 

 The thing that's odd to me is that a return is permissible inside
  a finally block. That return
 should be at top level,  even with the finally line. And of course
  something else should be in the body of the finally
  block.

It does have some legitimate uses, for example:

try:
failingThing()
finally:
simple_cleanup()
if(that_worked())
return
complicated
cleanup
with
lots
of
blocks

OTOH, it could just be that Guido didn't think of banning it when
exceptions were first added and doesn't want to introduce an
incompatability later.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-09 Thread Marko Rauhamaa
Philip Shaw jnufcvy...@tznvy.pbz:

 OTOH, it could just be that Guido didn't think of banning [return from
 finally] when exceptions were first added and doesn't want to
 introduce an incompatability later.

You don't have to ban all nonsensical things. Most guns allow you to
shoot yourself in the foot, even those with static type checking.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-09 Thread Shiyao Ma
It would be great if someone could discuss it from the viewpoint of
bytecode. e.g., how the stack is popped, etc.


2014-06-09 17:40 GMT+08:00 Marko Rauhamaa ma...@pacujo.net:

 Philip Shaw jnufcvy...@tznvy.pbz:

  OTOH, it could just be that Guido didn't think of banning [return from
  finally] when exceptions were first added and doesn't want to
  introduce an incompatability later.

 You don't have to ban all nonsensical things. Most guns allow you to
 shoot yourself in the foot, even those with static type checking.


 Marko
 --
 https://mail.python.org/mailman/listinfo/python-list




-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-09 Thread Skip Montanaro
On Mon, Jun 9, 2014 at 11:23 AM, Shiyao Ma i...@introo.me wrote:

 It would be great if someone could discuss it from the viewpoint of bytecode. 
 e.g., how the stack is popped, etc.

BITD, you couldn't have try/except/finally. You could have try/except
or try/finally. You could nest the two, which is what people used to
do (back when we had to walk uphill both ways to school in a
snowstorm). As I recall, it wasn't implemented from the start because
the benefit of having try/except/finally didn't outweigh the
difficulty of implementation. Someone finally buckled down and
implemented it. To understand it, I think you might have to read the
source and PEP 341.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-08 Thread Marko Rauhamaa
Mark Lawrence breamore...@yahoo.co.uk:

 A return statement inside a finally block is code smell.
 Not to my nose.  It seems like a perfectly reasonable thing to do.
 I agree, the code smell is the return in the except block.

Here's a regular pattern that I use for nonblocking I/O:

def poll(self):
try:
message = self.sock.recv(0x1)
except IOError as e:
if e.errno == errno.EAGAIN:
return
if errcode == errno.EINTR:
self.trigger()
return
self.handle_io_error(e.errno)
return
self.trigger()
self.handle_recv(message)

Does anyone have an example motivating a return from finally? It seems
to me it would always be a bad idea as it silently clears all unexpected
exceptions.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-08 Thread Joshua Landau
On 8 June 2014 08:12, Marko Rauhamaa ma...@pacujo.net wrote:

 Does anyone have an example motivating a return from finally? It seems
 to me it would always be a bad idea as it silently clears all unexpected
 exceptions.

In a general sense:

try:
something_that_can_break()
return foo() # before clean_up
finally:
clean_up()
if default:
return default() # after clean_up()

What's the best replacement? Note: I've never done this.

---

I do sometimes use

try:
return x
finally:
x += 1

over

ret = x
x += 1
return ret

now-a-days.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-08 Thread Joshua Landau
On 6 June 2014 18:39, Roy Smith r...@panix.com wrote:

 The only way I can think of to bypass a finally block would be to call
 os._exit(), or send yourself a kill signal.

If you're willing to use implementation details...

---

# BreakN.py

import sys

# Turn tracing on if it is off
if sys.gettrace() is None: sys.settrace(lambda frame, event, arg: None)

def break_n(n):
frame = sys._getframe().f_back

for _ in range(n):
frame.f_trace = skip_function_tracer
frame = frame.f_back

def skip_function_tracer(frame, event, arg):
try:
# Skip this line
while True:
frame.f_lineno += 1

except ValueError as e:
# Finished tracing function; remove trace
pass

---

# Thing_you_run.py

from BreakN import break_n

def foo():
try:
print(I am not skipped)
break_n(1)
print(I am skipped)
...
finally:
print(I am skipped)
...

foo()
# I am not skipped
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-08 Thread Ian Kelly
On Sun, Jun 8, 2014 at 12:02 PM, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Sun, Jun 8, 2014 at 11:57 AM, Joshua Landau jos...@landau.ws wrote:
 On 8 June 2014 08:12, Marko Rauhamaa ma...@pacujo.net wrote:

 Does anyone have an example motivating a return from finally? It seems
 to me it would always be a bad idea as it silently clears all unexpected
 exceptions.

 In a general sense:

 try:
 something_that_can_break()
 return foo() # before clean_up
 finally:
 clean_up()
 if default:
 return default() # after clean_up()

 What's the best replacement? Note: I've never done this.

 Why not just move the default out of the finally block?

 try:
 something_that_can_break()
 return foo() # before clean_up
 finally:
 clean_up()
 if default:
 return default() # after clean_up()

Never mind, that doesn't work.  But you could do this:

try:
something_that_can_break()
return foo() # before clean_up
except ExpectedException:
if default:
return default() # after clean_up()
else:
raise
finally:
clean_up()

And then anything unexpected will be propagated instead of silenced.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-08 Thread Ian Kelly
On Sun, Jun 8, 2014 at 11:57 AM, Joshua Landau jos...@landau.ws wrote:
 On 8 June 2014 08:12, Marko Rauhamaa ma...@pacujo.net wrote:

 Does anyone have an example motivating a return from finally? It seems
 to me it would always be a bad idea as it silently clears all unexpected
 exceptions.

 In a general sense:

 try:
 something_that_can_break()
 return foo() # before clean_up
 finally:
 clean_up()
 if default:
 return default() # after clean_up()

 What's the best replacement? Note: I've never done this.

Why not just move the default out of the finally block?

try:
something_that_can_break()
return foo() # before clean_up
finally:
clean_up()
if default:
return default() # after clean_up()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-07 Thread Ethan Furman

On 06/06/2014 11:22 AM, Ned Batchelder wrote:

On 6/6/14 1:47 PM, Frank B wrote:


Ok; thanks for the underscore and clarification.  Just need to adjust my 
thinking a bit.


Did this come up in real code?  I've seen this point about finally/return 
semantics a number of times, but haven't seen
real code that needed adjusting based on it.


I don't remember if I almost had this in real code or if I learned about it first, but it can definitely be a gotcha. 
It seems to me that if the try block exits with an explicit return, and then the finally block exits with an explicit 
return, some kind of error ought to be raised.


--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-07 Thread Chris Angelico
On Sun, Jun 8, 2014 at 8:49 AM, Ethan Furman et...@stoneleaf.us wrote:
 I don't remember if I almost had this in real code or if I learned about it
 first, but it can definitely be a gotcha. It seems to me that if the try
 block exits with an explicit return, and then the finally block exits with
 an explicit return, some kind of error ought to be raised.

I'd go a little simpler: A return statement inside a finally block is
code smell.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list



Re: try/except/finally

2014-06-07 Thread Roy Smith
In article mailman.10867.1402184850.18130.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 A return statement inside a finally block is code smell.

Not to my nose.  It seems like a perfectly reasonable thing to do.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-07 Thread Mark Lawrence

On 08/06/2014 01:12, Roy Smith wrote:

In article mailman.10867.1402184850.18130.python-l...@python.org,
  Chris Angelico ros...@gmail.com wrote:


A return statement inside a finally block is code smell.


Not to my nose.  It seems like a perfectly reasonable thing to do.



I agree, the code smell is the return in the except block.

--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-07 Thread Roy Smith
In article mailman.10871.1402189805.18130.python-l...@python.org,
 Mark Lawrence breamore...@yahoo.co.uk wrote:

 On 08/06/2014 01:12, Roy Smith wrote:
  In article mailman.10867.1402184850.18130.python-l...@python.org,
Chris Angelico ros...@gmail.com wrote:
 
  A return statement inside a finally block is code smell.
 
  Not to my nose.  It seems like a perfectly reasonable thing to do.
 
 
 I agree, the code smell is the return in the except block.

That's not setting my nose on end either.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-07 Thread Rustom Mody
On Sunday, June 8, 2014 5:17:21 AM UTC+5:30, Chris Angelico wrote:
 On Sun, Jun 8, 2014 at 8:49 AM, Ethan Furman  wrote:
  I don't remember if I almost had this in real code or if I learned about it
  first, but it can definitely be a gotcha. It seems to me that if the try
  block exits with an explicit return, and then the finally block exits with
  an explicit return, some kind of error ought to be raised.

 I'd go a little simpler: A return statement inside a finally block is
 code smell.

Some people¹ think that gotos are a code-smell.

And since both return and exceptions are thinly veiled gotos, what we
have here are two smells outsmelling each other.

¹ I am not exactly those people.
A chap called E W Dijkstra made the statement: Goto statement considered 
harmful and became famous.
The chap who taught me programming said to me: What the goto does to 
control structure, the assignment does to data structure
He did not become famous.
However in my view he made the more intelligent statement
-- 
https://mail.python.org/mailman/listinfo/python-list


try/except/finally

2014-06-06 Thread Frank B
Ok; this is a bit esoteric.

So finally is executed regardless of whether an exception occurs, so states the 
docs.

But, I thought, if I return from my function first, that should take 
precedence.

au contraire

Turns out that if you do this:

try:
  failingthing()
except FailException:
  return 0
finally:
  return 1

Then finally really is executed regardless... even though you told it to return.

That seems odd to me.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-06 Thread Roy Smith
In article 0a89c96d-de62-42ad-be48-6107ce10d...@googlegroups.com,
 Frank B fbick...@gmail.com wrote:

 Ok; this is a bit esoteric.
 
 So finally is executed regardless of whether an exception occurs, so states 
 the docs.
 
 But, I thought, if I return from my function first, that should take 
 precedence.
 
 au contraire
 
 Turns out that if you do this:
 
 try:
   failingthing()
 except FailException:
   return 0
 finally:
   return 1
 
 Then finally really is executed regardless... even though you told it to 
 return.
 
 That seems odd to me.

That's exactly what it's supposed to do.  The idea of finally is, No 
matter what else happens, including calling sys.exit(), make sure this 
code executed.  It's typically used to release some critical resource 
which was acquired in the body of the try block.
 
https://docs.python.org/2/reference/compound_stmts.html#the-try-statement
 says:

When a return, break or continue statement is executed in the try suite 
of a try...finally statement, the finally clause is also executed Œon 
the way out.¹

The only way I can think of to bypass a finally block would be to call 
os._exit(), or send yourself a kill signal.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-06 Thread Frank B
Ok; thanks for the underscore and clarification.  Just need to adjust my 
thinking a bit.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-06 Thread Ned Batchelder

On 6/6/14 1:47 PM, Frank B wrote:

Ok; thanks for the underscore and clarification.  Just need to adjust my 
thinking a bit.



Did this come up in real code?  I've seen this point about 
finally/return semantics a number of times, but haven't seen real code 
that needed adjusting based on it.


--
Ned Batchelder, http://nedbatchelder.com

--
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-31 Thread Göktuğ Kayaalp
Terry Reedy tjre...@udel.edu writes:

I do not have any information on the topic, but I *imagine* that the
when RETURN_VALUE opcode is evaluated within the context of an except
block, it triggers a check for whether a corresponding finally block
exists and should it exist, it is triggered, much like a callback.
So, my *imaginary* algorithm works like this:

return:
  if within an except block EB:
if EB has a correspoinding final block FB
  run FB
else
  do return
  else
do return

In Jessica's example, as the finally block executes a RETURN_VALUE
opcode, and as this is *probably* a jump to the caller, the rest of the
code does not get a chance to be executed.

As I have said earlier, I by no means assert the truth of this idea I've
explained here, but it seems quite reasonable to me.

  gk

 On 1/30/2014 7:05 AM, Dave Angel wrote:
   Jessica Ross deathwea...@gmail.com Wrote in message:
 I found something like this in a StackOverflow discussion.
 def paradox():
 ... try:
 ... raise Exception(Exception raised during try)
 ... except:
 ... print Except after try
 ... return True
 ... finally:
 ... print Finally
 ... return False
 ... return None
 ...
 return_val = paradox()
 Except after try
 Finally
 return_val
 False

 I understand most of this.
 What I don't understand is why this returns False rather than True. Does 
 the finally short-circuit the return in the except block?


 The finally has to happen before any return inside the try or the
   except.  And once you're in the finally clause you'll finish it
   before resuming the except clause.  Since it has a return,  that
   will happen before the other returns. The one in the except block
   will never get reached.

 It's the only reasonable behavior., to my mind.

 Checking with the disassembled code, it appears that the except return
 happens first and is then caught and the value over-written

   2   0 SETUP_FINALLY   45 (to 48)
   3 SETUP_EXCEPT16 (to 22)

   3   6 LOAD_GLOBAL  0 (Exception)
   9 LOAD_CONST   1 ('Exception raised during try')
  12 CALL_FUNCTION1 (1 positional, 0 keyword pair)
  15 RAISE_VARARGS1
  18 POP_BLOCK
  19 JUMP_FORWARD22 (to 44)

   422 POP_TOP
  23 POP_TOP
  24 POP_TOP

   5  25 LOAD_GLOBAL  1 (print)
  28 LOAD_CONST   2 ('Except after try')
  31 CALL_FUNCTION1 (1 positional, 0 keyword pair)
  34 POP_TOP

   6  35 LOAD_CONST   3 (True)
  38 RETURN_VALUE
  39 POP_EXCEPT
  40 JUMP_FORWARD 1 (to 44)
  43 END_FINALLY
44 POP_BLOCK
  45 LOAD_CONST   0 (None)

   848 LOAD_GLOBAL  1 (print)
  51 LOAD_CONST   4 ('Finally')
  54 CALL_FUNCTION1 (1 positional, 0 keyword pair)
  57 POP_TOP

   9  58 LOAD_CONST   5 (False)
  61 RETURN_VALUE
  62 END_FINALLY

  10  63 LOAD_CONST   0 (None)
  66 RETURN_VALUE




 -- 
 Terry Jan Reedy

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-30 Thread Chris Angelico
On Thu, Jan 30, 2014 at 11:05 PM, Dave Angel da...@davea.name wrote:
 The finally has to happen before any return inside the try or the
  except.  And once you're in the finally clause you'll finish it
  before resuming the except clause.  Since it has a return,  that
  will happen before the other returns. The one in the except block
  will never get reached.

 It's the only reasonable behavior., to my mind.

It's arguable that putting a return inside a finally is unreasonable
behaviour, but that's up to the programmer. A finally clause can be
used to do what might be done in C++ with a destructor: no matter how
this function/block exits, do this as you unwind the stack. In C++, I
might open a file like this:

void func()
{
ofstream output(output.txt);
// do a whole lot of stuff ...
// at the close brace, output.~output() will be called, which will
close the file
}

In Python, the equivalent would be:

def func():
try:
output = open(output.txt, w)
# do a whole lot of stuff ...
finally:
output.close()

(Actually, the Python equivalent would be to use a 'with' clause for
brevity, but 'with' uses try/finally under the covers, so it comes to
the same thing.) The concept of the finally clause is: Whether
execution runs off the end, hits a return statement, or throws an
exception, I need you do this before anything else happens. Having a
return statement inside 'finally' as well as in 'try' is a bit of a
corner case, since you're now saying Before you finish this function
and return something, I need you to return something else, which
doesn't usually make sense. If you think Python's behaviour is
confusing, first figure out what you would expect to happen in this
situation :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-30 Thread MRAB

On 2014-01-30 13:02, Chris Angelico wrote:

On Thu, Jan 30, 2014 at 11:05 PM, Dave Angel da...@davea.name wrote:

The finally has to happen before any return inside the try or the
 except.  And once you're in the finally clause you'll finish it
 before resuming the except clause.  Since it has a return,  that
 will happen before the other returns. The one in the except block
 will never get reached.

It's the only reasonable behavior., to my mind.


It's arguable that putting a return inside a finally is unreasonable
behaviour, but that's up to the programmer. A finally clause can be
used to do what might be done in C++ with a destructor: no matter how
this function/block exits, do this as you unwind the stack. In C++, I
might open a file like this:

void func()
{
 ofstream output(output.txt);
 // do a whole lot of stuff ...
 // at the close brace, output.~output() will be called, which will
close the file
}

In Python, the equivalent would be:

def func():
 try:
 output = open(output.txt, w)
 # do a whole lot of stuff ...
 finally:
 output.close()

(Actually, the Python equivalent would be to use a 'with' clause for
brevity, but 'with' uses try/finally under the covers, so it comes to
the same thing.) The concept of the finally clause is: Whether
execution runs off the end, hits a return statement, or throws an
exception, I need you do this before anything else happens. Having a
return statement inside 'finally' as well as in 'try' is a bit of a
corner case, since you're now saying Before you finish this function
and return something, I need you to return something else, which
doesn't usually make sense. If you think Python's behaviour is
confusing, first figure out what you would expect to happen in this
situation :)


One of the reasons that the 'with' statement was added was to prevent
the mistake that you've just done. ;-)

What if the file can't be opened?

--
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-30 Thread Chris Angelico
On Fri, Jan 31, 2014 at 12:11 AM, MRAB pyt...@mrabarnett.plus.com wrote:
 One of the reasons that the 'with' statement was added was to prevent
 the mistake that you've just done. ;-)

 What if the file can't be opened?

Yeah, whoops. The open shouldn't be inside try/finally.

def func():
output = open(output.txt, w)
try:
 # do a whole lot of stuff ...
finally:
 output.close()

But my point still stands, I believe :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-30 Thread Rotwang

On 30/01/2014 06:33, Andrew Berg wrote:

On 2014.01.29 23:56, Jessica Ross wrote:

I found something like this in a StackOverflow discussion.

def paradox():

... try:
... raise Exception(Exception raised during try)
... except:
... print Except after try
... return True
... finally:
... print Finally
... return False
... return None
...

return_val = paradox()

Except after try
Finally

return_val

False

I understand most of this.
What I don't understand is why this returns False rather than True.
Does the finally short-circuit the return in the except block?


My guess would be that the interpreter doesn't let the finally block
get skipped under any circumstances, so the return value gets set to
True, but then it forces the finally block to be run before returning,
which changes the return value to False.


Mine too. We can check that the interpreter gets as far as evaluating 
the return value in the except block:


 def paradox2():
try:
raise Exception(Raise)
except:
print(Except)
return [print(Return), True][1]
finally:
print(Finally)
return False
return None

 ret = paradox2()
Except
Return
Finally
 ret
False
--
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-30 Thread Ethan Furman

On 01/30/2014 10:12 AM, Rotwang wrote:

On 30/01/2014 06:33, Andrew Berg wrote:

On 2014.01.29 23:56, Jessica Ross wrote:


I found something like this in a StackOverflow discussion.
-- def paradox():
... try:
... raise Exception(Exception raised during try)
... except:
... print Except after try
... return True
... finally:
... print Finally
... return False
... return None
...
-- return_val = paradox()
Except after try
Finally
-- return_val
False

I understand most of this.
What I don't understand is why this returns False rather than True.
Does the finally short-circuit the return in the except block?


My guess would be that the interpreter doesn't let the finally block
get skipped under any circumstances, so the return value gets set to
True, but then it forces the finally block to be run before returning,
which changes the return value to False.


Mine too. We can check that the interpreter gets as far as evaluating the 
return value in the except block:

-- def paradox2():
   try:
   raise Exception(Raise)
   except:
   print(Except)
   return [print(Return), True][1]
   finally:
   print(Finally)
   return False
   return None

-- ret = paradox2()
Except
Return
Finally
-- ret
False


And just to be thorough, if the finally block doesn't have a return:

-- def paradox3():
try:
raise Exception(Raise)
except:
print(Except)
return [print(Return), True][1]
finally:
print(Finally)
return None

-- print(paradox3())
Except
Return
Finally
True

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-30 Thread Terry Reedy

On 1/30/2014 7:05 AM, Dave Angel wrote:

  Jessica Ross deathwea...@gmail.com Wrote in message:

I found something like this in a StackOverflow discussion.

def paradox():

... try:
... raise Exception(Exception raised during try)
... except:
... print Except after try
... return True
... finally:
... print Finally
... return False
... return None
...

return_val = paradox()

Except after try
Finally

return_val

False

I understand most of this.
What I don't understand is why this returns False rather than True. Does the 
finally short-circuit the return in the except block?



The finally has to happen before any return inside the try or the
  except.  And once you're in the finally clause you'll finish it
  before resuming the except clause.  Since it has a return,  that
  will happen before the other returns. The one in the except block
  will never get reached.

It's the only reasonable behavior., to my mind.


Checking with the disassembled code, it appears that the except return 
happens first and is then caught and the value over-written


  2   0 SETUP_FINALLY   45 (to 48)
  3 SETUP_EXCEPT16 (to 22)

  3   6 LOAD_GLOBAL  0 (Exception)
  9 LOAD_CONST   1 ('Exception raised during try')
 12 CALL_FUNCTION1 (1 positional, 0 keyword pair)
 15 RAISE_VARARGS1
 18 POP_BLOCK
 19 JUMP_FORWARD22 (to 44)

  422 POP_TOP
 23 POP_TOP
 24 POP_TOP

  5  25 LOAD_GLOBAL  1 (print)
 28 LOAD_CONST   2 ('Except after try')
 31 CALL_FUNCTION1 (1 positional, 0 keyword pair)
 34 POP_TOP

  6  35 LOAD_CONST   3 (True)
 38 RETURN_VALUE
 39 POP_EXCEPT
 40 JUMP_FORWARD 1 (to 44)
 43 END_FINALLY
   44 POP_BLOCK
 45 LOAD_CONST   0 (None)

  848 LOAD_GLOBAL  1 (print)
 51 LOAD_CONST   4 ('Finally')
 54 CALL_FUNCTION1 (1 positional, 0 keyword pair)
 57 POP_TOP

  9  58 LOAD_CONST   5 (False)
 61 RETURN_VALUE
 62 END_FINALLY

 10  63 LOAD_CONST   0 (None)
 66 RETURN_VALUE




--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Try-except-finally paradox

2014-01-29 Thread Jessica Ross
I found something like this in a StackOverflow discussion.
 def paradox():
... try:
... raise Exception(Exception raised during try)
... except:
... print Except after try
... return True
... finally:
... print Finally
... return False
... return None
... 
 return_val = paradox()
Except after try
Finally
 return_val
False

I understand most of this.
What I don't understand is why this returns False rather than True. Does the 
finally short-circuit the return in the except block?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-29 Thread Ian Kelly
On Jan 29, 2014 11:01 PM, Jessica Ross deathwea...@gmail.com wrote:

 I found something like this in a StackOverflow discussion.
  def paradox():
 ... try:
 ... raise Exception(Exception raised during try)
 ... except:
 ... print Except after try
 ... return True
 ... finally:
 ... print Finally
 ... return False
 ... return None
 ...
  return_val = paradox()
 Except after try
 Finally
  return_val
 False

 I understand most of this.
 What I don't understand is why this returns False rather than True. Does
the finally short-circuit the return in the except block?

The docs don't seem to specify what happens in this case, but this behavior
is intuitive to me. If the except suite had raised an exception instead of
returning, the return in the finally would suppress that. The generalized
rule appears to be that the control flow specification executed later
overrides the earlier.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-29 Thread Andrew Berg
On 2014.01.29 23:56, Jessica Ross wrote:
 I found something like this in a StackOverflow discussion.
 def paradox():
 ... try:
 ... raise Exception(Exception raised during try)
 ... except:
 ... print Except after try
 ... return True
 ... finally:
 ... print Finally
 ... return False
 ... return None
 ... 
 return_val = paradox()
 Except after try
 Finally
 return_val
 False
 
 I understand most of this.
 What I don't understand is why this returns False rather than True. Does the 
 finally short-circuit the return in the except block?
 
My guess would be that the interpreter doesn't let the finally block get 
skipped under any circumstances, so the return value gets set to
True, but then it forces the finally block to be run before returning, which 
changes the return value to False.

-- 
CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 10.0
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except-finally paradox

2014-01-29 Thread wxjmfauth
Le jeudi 30 janvier 2014 06:56:16 UTC+1, Jessica Ross a écrit :
 I found something like this in a StackOverflow discussion.
 
  def paradox():
 
 ... try:
 
 ... raise Exception(Exception raised during try)
 
 ... except:
 
 ... print Except after try
 
 ... return True
 
 ... finally:
 
 ... print Finally
 
 ... return False
 
 ... return None
 
 ... 
 
  return_val = paradox()
 
 Except after try
 
 Finally
 
  return_val
 
 False
 
 
 
 I understand most of this.
 
 What I don't understand is why this returns False rather than True. Does the 
 finally short-circuit the return in the except block?



The paradox is, in my mind, that the fct paradox() is
programmed to be paradoxal.

Compare with:

 def noparadox(i):
... try:
... a = 1 / i
... print('Process')
... except ZeroDivisionError:
... print(ZeroDivisionError)
... a = '?'
... except Exception:
... print(Exception)
... a = '?'
... finally:
... print(Finally)
... return a
... 
 noparadox(2)
Process
Finally
0.5
 noparadox(0)
ZeroDivisionError
Finally
'?'
 noparadox('asdf')
Exception
Finally
'?'


jmf
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue1757118] utilize 2.5 try/except/finally in contextlib

2012-06-19 Thread Georg Brandl

Changes by Georg Brandl ge...@python.org:


Removed file: http://bugs.python.org/file25625/1.html

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue1757118
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1757118] utilize 2.5 try/except/finally in contextlib

2012-05-17 Thread Fyrn Jilot

Changes by Fyrn Jilot fyrn7...@yahoo.com:


Added file: http://bugs.python.org/file25625/1.html

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue1757118
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4529] parser module failure on valid try/except/finally blocks

2008-12-05 Thread Georg Brandl

Georg Brandl [EMAIL PROTECTED] added the comment:

Fixed in r67576, will be ported to all branches.

--
nosy: +georg.brandl
resolution:  - fixed
status: open - closed

___
Python tracker [EMAIL PROTECTED]
http://bugs.python.org/issue4529
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4529] parser module failure on valid try/except/finally blocks

2008-12-04 Thread Kai Willadsen

New submission from Kai Willadsen [EMAIL PROTECTED]:

Using the parser module to create a parse tree succeeds, but a
subsequent tuple2ast fails, when parsing valid try/except/finally (and
try/except/else/finally) blocks. parser.tuple2ast fails with:
  parser.ParserError: Illegal number of children for try/finally node.

--
files: parser-testcase.py
messages: 76900
nosy: kaiw
severity: normal
status: open
title: parser module failure on valid try/except/finally blocks
type: behavior
versions: Python 2.5
Added file: http://bugs.python.org/file12221/parser-testcase.py

___
Python tracker [EMAIL PROTECTED]
http://bugs.python.org/issue4529
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1757118] utilize 2.5 try/except/finally in contextlib

2007-08-23 Thread Georg Brandl

Georg Brandl added the comment:

Committed in rev. 57331.

--
assignee:  - gbrandl
nosy: +gbrandl
resolution:  - accepted
status: open - closed

_
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1757118
_
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



try...except...finally problem in Python 2.5

2007-02-14 Thread redawgts
I keep getting this error local variable 'f' referenced before
assignment in the finally block when I run the following code.

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
self.isDataLoaded = False
finally:
f.close()

Can someone tell me what's wrong with the code? Am I doing something
wrong? I'm somewhat new to python but this makes sense to me.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Jean-Paul Calderone
On 14 Feb 2007 11:41:29 -0800, redawgts [EMAIL PROTECTED] wrote:
I keep getting this error local variable 'f' referenced before
assignment in the finally block when I run the following code.

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
self.isDataLoaded = False
finally:
f.close()

Can someone tell me what's wrong with the code? Am I doing something
wrong? I'm somewhat new to python but this makes sense to me.


f is not bound until the first line of the try suite has completely
successfully executed.  If it fails to do this, for example because
self.filename is an attribute error, or the filename given by that
attribute does not exist, then the finally suite will execute before
f has been bound, and the UnboundLocalError will mask the real error.

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Robert Kern
redawgts wrote:
 I keep getting this error local variable 'f' referenced before
 assignment in the finally block when I run the following code.
 
 try:
 f = file(self.filename, 'rb')
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 except:
 self.isDataLoaded = False
 finally:
 f.close()
 
 Can someone tell me what's wrong with the code? Am I doing something
 wrong? I'm somewhat new to python but this makes sense to me.

Move the f = file(self.filename, 'rb') above the try:. If opening the file
happens to throw an exception, then the assignment will never happen and there
will be no 'f' to close.

-- 
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Andrew Koenig
redawgts [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

I keep getting this error local variable 'f' referenced before
 assignment in the finally block when I run the following code.

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
self.isDataLoaded = False
finally:
f.close()

 Can someone tell me what's wrong with the code? Am I doing something
 wrong? I'm somewhat new to python but this makes sense to me.

If the call to file raises an exception, then variable f won't have been 
created.

Here's a simple example:

def f():
throw 42
try:
x = f()
except:
print x

Try it and see what happens.  While you're at it, you might try to figure 
out what you would like it to print.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Larry Bates
redawgts wrote:
 I keep getting this error local variable 'f' referenced before
 assignment in the finally block when I run the following code.
 
 try:
 f = file(self.filename, 'rb')
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 except:
 self.isDataLoaded = False
 finally:
 f.close()
 
 Can someone tell me what's wrong with the code? Am I doing something
 wrong? I'm somewhat new to python but this makes sense to me.
 
finally: block is executed even if there is an exception in which case f
hasn't been defined.  What you want is:

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

except:
isDataLoaded=False

else:
f.close()

-Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Paul Rubin
redawgts [EMAIL PROTECTED] writes:
 try:
 f = file(self.filename, 'rb') ...
 Can someone tell me what's wrong with the code? 

Various people have explained the error: if the file open attempt
fails, f is never assigned.  Doing it the right way (i.e. handling the
potential exceptions separately) with try/except statements is messy,
so it's worth mentioning that 2.5 adds the new with statement to
clean this up.  I'm not using 2.5 myself yet so maybe someone will
have to correct me, but I think you'd write:

from __future__ import with_statement

self.isDataLoaded = False
with open(self.filename, 'rb') as f:
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

and that should handle everything, closing the file automatically.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread redawgts
Thanks everybody, that helped alot.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Steven D'Aprano
On Wed, 14 Feb 2007 12:09:34 -0800, Paul Rubin wrote:

 redawgts [EMAIL PROTECTED] writes:
 try:
 f = file(self.filename, 'rb') ...
 Can someone tell me what's wrong with the code? 
 
 Various people have explained the error: if the file open attempt
 fails, f is never assigned.  Doing it the right way (i.e. handling the
 potential exceptions separately) with try/except statements is messy,
 so it's worth mentioning that 2.5 adds the new with statement to
 clean this up.  I'm not using 2.5 myself yet so maybe someone will
 have to correct me, but I think you'd write:
 
 from __future__ import with_statement
 
 self.isDataLoaded = False
 with open(self.filename, 'rb') as f:
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 
 and that should handle everything, closing the file automatically.


I don't have Python 2.5 here to experiment, but how is that different from
this?


self.isDataLoaded = False
try:
f = open(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
pass
else:
pass

(apart from being four lines shorter)



-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes:
 self.isDataLoaded = False
 try:
 f = open(self.filename, 'rb')
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 except:
 pass
 else:
 pass
 
 (apart from being four lines shorter)

Your version never closes the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Steven D'Aprano
On Wed, 14 Feb 2007 18:03:19 -0800, Paul Rubin wrote:

 Steven D'Aprano [EMAIL PROTECTED] writes:
 self.isDataLoaded = False
 try:
 f = open(self.filename, 'rb')
 f.seek(DATA_OFFSET)
 self.__data = f.read(DATA_SIZE)
 self.isDataLoaded = True
 except:
 pass
 else:
 pass
 
 (apart from being four lines shorter)
 
 Your version never closes the file.


Yes it does. Eventually f goes out of scope and is closed automatically.

I don't see where the with version closes the file either. How does it
know that I want to call the f's close() method, rather than, say,
f.exit() or f.do_something_else()?



-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Steven D'Aprano
Replying to my own question...

On Thu, 15 Feb 2007 13:17:00 +1100, Steven D'Aprano wrote:

 I don't see where the with version closes the file either. How does it
 know that I want to call the f's close() method, rather than, say,
 f.exit() or f.do_something_else()?

Ah, I *think* I see... file objects in Python 2.5 are objects that know
how to work with the with statement; that is they obey the context
management protocol and have __enter__ and __exit__ methods that do the
right thing to make everything work correctly.

http://docs.python.org/whatsnew/pep-343.html

Have I got it right?


-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes:
 Yes it does. Eventually f goes out of scope and is closed automatically.

Oh right, however you can't really predict when the closure occurs,
unless you're relying on current CPython artifacts.

Re your other post: yes, PEP 363 explains how the with statement
calls the __exit__ method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try...except...finally problem in Python 2.5

2007-02-14 Thread Paul Rubin
Paul Rubin http://[EMAIL PROTECTED] writes:
 Re your other post: yes, PEP 363 explains how the with statement

Whoops, 343. 
-- 
http://mail.python.org/mailman/listinfo/python-list


[ python-Bugs-1453570 ] try-except-finally in the tutorial

2006-03-19 Thread SourceForge.net
Bugs item #1453570, was opened at 2006-03-19 04:36
Message generated for change (Comment added) made by gbrandl
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1453570group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: Python 2.5
Status: Closed
Resolution: Fixed
Priority: 5
Submitted By: George Yoshida (quiver)
Assigned to: Nobody/Anonymous (nobody)
Summary: try-except-finally in the tutorial

Initial Comment:
Doc/tut/tut.tex describes finally statement as ::

  A try statement must either have one or more except 
clauses or one finally clause, but not both ...

But now that PEP 341[*] has been accepted and merged, 
this part needs a rewrite.

Adding a new section or an example using try-except-
(else-)finally will be required.

* http://www.python.org/peps/pep-0341.html


--

Comment By: Georg Brandl (gbrandl)
Date: 2006-03-19 11:21

Message:
Logged In: YES 
user_id=849994

I updated that section. try-except-finally should be made
clear now. [rev. 43142]

Thanks for spotting!

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1453570group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1453570 ] try-except-finally in the tutorial

2006-03-18 Thread SourceForge.net
Bugs item #1453570, was opened at 2006-03-19 13:36
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1453570group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: Python 2.5
Status: Open
Resolution: None
Priority: 5
Submitted By: George Yoshida (quiver)
Assigned to: Nobody/Anonymous (nobody)
Summary: try-except-finally in the tutorial

Initial Comment:
Doc/tut/tut.tex describes finally statement as ::

  A try statement must either have one or more except 
clauses or one finally clause, but not both ...

But now that PEP 341[*] has been accepted and merged, 
this part needs a rewrite.

Adding a new section or an example using try-except-
(else-)finally will be required.

* http://www.python.org/peps/pep-0341.html


--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1453570group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Exception handling code (try/except/finally)

2005-03-07 Thread djw
c.l.p-
I am having trouble understanding how one is supposed to correctly 
utilize try:...except:...finally: in real code. If I have a block of 
code like:

def foo():
try:
... some code that can raise an exception ...
finally:
... do some cleanup ...
return something
If any exception occurs in the code inside the try:...finally:, it will 
fail silently, which is a bad thing.

So, the obvious thing to do (I think) is:
def foo():
try:
try:
... some code that can raise an exception ...
except someerror:
... handle the error...
finally:
... do some cleanup ...
return something
But, now the finally doesn't really serve any purpose, if all the 
exceptions are handled by except:, finally will never be called as a 
result of an exception, only as the last statements of the function.

So, the next step is to do this?
def foo():
try:
try:
... some code that can raise an exception ...
except someerror:
... handle the error...
raise someerror
finally:
... do some cleanup ...
return something
Which, I guess will work, but it feels very awkward. Is this the 
preferred/correct way to handle this? Is there a more elegant solution?

Also, why is this construct not possible?:
try:
... some code that can raise an exception ...
except someerror:
... handle the error...
finally:
... do cleanup, etc. ...
Thanks,
Don

--
http://mail.python.org/mailman/listinfo/python-list


Re: Exception handling code (try/except/finally)

2005-03-07 Thread Michael Hoffman
djw wrote:
c.l.p-
I am having trouble understanding how one is supposed to correctly 
utilize try:...except:...finally: in real code. If I have a block of 
code like:

def foo():
try:
... some code that can raise an exception ...
finally:
... do some cleanup ...
return something
If any exception occurs in the code inside the try:...finally:, it will 
fail silently, which is a bad thing.
You want:
def foo():
try:
...work...
finally:
...cleanup...
return something
By removing the return from the finally block you will still
automatically raise an exception when something goes wrong.
Having the return in the finally block prevents that from happening.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list