Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-13 Thread Nick Coghlan
On 13 March 2014 07:49, Chris Angelico ros...@gmail.com wrote:

 Umm, yeah, that one. Why did I think hasattr was the only way around
 that? Anyway, that just means I picked a bad example. There are others
 where you have to go for the full try/except.

You may have been thinking of item lookup on sequences. Attribute
lookup can switch to getattr (at the cost of becoming more opaque to
the compiler and static analysers), and mappings can fall back to
get(), but there's no such alternative for sequences.

Anyway - exemplary work on the PEP, even though Guido remained
unconvinced. Not only does it become a useful resource if anyone else
comes forward with a similar proposal, it becomes something we can
point to and perhaps revisit next time someone asks for implicit
exception handling to be added to yet another API :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-13 Thread Victor Stinner
Hi,

2014-03-12 18:09 GMT+01:00 Guido van Rossum gu...@python.org:
 I want to reject this PEP. (...)
 this was a well-written and well-researched PEP, and I think you've done a
 great job moderating the discussion, collecting objections, reviewing
 alternatives, and everything else that is required to turn a heated debate
 into a PEP. Well done Chris (and everyone who helped), and good luck with
 your next PEP!

I spend many weeks to work (write the PEP *and* implement them) on the
following PEPs and Guido rejected them:

- PEP 416: Add a frozendict builtin type
- PEP 410: Use decimal.Decimal type for timestamps

It's hard to accept that a wonderful idea at a first look is not a
good idea. Some months later, I now agree and see issues of my PEPs.
The PEP process ensures that the Python language (+ stdlib) keeps
consistent and well designed.

Even if a PEP is rejected, it becomes the best reference if someone
requests the same or a similar feature some months or years later.
Rejected PEPs explain almost how the Python language was designed.

For thanks Chris, and I hope that it's not too hard for you to accept
the fact that your inline try/except idea is maybe not as good as
you expected :-)

Victor
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-13 Thread Chris Angelico
On Thu, Mar 13, 2014 at 8:15 PM, Victor Stinner
victor.stin...@gmail.com wrote:
 Even if a PEP is rejected, it becomes the best reference if someone
 requests the same or a similar feature some months or years later.
 Rejected PEPs explain almost how the Python language was designed.

 For thanks Chris, and I hope that it's not too hard for you to accept
 the fact that your inline try/except idea is maybe not as good as
 you expected :-)

One of the original goals of the PEP was to get everything written
down. I actually didn't have any sort of strong opinion on the matter
until part way in; effectively, I had to first convince myself, then
try to convince others :) So it's not hard to accept that the idea
isn't such a good one.

ChrisA
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-13 Thread Barry Warsaw
On Mar 13, 2014, at 10:15 AM, Victor Stinner wrote:

It's hard to accept that a wonderful idea at a first look is not a
good idea. Some months later, I now agree and see issues of my PEPs.
The PEP process ensures that the Python language (+ stdlib) keeps
consistent and well designed.

Even if a PEP is rejected, it becomes the best reference if someone
requests the same or a similar feature some months or years later.
Rejected PEPs explain almost how the Python language was designed.

For thanks Chris, and I hope that it's not too hard for you to accept
the fact that your inline try/except idea is maybe not as good as
you expected :-)

Don't worry, there's always Python 4 wink.

http://legacy.python.org/dev/peps/pep-0274/

-Barry
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-13 Thread Nikolaus Rath
Tres Seaver tsea...@palladion.com writes:
 On 03/12/2014 04:49 PM, Chris Angelico wrote:
 You can use hasattr() in place of AttributeError

 I use:

  getattr(subject, attrname, default)?

 *all the time*.

In my opinion that's almost as ugly, because it still forces you to
specify the attribute name as a string rather than an identifier.


Best,
Nikolaus

-- 
Encrypted emails preferred.
PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C

 »Time flies like an arrow, fruit flies like a Banana.«
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Brett Cannon
On Wed, Mar 12, 2014 at 12:10 AM, Chris Angelico ros...@gmail.com wrote:

 PEP 463, Exception-catching expressions, is stable and I believe ready
 for pronouncement. Drumroll please...

 http://www.python.org/dev/peps/pep-0463/

 PEP: 463
 Title: Exception-catching expressions
 Version: $Revision$
 Last-Modified: $Date$
 Author: Chris Angelico ros...@gmail.com
 Status: Draft
 Type: Standards Track
 Content-Type: text/x-rst
 Created: 15-Feb-2014
 Python-Version: 3.5
 Post-History: 20-Feb-2014, 16-Feb-2014


While I'm +0 on the idea, I'm -1 on the syntax; I just don't like having a
colon in an expression.
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Chris Angelico
On Thu, Mar 13, 2014 at 2:14 AM, Brett Cannon br...@python.org wrote:
 While I'm +0 on the idea, I'm -1 on the syntax; I just don't like having a
 colon in an expression.

Which is why there are alternatives listed, and the best four of them
(including the proposed one) ranked.

ChrisA
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Brett Cannon
On Wed, Mar 12, 2014 at 11:16 AM, Chris Angelico ros...@gmail.com wrote:

 On Thu, Mar 13, 2014 at 2:14 AM, Brett Cannon br...@python.org wrote:
  While I'm +0 on the idea, I'm -1 on the syntax; I just don't like having
 a
  colon in an expression.

 Which is why there are alternatives listed, and the best four of them
 (including the proposed one) ranked.


`value = (expr except Exception then default)` would be fine with me.
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Barry Warsaw
On Mar 12, 2014, at 11:14 AM, Brett Cannon wrote:

While I'm +0 on the idea, I'm -1 on the syntax; I just don't like having a
colon in an expression.

I'm -0 on the idea, mostly be cause it's never occurred to me to even need
something like this, and because I don't personally think the existing
spellings are deficient.  It doesn't bother me that we have dict.get() for
example.  I'd also find the proposed syntax difficult to read if it was used
more commonly than traditional try/except.

That being said, the colon really bothers me, despite what is written in
Common objections.  True, colons are used in places other than suite
introduction, but with exception handling, colons *do* introduce a new suite,
so its use here is jarring.  There may also be tooling issues (e.g. editors,
syntax colorizers, parsers, etc.).

Anyway, put it on the language summit track and we can have a fun debate. :)

-Barryu
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Chris Angelico
On Thu, Mar 13, 2014 at 2:44 AM, Barry Warsaw ba...@python.org wrote:
 That being said, the colon really bothers me, despite what is written in
 Common objections.  True, colons are used in places other than suite
 introduction, but with exception handling, colons *do* introduce a new suite,
 so its use here is jarring.  There may also be tooling issues (e.g. editors,
 syntax colorizers, parsers, etc.).

Tooling issues should already have been solved for lambda, but if you
don't like the colon, go with one of the other options - Brett
expressed support for 'then', which makes very good sense (it does
require creating a new keyword, but it's a fairly safe one).

ChrisA
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Paul Moore
On 12 March 2014 16:05, Chris Angelico ros...@gmail.com wrote:
 Tooling issues should already have been solved for lambda, but if you
 don't like the colon, go with one of the other options - Brett
 expressed support for 'then', which makes very good sense (it does
 require creating a new keyword, but it's a fairly safe one).

As a data point, Vim's syntax highlighting works mostly fine out of
the box for the top 4 proposed syntaxes. The keyword versions have
minor issues - then is not highlighted at all and pass is
highlighted as pythonStatement which is slightly jarring. The
punctuation-based variants just don't highlight the : or - which
is fine. Making then a keyword in Vim's syntax wouldn't be too hard,
you'd probably put it in class pythonException along with except,
try, finally and raise (which seems a bit odd, but that's actually the
only place then is used as a keyword, so it's right). Making pass
highlight as a statement when used standalone or as an expression
keyword in an except would be tricky (i.e., I wouldn't know how to do
it :-))

The highlighting issue is jarring enough to put me off the pass option.

Paul
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Gustavo Carneiro
On 12 March 2014 15:21, Brett Cannon br...@python.org wrote:




 On Wed, Mar 12, 2014 at 11:16 AM, Chris Angelico ros...@gmail.com wrote:

 On Thu, Mar 13, 2014 at 2:14 AM, Brett Cannon br...@python.org wrote:
  While I'm +0 on the idea, I'm -1 on the syntax;



 I just don't like having a
  colon in an expression.


lambda: is an expression and has a colon in it.

It would be weird to use except: without a colon IMHO, because we are
already used to write except: with colon everywhere else...

Which is why there are alternatives listed, and the best four of them
 (including the proposed one) ranked.


 `value = (expr except Exception then default)` would be fine with me.


Do we really need to introduce a new keyword 'then' ?

I'm +1 on the original proposal (expr except Exception: default)

-- 
Gustavo J. A. M. Carneiro
Gambit Research
The universe is always one step beyond logic. -- Frank Herbert
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Guido van Rossum
On Tue, Mar 11, 2014 at 9:10 PM, Chris Angelico ros...@gmail.com wrote:

 PEP 463, Exception-catching expressions, is stable and I believe ready
 for pronouncement. Drumroll please...

 http://www.python.org/dev/peps/pep-0463/

 PEP: 463
 Title: Exception-catching expressions
 Version: $Revision$
 Last-Modified: $Date$
 Author: Chris Angelico ros...@gmail.com
 Status: Draft
 Type: Standards Track
 Content-Type: text/x-rst
 Created: 15-Feb-2014
 Python-Version: 3.5
 Post-History: 20-Feb-2014, 16-Feb-2014


 Abstract
 

 Just as PEP 308 introduced a means of value-based conditions in an
 expression, this system allows exception-based conditions to be used
 as part of an expression.


I want to reject this PEP. I think the proposed syntax is acceptable given
the desired semantics, although it's still a bit jarring. It's probably no
worse than the colon used with lambda (which echoes the colon used in a def
just like the colon here echoes the one in a try/except) and definitely
better than the alternatives listed.

But the thing I can't get behind are the motivation and rationale. I don't
think that e.g. dict.get() would be unnecessary once we have except
expressions, and I disagree with the position that EAFP is better than
LBYL, or generally recommended by Python. (Where do you get that? From
the same sources that are so obsessed with DRY they'd rather introduce a
higher-order-function than repeat one line of code? :-)

This is probably the most you can get out of me as far as a pronouncement.
Given that the language summit is coming up I'd be happy to dive deeper in
my reasons for rejecting it there (if there's demand).

I do think that (apart from never explaining those dreadful acronyms :-)
this was a well-written and well-researched PEP, and I think you've done a
great job moderating the discussion, collecting objections, reviewing
alternatives, and everything else that is required to turn a heated debate
into a PEP. Well done Chris (and everyone who helped), and good luck with
your next PEP!

-- 
--Guido van Rossum (python.org/~guido)
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Ethan Furman

On 03/12/2014 10:09 AM, Guido van Rossum wrote:


I want to reject this PEP.  [...]

But the thing I can't get behind are the motivation and rationale. I don't 
think that e.g. dict.get() would be
unnecessary once we have except expressions, and I disagree with the position 
that EAFP is better than LBYL [...]


Does this mean a better motivation and rationale may cause you to change your 
mind?

My motivation is for simpler, easier to read code:  instead of a full-blown try/except block or a double-lookup into an 
indexable object I would much rather do:


self.date = text_to_date(date, 'mdy') except ValueError: batch_date

instead of:

try:
self.date = text_to_date(date, 'mdy')
except ValueError:
self.date = batch_date



This is probably the most you can get out of me as far as a pronouncement. 
Given that the language summit is coming up
I'd be happy to dive deeper in my reasons for rejecting it there (if there's 
demand).


I would like to know, but I won't be at the language summit.  I can wait until after, though --  I know time is in 
especially short supply until then.


--
~Ethan~
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Barry Warsaw
On Mar 12, 2014, at 10:40 AM, Ethan Furman wrote:

Does this mean a better motivation and rationale may cause you to change your
mind?

My motivation is for simpler, easier to read code: instead of a full-blown
try/except block or a double-lookup into an indexable object I would much
rather do:

 self.date = text_to_date(date, 'mdy') except ValueError: batch_date

instead of:

 try:
 self.date = text_to_date(date, 'mdy')
 except ValueError:
 self.date = batch_date

I have to challenge a couple of assertions here.  First, that the exception
expression is easier to read.  I'm not sure it is.  I suspect they will tend
to be expressed on very long lines, much like ternary expressions are today.
PEP 8 then would have you split them across multiple lines, which introduces
parentheses or backslashes to accomplish.

For ternary expressions, this can get ugly and for me sometimes draws me back
to traditional if/else statements.  Other times, ternaries can be worth it,
but either way, it does (again for me) reduce the readability argument.

Interestingly enough, where ternaries are most useful are in the same
situations where I think exception expressions would be most useful, in the
setting of a variable or attribute to one of two different values.  In both
branches of the conditional, the left hand side is the same target, and what
differs is the value being assigned to the LHS.

Looking over exception examples from a large code base, I find it rare (but
not nonexistent) that exceptions are used in the same situation.  But that
could be because I'm so comfortable with .get() and other helpers.  Ternary
expressions seem more compelling.  But there's definitely some overlap, which
is perhaps why the colon seems so jarring to me.

So the second assertion is that these will be common enough to warrant
changing the language.  Again, I'm not personally convinced.

I echo Guido though: it is a well written PEP, and I commend Chris for
navigating the python-dev/python-ideas gauntlet!  That's an accomplishment
even if the PEP is rejected.

Cheers,
-Barry
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Chris Angelico
On Thu, Mar 13, 2014 at 4:09 AM, Guido van Rossum gu...@python.org wrote:
 But the thing I can't get behind are the motivation and rationale. I don't
 think that e.g. dict.get() would be unnecessary once we have except
 expressions, and I disagree with the position that EAFP is better than LBYL,
 or generally recommended by Python. (Where do you get that? From the same
 sources that are so obsessed with DRY they'd rather introduce a
 higher-order-function than repeat one line of code? :-)

Hmm. Not actually sure where I got it from, except [1] that I've heard
it periodically advocated as a way to eliminate race conditions in
multitasking situations and such (in the same way that
stat-followed-by-open is vulnerable, so instead use try-open-except).

 This is probably the most you can get out of me as far as a pronouncement.
 Given that the language summit is coming up I'd be happy to dive deeper in
 my reasons for rejecting it there (if there's demand).

Geography prevents me from being there, but if anyone else asks and
the answer can be written down, I'm probably not the only one who
would read it with interest.

 I do think that (apart from never explaining those dreadful acronyms :-)

Hmm, I thought for some reason they were axiomatic Python, like BDFL
and IDLE. :)

 this was a well-written and well-researched PEP, and I think you've done a
 great job moderating the discussion, collecting objections, reviewing
 alternatives, and everything else that is required to turn a heated debate
 into a PEP. Well done Chris (and everyone who helped), and good luck with
 your next PEP!

Thanks! And yes, thank you to everyone who offered suggestions, kept
the intelligent discussion going (it strayed a bit but never turned
into a flame war), and especially to everyone who helped with wording
and such. I'm only one person, and what seems patently obvious to me
isn't always obvious to someone else.

I have to say this PEP has been highly successful even without being
accepted. The next time anyone asks, they can be pointed to the PEP,
with its list of flawed syntax options. (The most common response, by
far, was Nice idea but I don't like the syntax - for any syntax
proposed.) Plus, it taught me how to use the ast module in research. I
don't know when that'll come in handy, but Sherlock Holmes was right -
all knowledge comes useful!

But I'm not going to devote myself to another PEP *quite* yet. Decimal
literals is in need of a champion, but I need to do other things,
unless someone's going to employ me to champion PEPs full time :)
(Hmm. That would be an interesting job title on the resume.)

ChrisA

[1] Pun intended. Sorry!
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Chris Angelico
On Thu, Mar 13, 2014 at 7:14 AM, Barry Warsaw ba...@python.org wrote:
 Interestingly enough, where ternaries are most useful are in the same
 situations where I think exception expressions would be most useful, in the
 setting of a variable or attribute to one of two different values.  In both
 branches of the conditional, the left hand side is the same target, and what
 differs is the value being assigned to the LHS.

 Looking over exception examples from a large code base, I find it rare (but
 not nonexistent) that exceptions are used in the same situation.  But that
 could be because I'm so comfortable with .get() and other helpers.  Ternary
 expressions seem more compelling.  But there's definitely some overlap, which
 is perhaps why the colon seems so jarring to me.

When you say looking over, do you mean with the Mk 1 Human Eyeball,
or with the script from my research?

https://github.com/Rosuav/ExceptExpr/blob/master/find_except_expr.py

If you've used the script and have some stats to offer, I'd love to
see them. So far, all I have is the stdlib, which isn't necessarily
representative.

Bear in mind, there isn't a .get() for every situation. You can use
hasattr() in place of AttributeError, which isn't quite the same
thing, but most of the OSError-raising APIs don't (as far as I know)
offer a way to return a default instead of raising. So even if you do
generally use dict.get(), there'll likely be some that the script
would catch.

ChrisA
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Emile van Sebille

On 3/12/2014 1:44 PM, Chris Angelico wrote:


unless someone's going to employ me to champion PEPs full time :)
(Hmm. That would be an interesting job title on the resume.)


It's available now -- www.pepboys.com  :)

Emile

___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Tres Seaver
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 03/12/2014 04:49 PM, Chris Angelico wrote:
 You can use hasattr() in place of AttributeError

I use:

 getattr(subject, attrname, default)?

*all the time*.



Tres.
- -- 
===
Tres Seaver  +1 540-429-0999  tsea...@palladion.com
Palladion Software   Excellence by Designhttp://palladion.com
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMg060ACgkQ+gerLs4ltQ70IgCgi2HFt1DRWHaeIlwgjyf1UJiR
1uEAn0+pf2fS+USmesmXtV9O63jA93hq
=fLq7
-END PGP SIGNATURE-

___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-12 Thread Chris Angelico
On Thu, Mar 13, 2014 at 8:37 AM, Tres Seaver tsea...@palladion.com wrote:
 On 03/12/2014 04:49 PM, Chris Angelico wrote:
 You can use hasattr() in place of AttributeError

 I use:

  getattr(subject, attrname, default)?

 *all the time*.

Umm, yeah, that one. Why did I think hasattr was the only way around
that? Anyway, that just means I picked a bad example. There are others
where you have to go for the full try/except.

ChrisA
___
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


[Python-Dev] Requesting pronouncement on PEP 463: Exception-catching expressions

2014-03-11 Thread Chris Angelico
PEP 463, Exception-catching expressions, is stable and I believe ready
for pronouncement. Drumroll please...

http://www.python.org/dev/peps/pep-0463/

PEP: 463
Title: Exception-catching expressions
Version: $Revision$
Last-Modified: $Date$
Author: Chris Angelico ros...@gmail.com
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 15-Feb-2014
Python-Version: 3.5
Post-History: 20-Feb-2014, 16-Feb-2014


Abstract


Just as PEP 308 introduced a means of value-based conditions in an
expression, this system allows exception-based conditions to be used
as part of an expression.


Motivation
==

A number of functions and methods have parameters which will cause
them to return a specified value instead of raising an exception.  The
current system is ad-hoc and inconsistent, and requires that each
function be individually written to have this functionality; not all
support this.

* dict.get(key, default) - second positional argument in place of
  KeyError

* next(iter, default) - second positional argument in place of
  StopIteration

* list.pop() - no way to return a default

* seq[index] - no way to handle a bounds error

* min(sequence, default=default) - keyword argument in place of
  ValueError

* statistics.mean(data) - no way to handle an empty iterator

Had this facility existed early in Python's history, there would have been
no need to create dict.get() and related methods; the one obvious way to
handle an absent key would be to respond to the exception.  One method is
written which signals the absence in one way, and one consistent technique
is used to respond to the absence.  Instead, we have dict.get(), and as of
Python 3.4, we also have min(... default=default), and myriad others.  We
have a LBYL syntax for testing inside an expression, but there is currently
no EAFP notation; compare the following::

# LBYL:
if key in dic:
process(dic[key])
else:
process(None)
# As an expression:
process(dic[key] if key in dic else None)

# EAFP:
try:
process(dic[key])
except KeyError:
process(None)
# As an expression:
process(dic[key] except KeyError: None)

Python generally recommends the EAFP policy, but must then proliferate
utility functions like dic.get(key,None) to enable this.


Rationale
=

The current system requires that a function author predict the need
for a default, and implement support for it.  If this is not done, a
full try/except block is needed.

Since try/except is a statement, it is impossible to catch exceptions
in the middle of an expression.  Just as if/else does for conditionals
and lambda does for function definitions, so does this allow exception
catching in an expression context.

This provides a clean and consistent way for a function to provide a
default: it simply raises an appropriate exception, and the caller
catches it.

With some situations, an LBYL technique can be used (checking if some
sequence has enough length before indexing into it, for instance). This is
not safe in all cases, but as it is often convenient, programmers will be
tempted to sacrifice the safety of EAFP in favour of the notational brevity
of LBYL. Additionally, some LBYL techniques (eg involving getattr with
three arguments) warp the code into looking like literal strings rather
than attribute lookup, which can impact readability. A convenient EAFP
notation solves all of this.

There's no convenient way to write a helper function to do this; the
nearest is something ugly using either lambda::

def except_(expression, exception_list, default):
try:
return expression()
except exception_list:
return default()
value = except_(lambda: 1/x, ZeroDivisionError, lambda: float(nan))

which is clunky, and unable to handle multiple exception clauses; or
eval::

def except_(expression, exception_list, default):
try:
return eval(expression, globals_of_caller(), locals_of_caller())
except exception_list as exc:
l = locals_of_caller().copy()
l['exc'] = exc
return eval(default, globals_of_caller(), l)

def globals_of_caller():
return sys._getframe(2).f_globals

def locals_of_caller():
return sys._getframe(2).f_locals

value = except_(1/x,ZeroDivisionError, Can't divide by zero )

which is even clunkier, and relies on implementation-dependent hacks.
(Writing globals_of_caller() and locals_of_caller() for interpreters
other than CPython is left as an exercise for the reader.)

Raymond Hettinger `expresses`__ a desire for such a consistent
API. Something similar has been `requested`__ `multiple`__ `times`__
in the past.

__ https://mail.python.org/pipermail/python-ideas/2014-February/025443.html
__ https://mail.python.org/pipermail/python-ideas/2013-March/019760.html
__ https://mail.python.org/pipermail/python-ideas/2009-August/005441.html
__