[Python-Dev] Third preview of 3.4.0rc2 is up

2014-02-21 Thread Larry Hastings


We're now up to 66 cherry-picks.  75%+ of those are asyncio changes.

Hopefully I won't have to redo the cherry-picking from scratch again, I 
can just pile more picks on top of the ones I've got.


As before you'll find the results here:

   http://midwinter.com/~larry/3.4.status/



//arry/
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] rpm needs python

2014-02-21 Thread Terry Reedy

On 2/21/2014 2:06 AM, anju Tiwari wrote:


I have two version of python 2.4 and 2.7.
By default python version is 2.4 . I want to install need to install
some rpm
which needs python 2.7 interpreter. how can I enable 2.7 interpreter for
only those
packages which are requiring python 2.7, I don’t want to change my
default python version(2.4).


Ask usage questions like this on python-list or similar user forums. 
pydev is for development *of* python, not *with* python.



--
Terry Jan Reedy


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


[Python-Dev] cherry pick a change to Enum

2014-02-21 Thread Ethan Furman

Greetings, all!

Larry asked me to bring this to PyDev, so here it is.

The issues involved are:

http://bugs.python.org/issue20534  -> already in RC1
http://bugs.python.org/issue20653  -> hoping to get cherry-picked

Background
==
When I put Enum together, my knowledge of pickle and its protocols was dreadfully weak.  As a result, I didn't make the 
best choice in implementing it [1].


Just before RC1 was cut, Serhiy discovered a problem with pickling Enums at protocol four, and with his help I fixed 
that (this is the part that is already in RC1).  This fix consisted primarily of adding a __reduce_ex__ to the Enum 
class, and also checking for all the pickle protocols in a mixed-in type [2], but I left __getnewargs__ in.  Not only 
that, and worse, I wasn't checking to see if the new subclass had its own __getnewargs__ or __reduce_ex__ before I 
invalidated the class for pickling [3].  This means that even though a subclass could have its own __reduce_ex__ to make 
pickling/unpickling possible, it will be ignored.



Problem
===
All the previous changes to disallow something have been for strategic reasons (the usual ones being either consistency, 
or "it doesn't make sense for an enum member/class to behave that way"), but this is effectively disallowing a user to 
specify how their enums should be pickled, and I am unaware of any reason why this should be.



Discussion
==

Is there a valid reason to not allow a user to modify how their enums are 
pickled?

If not, should we put the change in RC2 / Final?  The main reason I'm pushing for this is that Enum is still new, but 
after 3.4.0 is cut we then have to deal with backwards compatibility issues.



Thanks for your time and thoughts.

--
~Ethan~


[1] I chose __getnewargs__, with the result that originally Enum didn't support pickle protocols 0 or 1, and when 4 was 
added later it had trouble with some types of Enum subclasses (tuples, to be exact).


[2] Those protocol methods being __reduce__, __reduce_ex__, __getnewargs__, and 
__getnewargs_ex__.

[3] This logic error has been there from the beginning, it did not sneak in in 
the last patch before RC1.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Third preview of 3.4.0rc2 is up

2014-02-21 Thread Ned Deily
In article <[email protected]>,
 Larry Hastings  wrote:
> As before you'll find the results here:
> 
> http://midwinter.com/~larry/3.4.status/

Status says that: 

eef7899ea7ab Doc: do not rely on checked-out Sphinx toolchain from 
svn.python.org anymore

is unmerged, which is what Georg and I agreed upon in Issue20661.  Yet, 
in the current python.3.4.2014.02.21.00.07.42.tgz tarball, that change 
appears to be present and, as such, causes installer builds to fail.

-- 
 Ned Deily,
 [email protected]

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


Re: [Python-Dev] Python 3.4: Cherry-picking into rc2 and final

2014-02-21 Thread Andreas Röhler

Am 20.02.2014 02:24, schrieb Stephen J. Turnbull:
[ ... ]

Sure, but it *doesn't* help in knowing which ones are *correctly*
addressed.  These *are* ambitious changes; some of the remaining bugs
may be very deep.  The obvious fixes may do more harm than good.  Ie,
"more eyes" is (a) mostly a fallacy (as Heinlein put it, the wisdom of
a group is less than or equal to the maximum of the wisdom of the
members) and (b) in any case the "more eyes" effect is diluted if
people are deliberately looking at different parts of the code.



All depends from the way, a group is organized, composed etc.
What might stiffle results in a group for example is hierarchy, resp. a fear to 
get chastised by the leader.

After all I'm not in position to make a guess here - but rather would expect 
much higher results by groups-coop than from most gifted single person among.


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


Re: [Python-Dev] Third preview of 3.4.0rc2 is up

2014-02-21 Thread Larry Hastings

On 02/21/2014 01:30 AM, Ned Deily wrote:

In article <[email protected]>,
  Larry Hastings  wrote:

As before you'll find the results here:

 http://midwinter.com/~larry/3.4.status/

Status says that:

eef7899ea7ab Doc: do not rely on checked-out Sphinx toolchain from
svn.python.org anymore

is unmerged, which is what Georg and I agreed upon in Issue20661.  Yet,
in the current python.3.4.2014.02.21.00.07.42.tgz tarball, that change
appears to be present and, as such, causes installer builds to fail.



Whoopsie!  My local branch is actually correct.  But!  I effectively did 
this in my automation:


   % hg clone 3.4 python-{time}
   % cd python-{time}
   % rm -rf .hg* .bzr* .git*
   % cd ..
   % tar cvfz python-{time}.tgz python-{time}

Can you spot the error?  That's right: when you clone, the clone always 
starts out in "default".  So all the tarballs I've published so far have 
been wrong.  ARGH.  Sorry!


I've added a "hg branch 3.4" in a judicious spot in my automation. The 
resulting tarball doesn't have the sphinx toolchain change.


Look for a new tarball in a few minutes, once "make test" finishes,


//arry/
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] cherry pick a change to Enum

2014-02-21 Thread Antoine Pitrou
On Fri, 21 Feb 2014 00:36:09 -0800
Ethan Furman  wrote:
> 
> Discussion
> ==
> 
> Is there a valid reason to not allow a user to modify how their enums are 
> pickled?
> 
> If not, should we put the change in RC2 / Final?  The main reason I'm pushing 
> for this is that Enum is still new, but 
> after 3.4.0 is cut we then have to deal with backwards compatibility issues.

I think this should be cherry-picked.
(but see my comment on the issue)

Regards

Antoine.


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


Re: [Python-Dev] Third preview of 3.4.0rc2 is up

2014-02-21 Thread Arfrever Frehtes Taifersar Arahesis
2014-02-21 11:06 Larry Hastings napisał(a):
> On 02/21/2014 01:30 AM, Ned Deily wrote:
> > In article <[email protected]>,
> >   Larry Hastings  wrote:
> >> As before you'll find the results here:
> >>
> >>  http://midwinter.com/~larry/3.4.status/
> > Status says that:
> >
> > eef7899ea7ab Doc: do not rely on checked-out Sphinx toolchain from
> > svn.python.org anymore
> >
> > is unmerged, which is what Georg and I agreed upon in Issue20661.  Yet,
> > in the current python.3.4.2014.02.21.00.07.42.tgz tarball, that change
> > appears to be present and, as such, causes installer builds to fail.
> >
> 
> Whoopsie!  My local branch is actually correct.  But!  I effectively did 
> this in my automation:
> 
> % hg clone 3.4 python-{time}
> % cd python-{time}
> % rm -rf .hg* .bzr* .git*
> % cd ..
> % tar cvfz python-{time}.tgz python-{time}
> 
> Can you spot the error?  That's right: when you clone, the clone always 
> starts out in "default".  So all the tarballs I've published so far have 
> been wrong.  ARGH.  Sorry!
> 
> I've added a "hg branch 3.4" in a judicious spot in my automation.

You can use 'hg clone -u 3.4 3.4 python-{time}'.

$ hg clone --help
...
To check out a particular version, use -u/--update, or -U/--noupdate to
create a clone with no working directory.
...
 -u --updaterev REV revision, tag or branch to check out


--
Arfrever Frehtes Taifersar Arahesis


signature.asc
Description: This is a digitally signed message part.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Third preview of 3.4.0rc2 is up

2014-02-21 Thread Antoine Pitrou
On Fri, 21 Feb 2014 02:06:07 -0800
Larry Hastings  wrote:
> 
> Whoopsie!  My local branch is actually correct.  But!  I effectively did 
> this in my automation:
> 
> % hg clone 3.4 python-{time}
> % cd python-{time}
> % rm -rf .hg* .bzr* .git*
> % cd ..
> % tar cvfz python-{time}.tgz python-{time}

You could use "hg archive".

Regards

Antoine.


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


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

2014-02-21 Thread Nick Coghlan
On 21 February 2014 13:15, Chris Angelico  wrote:
> PEP: 463
> Title: Exception-catching expressions
> Version: $Revision$
> Last-Modified: $Date$
> Author: Chris Angelico 
> Status: Draft
> Type: Standards Track
> Content-Type: text/x-rst
> Created: 15-Feb-2014
> Python-Version: 3.5
> Post-History: 16-Feb-2014, 21-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.

Great work on this Chris - this is one of the best researched and
justified Python syntax proposals I've seen :)

> Open Issues
> ===
>
> Parentheses around the entire expression
> 
>
> Generator expressions require parentheses, unless they would be
> strictly redundant.  Ambiguities with except expressions could be
> resolved in the same way, forcing nested except-in-except trees to be
> correctly parenthesized and requiring that the outer expression be
> clearly delineated.  `Steven D'Aprano elaborates on the issue.`__
>
> __ https://mail.python.org/pipermail/python-ideas/2014-February/025647.html

I'd like to make the case that the PEP should adopt this as its
default position. My rationale is mainly that if we start by requiring
the parentheses, it's pretty straightforward to take that requirement
away in specific cases later, as well as making it easier to introduce
multiple except clauses if that ever seems necessary.

However, if we start without the required parentheses, that's it - we
can't introduce a requirement for parentheses later if we decide the
bare form is too confusing in too many contexts, and there's plenty of
potential for such confusion.

In addition to the odd interactions with other uses of the colon as a
marker in the syntax, including suite headers, lambdas and function
annotations, omitting the parentheses makes it harder to decide which
behaviour was intended in ambiguous cases, while the explicit
parentheses would force the writer to be clear which one they meant.
Consider:

x = get_value() except NotFound: foo is not None

There are two plausible interpretations of that:

x = (get_value() except NotFound: foo) is not None
x = get_value() except NotFound: (foo is not None)

With the proposed precedence in the PEP (which I agree with), the
latter is the correct interpretation, but that's not at all obvious to
the reader - they would have to "just know" that's the way it works.
By contrast, if the parentheses are required, then the spelling would
have to be one of the following to be legal:

x = (get_value() except NotFound: foo is not None)
x = (get_value() except NotFound: foo) is not None

Which means the ":" and the closing ")" nicely bracket the fallback
value in both cases and make the author's intent relatively clear.

The required parentheses also help in the cases where there is a
nearby colon with a different meaning:

   if check() except Exception: False:
...
   if (check() except Exception: False):
...

   lambda x: calculate(x) except Exception: None
   lambda x: (calculate(x) except Exception: None)

   def f(a: "OS dependent" = os_defaults[os.name] except KeyError: None): pass
   def f(a: "OS dependent" = (os_defaults[os.name] except KeyError: None)): pass

Rather than making people consider "do I need the parentheses in this
case or not?", adopting the genexp rule makes it simple: yes, you need
them, because the compiler will complain if you leave them out.

> Retrieving a message from either a cache or the internet, with auth
> check::
>
> logging.info("Message shown to user: %s",((cache[k]
> except LookupError:
> (backend.read(k) except OSError: 'Resource not available')
> )
> if check_permission(k) else 'Access denied'
> ) except BaseException: "This is like a bare except clause")

I don't think taking it all the way to one expression shows the new
construct in the best light. Keeping this as multiple statements
assigning to a temporary variable improves the readability quite a
bit:

if not check_permission(k):
msg = 'Access denied'
else:
msg = (cache[k] except LookupError: None)
if msg is None:
msg = (backend.read(k) except OSError: 'Resource not available')

logging.info("Message shown to user: %s", msg)

I would also move the "bare except clause" equivalent out to a
separate example. Remember, you're trying to convince people to *like*
the PEP, not scare them away with the consequences of what happens
when people try to jam too much application logic into a single
statement. While we're admittedly giving people another tool to help
them win obfuscated Python contests, we don't have to *encourage* them
:)

> try:
> if check_permission(k):
> try:
> _ = cache[k]
> except LookupError:
> try:
>   

Re: [Python-Dev] cherry pick a change to Enum

2014-02-21 Thread Nick Coghlan
On 21 February 2014 20:29, Antoine Pitrou  wrote:
> On Fri, 21 Feb 2014 00:36:09 -0800
> Ethan Furman  wrote:
>>
>> Discussion
>> ==
>>
>> Is there a valid reason to not allow a user to modify how their enums are 
>> pickled?
>>
>> If not, should we put the change in RC2 / Final?  The main reason I'm 
>> pushing for this is that Enum is still new, but
>> after 3.4.0 is cut we then have to deal with backwards compatibility issues.
>
> I think this should be cherry-picked.
> (but see my comment on the issue)

That course of action makes sense to me, too. While we ideally want to
catch design bugs during beta, the fact is that we sometime won't
notice them until the release candidate phase, and it makes sense to
fix them before the final release.

However, it also makes sense to discuss the corner cases here before
deciding how to proceed, and if we uncover any more after rc2, such a
change would probably be a trigger for a 3rd release candidate
(although that would ultimately be Larry's call as release manager).

Cheers,
Nick.

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


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

2014-02-21 Thread Paul Moore
On 21 February 2014 11:35, Nick Coghlan  wrote:
>> 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.
>
> Great work on this Chris - this is one of the best researched and
> justified Python syntax proposals I've seen :)

Agreed - given the number of differing opinions on python-ideas, it's
particularly impressive how well the debate was conducted too.

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


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

2014-02-21 Thread Chris Angelico
On Fri, Feb 21, 2014 at 10:35 PM, Nick Coghlan  wrote:
> On 21 February 2014 13:15, Chris Angelico  wrote:
>> PEP: 463
>> Title: Exception-catching expressions
> Great work on this Chris - this is one of the best researched and
> justified Python syntax proposals I've seen :)

It is? Wow... I'm not sure what that says about other syntax
proposals. This is one week's python-ideas discussion plus one little
script doing analysis on the standard library. Hardly PhD level
research :)

>> Parentheses around the entire expression
>> 
>>
>> Generator expressions require parentheses, unless they would be
>> strictly redundant.  Ambiguities with except expressions could be
>> resolved in the same way, forcing nested except-in-except trees to be
>> correctly parenthesized and requiring that the outer expression be
>> clearly delineated.  `Steven D'Aprano elaborates on the issue.`__
>>
>> __ https://mail.python.org/pipermail/python-ideas/2014-February/025647.html
>
> I'd like to make the case that the PEP should adopt this as its
> default position. My rationale is mainly that if we start by requiring
> the parentheses, it's pretty straightforward to take that requirement
> away in specific cases later, as well as making it easier to introduce
> multiple except clauses if that ever seems necessary.
>
> However, if we start without the required parentheses, that's it - we
> can't introduce a requirement for parentheses later if we decide the
> bare form is too confusing in too many contexts, and there's plenty of
> potential for such confusion.

If once the parens are made mandatory, they'll most likely stay
mandatory forever - I can't imagine there being any strong impetus to
change the language to make them optional.

> The required parentheses also help in the cases where there is a
> nearby colon with a different meaning:
>
>if check() except Exception: False:
> ...
>if (check() except Exception: False):

People can already write:

if (x if y else z):

without the parens, and it works. Readability suffers when the same
keyword is used twice (here "if" rather than the colon, but same
difference), yet the parens are considered optional. Python is a
language that, by and large, lacks syntactic salt; style guides are
free to stipulate more, but the language doesn't make demands. I would
strongly *recommend* using parens in all the cases you've shown,
especially lambda:

>lambda x: calculate(x) except Exception: None
>lambda x: (calculate(x) except Exception: None)

as it would otherwise depend on operator precedence; but mandating
them feels to me like demanding readability.

>def f(a: "OS dependent" = os_defaults[os.name] except KeyError: None): pass
>def f(a: "OS dependent" = (os_defaults[os.name] except KeyError: None)): 
> pass

Ehh, that one's a mess. I'd be looking at breaking out the default:

default = os_defaults[os.name] except KeyError: None
def f(a: "OS dependent" = default): pass

with possibly some better name than 'default'. The one-liner is almost
80 characters long without indentation and with very short names. But
if it's okay to wrap it, that would work without the parens:

def f(
a: "OS dependent" = os_defaults[os.name] except KeyError: None,
another_arg .,
more, args ..,
):
pass

Clarity is maintained by judicious placement of newlines just as much
as by parentheses.

> Rather than making people consider "do I need the parentheses in this
> case or not?", adopting the genexp rule makes it simple: yes, you need
> them, because the compiler will complain if you leave them out.

Yes, that is a reasonable line of argument. On the other hand, there's
no demand for parens when you mix and and or:

x or y and z

I'd wager more than half of Python programmers would be unable to say
for sure which would be evaluated first. The compiler could have been
written to reject this (by placing and and or at the same precedence
and having no associativity - I'm not sure if the current lexer in
CPython can do that, but it's certainly not conceptually
inconceivable), but a decision was made to make this legal.

>> Retrieving a message from either a cache or the internet, with auth
>> check::
>>
>> logging.info("Message shown to user: %s",((cache[k]
>> except LookupError:
>> (backend.read(k) except OSError: 'Resource not available')
>> )
>> if check_permission(k) else 'Access denied'
>> ) except BaseException: "This is like a bare except clause")
>
> I don't think taking it all the way to one expression shows the new
> construct in the best light. Keeping this as multiple statements
> assigning to a temporary variable improves the readability quite a
> bit:

Yeah, good point. I tried to strike a balance between simple and
complex examples, but it's hard to judge.

> I would also move the "bare except clause" equivalent out to a
> separate example. Remember, you're trying to co

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

2014-02-21 Thread Chris Angelico
On Fri, Feb 21, 2014 at 11:37 PM, Paul Moore  wrote:
> On 21 February 2014 11:35, Nick Coghlan  wrote:
>>> 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.
>>
>> Great work on this Chris - this is one of the best researched and
>> justified Python syntax proposals I've seen :)
>
> Agreed - given the number of differing opinions on python-ideas, it's
> particularly impressive how well the debate was conducted too.

On that subject, I'd like to thank everyone involved in the
python-ideas discussion, and particularly Steven D'Aprano, Rob Cliffe,
and Andrew Barnert; it was an amazingly productive thread, getting to
nearly four hundred emails before seriously meandering. And even then,
it mostly just started looping back on itself, which isn't surprising
given that it was so long - anyone not majorly invested in the topic
won't have read every single post.

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


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

2014-02-21 Thread Nick Coghlan
On 21 February 2014 22:42, Chris Angelico  wrote:
> It'd be a backward-incompatible change, but it's more likely to be
> what people expect. The general assumption of "with ... as ..." is
> that the thing should be used inside the block, and should be finished
> with when you exit the block, so having the name valid only inside the
> block does make sense.
>
> That's a completely separate proposal. But suppose that were to
> happen, and to not require a closure. It would then make good sense to
> be able to capture an exception inside an expression - and it could be
> done without breaking anything.
>
> So, if it is to be rejected, I'd say it's on the technical grounds
> that it would require a closure in CPython, and that a closure is
> incompatible with the current proposal. Does that sound right?
>
> (It's also not a huge loss, since it's almost unused. But it's an
> incompatibility between statement and expression form.)

It's probably OK to leave it in the deferred section and just note the
difficulty of implementing it in a backwards compatible way, since
we're *not* going to be introducing a closure. Python 3 except clauses
are already a bit weird anyway, since they do an implicit delete at
the end, but only if the except clause is actually triggered:


>>> e = "Hello"
>>> try:
... 1/0
... except ZeroDivisionError as e:
... pass
...
>>> e
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'e' is not defined
>>> e = "Hello"
>>> try:
... pass
... except Exception as e:
... pass
...
>>> e
'Hello'

Cheers,
Nick.

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


Re: [Python-Dev] Third preview of 3.4.0rc2 is up

2014-02-21 Thread Ned Deily
In article <[email protected]>,
 Larry Hastings  wrote:
> Whoopsie!  My local branch is actually correct.  But!  I effectively did 
> this in my automation:
> 
> % hg clone 3.4 python-{time}
> % cd python-{time}
> % rm -rf .hg* .bzr* .git*
> % cd ..
> % tar cvfz python-{time}.tgz python-{time}
> 
> Can you spot the error?  That's right: when you clone, the clone always 
> starts out in "default".  So all the tarballs I've published so far have 
> been wrong.  ARGH.  Sorry!
> 
> I've added a "hg branch 3.4" in a judicious spot in my automation. The 
> resulting tarball doesn't have the sphinx toolchain change.
> 
> Look for a new tarball in a few minutes, once "make test" finishes,

Much better - thanks!

-- 
 Ned Deily,
 [email protected]

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


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

2014-02-21 Thread Nick Coghlan
On 21 February 2014 22:42, Chris Angelico  wrote:
> On Fri, Feb 21, 2014 at 10:35 PM, Nick Coghlan  wrote:
>> On 21 February 2014 13:15, Chris Angelico  wrote:
>>> PEP: 463
>>> Title: Exception-catching expressions
>> Great work on this Chris - this is one of the best researched and
>> justified Python syntax proposals I've seen :)
>
> It is? Wow... I'm not sure what that says about other syntax
> proposals. This is one week's python-ideas discussion plus one little
> script doing analysis on the standard library. Hardly PhD level
> research :)

Right, it just takes someone willing to put in the time to actually
put a concrete proposal together, read all the discussions, attempt to
summarise them into a coherent form and go looking for specific
examples to help make their case.

I think a large part of my pleased reaction is the fact that several
of the python-ideas regulars (including me) have a habit of responding
to new syntax proposals with a list of things to do to make a good PEP
(especially Raymond's "search the stdlib for code that would be
improved" criterion), and it's quite a novelty to have someone take
that advice and put together a compelling argument - the more typical
reaction is for the poster to decide that a PEP sounds like too much
work and drop the idea (or else to realise that they can't actually
provide the compelling use cases requested).

As you have discovered, creating a PEP really isn't that arduous, so
long as you have enough spare time to keep up with the discussions,
and there actually are compelling examples of possible improvements
readily available :)

Cheers,
Nick.

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


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

2014-02-21 Thread Antoine Pitrou
On Fri, 21 Feb 2014 14:15:59 +1100
Chris Angelico  wrote:
> 
> 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.

While I sympathize with the motivation, I really don't like the end
result:

> lst = [1, 2]
> value = lst[2] except IndexError: "No value"

is too much of a break from the usual stylistic conventions, and looks
like several statements were stuffed on a single line.

In other words, the gain in concision is counterbalanced by a loss in
readability, a compromise which doesn't fit in Python's overall design
principles.

(compare with "with", which solves actual readability issues due to the
distance between the "try" and the "finally" clause, and also promotes
better resource management)

So -0.5 from me.

Regards

Antoine.


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


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

2014-02-21 Thread Nick Coghlan
On 21 February 2014 22:42, Chris Angelico  wrote:
> People can already write:
>
> if (x if y else z):
>
> without the parens, and it works. Readability suffers when the same
> keyword is used twice (here "if" rather than the colon, but same
> difference), yet the parens are considered optional. Python is a
> language that, by and large, lacks syntactic salt; style guides are
> free to stipulate more, but the language doesn't make demands. I would
> strongly *recommend* using parens in all the cases you've shown,
> especially lambda:
>
>>lambda x: calculate(x) except Exception: None
>>lambda x: (calculate(x) except Exception: None)
>
> as it would otherwise depend on operator precedence; but mandating
> them feels to me like demanding readability.

Right, that's why my main motivation for this suggestion is the one
relating to keeping future options open. If the parentheses are
optional, than adding multiple except clauses latter isn't possible,
since this would already be valid, but mean something different:

expr except Exception1: default1 except Exception2: default2

The deferral currently has this snippet:

"""In order to ensure compatibility with future versions, ensure that
any consecutive except operators are parenthesized to guarantee the
interpretation you expect."""

That's not a reasonable expectation - either the parentheses have to
be mandatory as part of the deferral, or else multiple except clause
support needs to be listed as rejected rather than deferred.

Cheers,
Nick.

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


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

2014-02-21 Thread Rob Cliffe

My 2 cents worth:


On 21/02/2014 12:42, Chris Angelico wrote:

On Fri, Feb 21, 2014 at 10:35 PM, Nick Coghlan  wrote:

Great work on this Chris - this is one of the best researched and
justified Python syntax proposals I've seen :)

Hear, hear!  ("Praise from the praiseworthy is praise indeed" - Tolkien.)

Small point: in one of your examples you give a plug for the PEP "note 
the DRY improvement".

I would suggest that similarly
perhaps in your Lib/tarfile.py:2198 example you point out the 
increase in readability due to the 2 lines lining up
in your Lib/ipaddress.py:343 example you point out that the new 
form is probably an improvement (i.e. probably closer to the author's 
intention) as it will NOT catch an AttributeError evaluating 
"ips.append" (this would matter e.g. if "append" were mis-spelt).  YOU 
are clearly aware of this but it would often escape the casual reader.

Retrieving a message from either a cache or the internet, with auth
check::

 logging.info("Message shown to user: %s",((cache[k]
 except LookupError:
 (backend.read(k) except OSError: 'Resource not available')
 )
 if check_permission(k) else 'Access denied'
 ) except BaseException: "This is like a bare except clause")

I don't think taking it all the way to one expression shows the new
construct in the best light. Keeping this as multiple statements
assigning to a temporary variable improves the readability quite a
bit:
I agree, it looks scary (too many branches in one statement).  The 
shorter the example, the more convincing.

Yeah, good point. I tried to strike a balance between simple and
complex examples, but it's hard to judge.



Capturing the exception object
--

An examination of the Python standard library shows that, while the use
of 'as' is fairly common (occurring in roughly one except clause in five),
it is extremely *uncommon* in the cases which could logically be converted
into the expression form.  Its few uses can simply be left unchanged.
Consequently, in the interests of simplicity, the 'as' clause is not
included in this proposal.  A subsequent Python version can add this without
breaking any existing code, as 'as' is already a keyword.

We can't defer this one - if we don't implement it now, we should
reject it as a future addition. The reason we can't defer it is
[ chomped for brevity ]

So I think it makes more sense to reject this subproposal outright -
it makes the change more complex and make the handling of the common
case worse, for the sake of something that will almost never be an
appropriate thing to do.

Thanks for looking into this Nick.
I confess I don't entirely understand the technical argument (my 
understanding breaks down at "the subexpressions can't see the class 
level variables", but I don't want to waste anybody's time expecting an 
explanation, I can always look into it myself) but I accept that there 
is a good reason for disallowing 'as' and its usage would be rare, so I 
will (slightly regretfully) wave it goodbye.





So, if it is to be rejected, I'd say it's on the technical grounds
that it would require a closure in CPython, and that a closure is
incompatible with the current proposal. Does that sound right?

It does to me FWIW.


(It's also not a huge loss, since it's almost unused. But it's an
incompatibility between statement and expression form.)

ChrisA
Assuming the PEP is accepted (not a trivial assumption!)  I hope that at 
some stage allowing multiple except clauses (to trap different 
exceptions raised by the original expression) will be reinstated.  But I 
have to accept that it would be rarely used.


To my mind the real unsung hero of this story is the existing "try ... 
except ... finally" syntax and its flexibility.  In my code base there 
were a few hundred of these, but just over a dozen where the new syntax 
would be appropriate.  (Hope I'm not starting to argue against the PEP!)

Rob Cliffe

___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/rob.cliffe%40btinternet.com


-
No virus found in this message.
Checked by AVG - www.avg.com
Version: 2012.0.2247 / Virus Database: 3705/6611 - Release Date: 02/20/14




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


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

2014-02-21 Thread Nick Coghlan
On 22 February 2014 00:03, Eli Bendersky  wrote:
> On Thu, Feb 20, 2014 at 7:15 PM, Chris Angelico  wrote:
>>
>> PEP: 463
>> Title: Exception-catching expressions
>> Version: $Revision$
>> Last-Modified: $Date$
>> Author: Chris Angelico 
>> Status: Draft
>> Type: Standards Track
>> Content-Type: text/x-rst
>> Created: 15-Feb-2014
>> Python-Version: 3.5
>> Post-History: 16-Feb-2014, 21-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.
>
>
>
> Chris, while I also commend you for the comprehensive PEP, I'm -1 on the
> proposal, for two main reasons:
>
> 1. Many proposals suggest new syntax to gain some succinctness. Each has to
> be judged for its own merits, and in this case IMHO the cons eclipse the
> pros. I don't think this will save a lot of code in a typical
> well-structured program - maybe a few lines out of hundreds. On the other
> hand, it adds yet another syntax to remember and understand, which is not
> the Pythonic way.
>
> 2. Worse, this idea subverts exceptions to control flow, which is not only
> un-Pythonic but also against the accepted practices of programming in
> general. Here, the comparison to PEP 308 is misguided. PEP 308, whatever
> syntax it adds, still remains within the domain of normal control flow. PEP
> 463, OTOH, makes it deliberately easy to make exceptions part of
> non-exceptional code, encouraging very bad programming practices.

Neither of these objections addresses the problems with the status quo, though:

- the status quo encourages overbroad exception handling (as
illustrated by examples in the PEP)
- the status quo encourages an ad hoc approach to hiding exception
handling inside functions

PEP 308 was accepted primarily because the and/or hack was a bug
magnet. The status quo for exception handling is both a bug magnet
(due to overbroad exception handlers), and a cause of creeping
complexity in API design (as more and more APIs, both in the standard
library and elsewhere, acquire ways to request implicit exception
handling).

That's why the comparison to PEP 308 is appropriate: it's less about
making the language better directly, and more about deciding the
consequences of not having it are no longer acceptable.

Cheers,
Nick.

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


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

2014-02-21 Thread Brett Cannon
On Fri, Feb 21, 2014 at 8:52 AM, Antoine Pitrou  wrote:

> On Fri, 21 Feb 2014 14:15:59 +1100
> Chris Angelico  wrote:
> >
> > 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.
>
> While I sympathize with the motivation, I really don't like the end
> result:
>
> > lst = [1, 2]
> > value = lst[2] except IndexError: "No value"
>
> is too much of a break from the usual stylistic conventions, and looks
> like several statements were stuffed on a single line.
>
> In other words, the gain in concision is counterbalanced by a loss in
> readability, a compromise which doesn't fit in Python's overall design
> principles.
>
> (compare with "with", which solves actual readability issues due to the
> distance between the "try" and the "finally" clause, and also promotes
> better resource management)
>

While I like the general concept, I agree that it looks too much like a
crunched statement; the use of the colon is a non-starter for me. I'm sure
I'm not the only one whose brain has been trained to view a colon in Python
to mean "statement", period. This goes against that syntactic practice and
just doesn't work for me.

I'm -1 with the current syntax, but it can go into the + range if a better
syntax can be chosen.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eli Bendersky
On Fri, Feb 21, 2014 at 6:28 AM, Nick Coghlan  wrote:

> On 22 February 2014 00:03, Eli Bendersky  wrote:
> > On Thu, Feb 20, 2014 at 7:15 PM, Chris Angelico 
> wrote:
> >>
> >> PEP: 463
> >> Title: Exception-catching expressions
> >> Version: $Revision$
> >> Last-Modified: $Date$
> >> Author: Chris Angelico 
> >> Status: Draft
> >> Type: Standards Track
> >> Content-Type: text/x-rst
> >> Created: 15-Feb-2014
> >> Python-Version: 3.5
> >> Post-History: 16-Feb-2014, 21-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.
> >
> >
> >
> > Chris, while I also commend you for the comprehensive PEP, I'm -1 on the
> > proposal, for two main reasons:
> >
> > 1. Many proposals suggest new syntax to gain some succinctness. Each has
> to
> > be judged for its own merits, and in this case IMHO the cons eclipse the
> > pros. I don't think this will save a lot of code in a typical
> > well-structured program - maybe a few lines out of hundreds. On the other
> > hand, it adds yet another syntax to remember and understand, which is not
> > the Pythonic way.
> >
> > 2. Worse, this idea subverts exceptions to control flow, which is not
> only
> > un-Pythonic but also against the accepted practices of programming in
> > general. Here, the comparison to PEP 308 is misguided. PEP 308, whatever
> > syntax it adds, still remains within the domain of normal control flow.
> PEP
> > 463, OTOH, makes it deliberately easy to make exceptions part of
> > non-exceptional code, encouraging very bad programming practices.
>
> Neither of these objections addresses the problems with the status quo,
> though:
>
> - the status quo encourages overbroad exception handling (as
> illustrated by examples in the PEP)
> - the status quo encourages an ad hoc approach to hiding exception
> handling inside functions
>

I think the PEP, and your reply, focuses too much on one single "status
quo" situation, which is the dict.get-like usage. However, the PEP does not
propose a narrow solution - it proposes a significant change in the way
expressions may be written and exceptions may be caught, and thus opens a
can of worms. Even if the status quo will be made better by it, and even
this I'm not sure about (*), many many other possibilities of bad code open
up.

(*) IMHO it's better to hide these exceptions inside well defined functions
-- because dict.get tells me it's the normal code flow, not the exceptional
code flow. On the other hand, the syntax proposed herein tells me - yeah
it's the exceptional code flow, but let me merge it into the normal code
flow for you.

This goes against anything I understand about how exceptions should and
should not be used.

Eli




>
> PEP 308 was accepted primarily because the and/or hack was a bug
> magnet. The status quo for exception handling is both a bug magnet
> (due to overbroad exception handlers), and a cause of creeping
> complexity in API design (as more and more APIs, both in the standard
> library and elsewhere, acquire ways to request implicit exception
> handling).
>
> That's why the comparison to PEP 308 is appropriate: it's less about
> making the language better directly, and more about deciding the
> consequences of not having it are no longer acceptable.
>
>
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


[Python-Dev] Tangent on class level scoping rules (was Re: PEP 463: Exception-catching expressions)

2014-02-21 Thread Nick Coghlan
On 22 February 2014 00:22, Rob Cliffe  wrote:
> Thanks for looking into this Nick.
> I confess I don't entirely understand the technical argument (my
> understanding breaks down at "the subexpressions can't see the class level
> variables", but I don't want to waste anybody's time expecting an
> explanation, I can always look into it myself)

It's a relatively arcane scoping rule that only matters if you have
non-trivial logic at class scope. The vast majority of Python
programmers will never have to care, because they do the typical thing
and their class bodies consist almost entirely of function definitions
and relatively simple assignment statements. However, it's something
that expression level name binding proposals need to take into account
if they want to avoid side effects on the containing scope.

Python's scoping rules are deliberately designed so that methods
*can't* see class attributes directly, they have to access them via
their first argument or the magic __class__ variable (Py3 only for the
latter). For example:

>>> class C:
... attr = "Hello"
... def m(self):
... print(self.attr)
... print(attr)
...
>>> C().m()
Hello
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in m
NameError: global name 'attr' is not defined

The trick that makes it relevant here is that the "hidden" iteration
variable in comprehensions is implemented by creating an implicit
closure and then calling it. From the point of view of the scoping
rules, that implicit closure behaves the same way as any other method
definition, so most of the subexpressions can't see the class
variables. The sole exception is the outermost iterator expression,
because that is evaluated in the containing scope and then passed to
the closure as an argument (this is all based on the way generator
expressions work, and those *have* to be a closure, because they need
to run in their own completely independent frame).

As Chris later noted, you likely *could* still implement expression
local name binding for an except expression without a full closure, it
would just be rather difficult.

Cheers,
Nick.

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


Re: [Python-Dev] cherry pick a change to Enum

2014-02-21 Thread Barry Warsaw
On Feb 21, 2014, at 12:36 AM, Ethan Furman wrote:

>If not, should we put the change in RC2 / Final?  The main reason I'm pushing
>for this is that Enum is still new, but after 3.4.0 is cut we then have to
>deal with backwards compatibility issues.

I concur this should be cherry picked.  Let's not hobble this API for all
eternity  if it can be fixed before the release.

Thanks for working so hard to make enums great in Python 3.4.

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


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

2014-02-21 Thread Nick Coghlan
On 22 February 2014 00:37, Eli Bendersky  wrote:
> This goes against anything I understand about how exceptions should and
> should not be used.

I think you're thinking of a language that isn't Python - we use
exceptions for control flow all over the place (it's how hasattr() is
*defined*, for example).

Cheers,
Nick.

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


Re: [Python-Dev] Tangent on class level scoping rules (was Re: PEP 463: Exception-catching expressions)

2014-02-21 Thread Nick Coghlan
Sorry folks, that was meant to go to python-ideas, not python-dev.
I've been so used to the PEP 463 threads being on python-ideas, I
missed that this was the python-dev one :)

Cheers,
Nick.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eli Bendersky
On Fri, Feb 21, 2014 at 6:46 AM, Nick Coghlan  wrote:

> On 22 February 2014 00:37, Eli Bendersky  wrote:
> > This goes against anything I understand about how exceptions should and
> > should not be used.
>
> I think you're thinking of a language that isn't Python - we use
> exceptions for control flow all over the place (it's how hasattr() is
> *defined*, for example).
>

No, it is Python I'm thinking about. As I mentioned in the reply to Brett's
message, I see a difference between allowing exceptions on expression level
and statement level. The latter is less likely to be abused. Once you add
exceptions into expressions, all bets are off.

For instance, it is sometime non-trivial to know which exceptions some
function may throw. When you write a try...raise statement, you think hard
about covering all the bases. In an expression you're unlikely to, which
opens up a lot of possibilities for bugs. Again, please stop focusing just
on the list[index] case -- the proposal adds a new significant feature to
the language that can (and thus will) be used in a variety of scenarios.

Eli
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Antoine Pitrou
On Sat, 22 Feb 2014 00:28:01 +1000
Nick Coghlan  wrote:
> 
> Neither of these objections addresses the problems with the status quo, 
> though:
> 
> - the status quo encourages overbroad exception handling (as
> illustrated by examples in the PEP)

I don't get this. Using the proper exception class in a "try...except"
suite is no more bothersome than using the proper exception class in
this newly-proposed construct.

Regards

Antoine.


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


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

2014-02-21 Thread Nick Coghlan
On 22 February 2014 00:44, Eli Bendersky  wrote:
> True, but at least you still have to explicitly try...except... which takes
> a toll on the code so isn't taken lightly. Adding except into expressions, I
> fear, will proliferate this usage much more.

The same fears were raised regarding conditional expressions, and
they'll be dealt with the same way: style guides and code review.

That's also why the examples part of the PEP is so important, though:
this is about providing a tool to *improve* readability in the cases
where it applies, without significantly increasing the cognitive
burden of the language.

One example not mentioned in the PEP is that "text.find(substr)" would
become just a shorthand for "text.index(substr) except ValueError:
-1", but the latter has the benefit that you can substitute "None"
instead, which avoids the trap where "-1" is a valid subscript for the
string (but doesn't give you the answer you want).

Cheers,
Nick.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 12:53 AM, Nick Coghlan  wrote:
> On 21 February 2014 22:42, Chris Angelico  wrote:
>> People can already write:
>>
>> if (x if y else z):
>>
>> without the parens, and it works. Readability suffers when the same
>> keyword is used twice (here "if" rather than the colon, but same
>> difference), yet the parens are considered optional. Python is a
>> language that, by and large, lacks syntactic salt; style guides are
>> free to stipulate more, but the language doesn't make demands. I would
>> strongly *recommend* using parens in all the cases you've shown,
>> especially lambda:
>>
>>>lambda x: calculate(x) except Exception: None
>>>lambda x: (calculate(x) except Exception: None)
>>
>> as it would otherwise depend on operator precedence; but mandating
>> them feels to me like demanding readability.
>
> Right, that's why my main motivation for this suggestion is the one
> relating to keeping future options open. If the parentheses are
> optional, than adding multiple except clauses latter isn't possible,
> since this would already be valid, but mean something different:
>
> expr except Exception1: default1 except Exception2: default2
>
> The deferral currently has this snippet:
>
> """In order to ensure compatibility with future versions, ensure that
> any consecutive except operators are parenthesized to guarantee the
> interpretation you expect."""
>
> That's not a reasonable expectation - either the parentheses have to
> be mandatory as part of the deferral, or else multiple except clause
> support needs to be listed as rejected rather than deferred.

I've spent the better part of the last hour debating this in my head.
It's basically a question of simplicity versus future flexibility:
either keep the syntax clean and deny the multiple-except-clause
option, or mandate the parens and permit it. The first option has, in
my own head, the stronger case - this is designed for simplicity, and
it wouldn't be that big a deal to completely reject multiple except
clauses and simply require that the
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 1:59 AM, Chris Angelico  wrote:
> I've spent the better part of the last hour debating this in my head.
> It's basically a question of simplicity versus future flexibility:
> either keep the syntax clean and deny the multiple-except-clause
> option, or mandate the parens and permit it. The first option has, in
> my own head, the stronger case - this is designed for simplicity, and
> it wouldn't be that big a deal to completely reject multiple except
> clauses and simply require that the

Oops, hit the wrong key and sent that half-written.

... and simply require that the statement form be used. But the
whelming opinion of python-dev seems to be in favour of the parens
anyway, and since they give us the possibility of future expansion
effectively for free, I've gone that way. Parens are now required; the
syntax is:

value = (expr except Exception: default)

and, as per genexp rules, redundant parens can be omitted:

print(lst[i] except IndexError: "Out of bounds")

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


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

2014-02-21 Thread Nick Coghlan
On 22 February 2014 00:59, Chris Angelico  wrote:
> On Sat, Feb 22, 2014 at 12:53 AM, Nick Coghlan  wrote:
>> The deferral currently has this snippet:
>>
>> """In order to ensure compatibility with future versions, ensure that
>> any consecutive except operators are parenthesized to guarantee the
>> interpretation you expect."""
>>
>> That's not a reasonable expectation - either the parentheses have to
>> be mandatory as part of the deferral, or else multiple except clause
>> support needs to be listed as rejected rather than deferred.
>
> I've spent the better part of the last hour debating this in my head.
> It's basically a question of simplicity versus future flexibility:
> either keep the syntax clean and deny the multiple-except-clause
> option, or mandate the parens and permit it. The first option has, in
> my own head, the stronger case - this is designed for simplicity, and
> it wouldn't be that big a deal to completely reject multiple except
> clauses and simply require that the

Yep, moving multiple exceptions to the "Rejected subproposals" section
would work for me.

Cheers,
Nick.

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


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

2014-02-21 Thread Nick Coghlan
On 22 February 2014 00:50, Antoine Pitrou  wrote:
> On Sat, 22 Feb 2014 00:28:01 +1000
> Nick Coghlan  wrote:
>>
>> Neither of these objections addresses the problems with the status quo, 
>> though:
>>
>> - the status quo encourages overbroad exception handling (as
>> illustrated by examples in the PEP)
>
> I don't get this. Using the proper exception class in a "try...except"
> suite is no more bothersome than using the proper exception class in
> this newly-proposed construct.

Not overbroad in the sense of catching too many different kinds of
exception, overbroad in the sense of covering too much code in the try
block.

Cheers,
Nick.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 1:50 AM, Antoine Pitrou  wrote:
> On Sat, 22 Feb 2014 00:28:01 +1000
> Nick Coghlan  wrote:
>>
>> Neither of these objections addresses the problems with the status quo, 
>> though:
>>
>> - the status quo encourages overbroad exception handling (as
>> illustrated by examples in the PEP)
>
> I don't get this. Using the proper exception class in a "try...except"
> suite is no more bothersome than using the proper exception class in
> this newly-proposed construct.

Overbroad exception handling comes in two ways. One is simply catching
Exception or BaseException when a narrower class would be better, and
that's not addressed by this PEP (except insofar as it does not have a
bare "except:" syntax, and so it forces you to at least be explicit
about catching BaseException). The other is this:

try:
f(x[i])
except IndexError:
f(default)

Translating that into this form:

f(x[i] except IndexError: default)

means that an IndexError thrown inside f() will not be caught. While
it is, of course, possible to write that currently:

try:
arg = x[i]
except IndexError:
arg = default
f(arg)

it's that much less readable, and as evidenced by several examples in
the standard library (some of which are in the PEP, and a few more can
be found in my associated collection [1]), it's common to short-cut
this. By providing a clean and convenient syntax for catching an
exception in just one small expression, we encourage the narrowing of
the catch front.

ChrisA

[1] https://github.com/Rosuav/ExceptExpr/blob/master/examples.py
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Brett Cannon
On Fri, Feb 21, 2014 at 9:49 AM, Eli Bendersky  wrote:

> On Fri, Feb 21, 2014 at 6:46 AM, Nick Coghlan  wrote:
>
>> On 22 February 2014 00:37, Eli Bendersky  wrote:
>> > This goes against anything I understand about how exceptions should and
>> > should not be used.
>>
>> I think you're thinking of a language that isn't Python - we use
>> exceptions for control flow all over the place (it's how hasattr() is
>> *defined*, for example).
>>
>
> No, it is Python I'm thinking about. As I mentioned in the reply to
> Brett's message, I see a difference between allowing exceptions on
> expression level and statement level. The latter is less likely to be
> abused. Once you add exceptions into expressions, all bets are off.
>
> For instance, it is sometime non-trivial to know which exceptions some
> function may throw. When you write a try...raise statement, you think hard
> about covering all the bases. In an expression you're unlikely to, which
> opens up a lot of possibilities for bugs. Again, please stop focusing just
> on the list[index] case -- the proposal adds a new significant feature to
> the language that can (and thus will) be used in a variety of scenarios.
>

I understand you are arguing that a try expression will lead to people just
doing `something() except Exception: None` or whatever and that people will
simply get lazy and not think about what they are doing with their
exceptions. Unfortunately they already are; that shipped sailed when we
didn't eliminate bare except clauses in Python 3 (hopefully we can change
that in Python 4).

I personally don't think that making people type out a try statement is
going to lead to that much thought compared to an expression. I'm willing
to bet most IDEs have a code snippet for creating a try statement so people
are already not using the extra typing of a full-blown statement with at
least two clauses as a way to stop and think about what they are doing.

I'm totally fine restricting this proposal to not having any concept of
exception catching or finally clause: it just replaces the simplest
try/except clause possible (while requiring an exception be specified).
That takes care of the common control flow use case of exceptions while
requiring more thought for more complex cases.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 1:03 AM, Eli Bendersky  wrote:
> Chris, while I also commend you for the comprehensive PEP, I'm -1 on the
> proposal, for two main reasons:
>
> 1. Many proposals suggest new syntax to gain some succinctness. Each has to
> be judged for its own merits, and in this case IMHO the cons eclipse the
> pros. I don't think this will save a lot of code in a typical
> well-structured program - maybe a few lines out of hundreds. On the other
> hand, it adds yet another syntax to remember and understand, which is not
> the Pythonic way.

It doesn't need to save a huge number of lines. Just like lambda and
the if/else expression, it's there as a tool - if it makes your code
easier to read, it's a good too, and if it makes it harder, then don't
use it. Yes, it's more to learn, but so is the proliferation of ad-hoc
alternatives, several of which are listed in the 'Motivation' section
at the top.

> 2. Worse, this idea subverts exceptions to control flow, which is not only
> un-Pythonic but also against the accepted practices of programming in
> general. Here, the comparison to PEP 308 is misguided. PEP 308, whatever
> syntax it adds, still remains within the domain of normal control flow. PEP
> 463, OTOH, makes it deliberately easy to make exceptions part of
> non-exceptional code, encouraging very bad programming practices.

Again, I point to the current alternatives, including:

* dict[key] -> dict.get(key, default)

* min(sequence) -> min(sequence, default=default), as of 3.4

Both offer a way to either get an exception back or use a (usually
constant) default value. In each case, the author of the
class/function had to cater to the fact that some callers might want
it to not raise an exception. The alternative is to always use the
full try/except block, which leads to questions like "How can I keep
going after an exception?" with code like this:

try:
spam = d["spam"]
ham = d["ham"]
eggs = d["eggs"]
sausage = d["sausage"]
except KeyError:
thing_that_failed = ""

The dict class offers a way to avoid the exception here, by showing
that it's non-exceptional:

spam = d.get("spam","")
ham = d.get("ham","")
eggs = d.get("eggs","")
sausage = d.get("sausage","")

But not everything does. Writing that with just exception handling
looks like this:

try:
spam = d["spam"]
except KeyError:
span = ""
try:
ham = d["ham"]
except KeyError:
ham = ""
try:
eggs = d["eggs"]
except KeyError:
eggs = ""
try:
sausage = d["sausage"]
except KeyError:
sausage = ""

with extreme likelihood of an error - do you see what I got wrong
there? With inline exception handling, d could be a custom class that
simply defines [...] to raise KeyError on unknowns, and the code can
be written thus:

spam = d["spam"] except KeyError: ""
ham = d["ham"] except KeyError: ""
eggs = d["eggs"] except KeyError: ""
sausage = d["sausage"] except KeyError: ""

It's still a bit repetitive, but that's hard to avoid. And it puts the
exception handling at the exact point where it stops being exceptional
and starts being normal - exactly as the try/except statement should.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 1:22 AM, Rob Cliffe  wrote:
> Small point: in one of your examples you give a plug for the PEP "note the
> DRY improvement".
> I would suggest that similarly
> perhaps in your Lib/tarfile.py:2198 example you point out the increase
> in readability due to the 2 lines lining up
> in your Lib/ipaddress.py:343 example you point out that the new form is
> probably an improvement (i.e. probably closer to the author's intention) as
> it will NOT catch an AttributeError evaluating "ips.append" (this would
> matter e.g. if "append" were mis-spelt).  YOU are clearly aware of this but
> it would often escape the casual reader.

Sure. Added a paragraph down the bottom of the section explaining the
benefit of the narrowed scope.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 1:34 AM, Brett Cannon  wrote:
> While I like the general concept, I agree that it looks too much like a
> crunched statement; the use of the colon is a non-starter for me. I'm sure
> I'm not the only one whose brain has been trained to view a colon in Python
> to mean "statement", period. This goes against that syntactic practice and
> just doesn't work for me.
>
> I'm -1 with the current syntax, but it can go into the + range if a better
> syntax can be chosen.

We bikeshedded that extensively on -ideas. The four best options are:

value = (expr except Exception: default)
value = (expr except Exception -> default)
value = (expr except Exception pass default)
value = (expr except Exception then default)

Note that the last option involves the creation of a new keyword.

Would any of the others feel better to you?

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 2:19 AM, Brett Cannon  wrote:
> I understand you are arguing that a try expression will lead to people just
> doing `something() except Exception: None` or whatever and that people will
> simply get lazy and not think about what they are doing with their
> exceptions. Unfortunately they already are; that shipped sailed when we
> didn't eliminate bare except clauses in Python 3 (hopefully we can change
> that in Python 4).

That's already come up a few times. I wrote a script to try to find
potential conversion targets, and technically it's correct to show
this up:

Doc/tools/rstlint.py:73:
try:
compile(code, fn, 'exec')
except SyntaxError as err:
yield err.lineno, 'not compilable: %s' % err

Yes, technically you could treat that as an expression. Well, okay.
Current version of the proposal doesn't include 'as', so you can't do
that. Let's grab the next one.

Lib/asyncio/events.py:40:
try:
self._callback(*self._args)
except Exception:
logger.exception('Exception in callback %s %r',
 self._callback, self._args)

That could, per PEP 463, become:
(self._callback(*self._args) except Exception:
logger.exception('Exception in callback %s %r',
 self._callback, self._args))

But that would be abuse of the syntax. It's just like converting this:

for s in list_of_strings:
print(s)

into an expression:

[print(s) for s in list_of_strings]
list(map(print,list_of_strings))

Neither of them is a good way to write code, yet that's not the fault
of either map() or the list comp.

> I'm totally fine restricting this proposal to not having any concept of
> exception catching or finally clause: it just replaces the simplest
> try/except clause possible (while requiring an exception be specified). That
> takes care of the common control flow use case of exceptions while requiring
> more thought for more complex cases.

The finally clause was never in the proposal. I added it as an open
issue early on, just to see if it gathered any interest, but the
weight of opinion agreed with my initial feeling: it's utterly useless
to the exception syntax. Same goes for an else clause. Currently, the
two complexities not possible in the expression form are capturing the
exception with 'as' (for technical reasons) and stringing multiple
except clauses on (for complexity reasons). In the standard library,
counting up all the cases that could plausibly be converted to
expression form, very very few use either feature. So this is a case
of "do just the really simple option and catch 98.5% of the actual
usage".

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


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

2014-02-21 Thread Antoine Pitrou
On Sat, 22 Feb 2014 02:12:04 +1100
Chris Angelico  wrote:
> 
> Overbroad exception handling comes in two ways. One is simply catching
> Exception or BaseException when a narrower class would be better, and
> that's not addressed by this PEP (except insofar as it does not have a
> bare "except:" syntax, and so it forces you to at least be explicit
> about catching BaseException). The other is this:
> 
> try:
> f(x[i])
> except IndexError:
> f(default)
> 
> Translating that into this form:
> 
> f(x[i] except IndexError: default)
> 
> means that an IndexError thrown inside f() will not be caught.

Thank you and Nick for the explanation. This is a good point.
I'm still put off by the syntax, though, just like Brett.

Regards

Antoine.


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


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

2014-02-21 Thread Eric Snow
[re: "as" clause]
On Fri, Feb 21, 2014 at 6:20 AM, Nick Coghlan  wrote:
> It's probably OK to leave it in the deferred section and just note the
> difficulty of implementing it in a backwards compatible way, since
> we're *not* going to be introducing a closure.

Agreed.

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 8:12 AM, Chris Angelico  wrote:
> On Sat, Feb 22, 2014 at 1:50 AM, Antoine Pitrou  wrote:
>> On Sat, 22 Feb 2014 00:28:01 +1000
>> Nick Coghlan  wrote:
>>>
>>> Neither of these objections addresses the problems with the status quo, 
>>> though:
>>>
>>> - the status quo encourages overbroad exception handling (as
>>> illustrated by examples in the PEP)
>>
>> I don't get this. Using the proper exception class in a "try...except"
>> suite is no more bothersome than using the proper exception class in
>> this newly-proposed construct.
>
> Overbroad exception handling comes in two ways. One is simply catching
> Exception or BaseException when a narrower class would be better, and
> that's not addressed by this PEP (except insofar as it does not have a
> bare "except:" syntax, and so it forces you to at least be explicit
> about catching BaseException). The other is this:
>
> try:
> f(x[i])
> except IndexError:
> f(default)
>
> Translating that into this form:
>
> f(x[i] except IndexError: default)
>
> means that an IndexError thrown inside f() will not be caught. While
> it is, of course, possible to write that currently:
>
> try:
> arg = x[i]
> except IndexError:
> arg = default
> f(arg)
>
> it's that much less readable, and as evidenced by several examples in
> the standard library (some of which are in the PEP, and a few more can
> be found in my associated collection [1]), it's common to short-cut
> this. By providing a clean and convenient syntax for catching an
> exception in just one small expression, we encourage the narrowing of
> the catch front.

Be sure to capture in the PEP (within reason) a summary of concerns
and rebuttals/acquiescence.  Eli's, Brett's, and Antoine's concerns
likely reflect what others are thinking as well.  The PEP and its
result will be better for recording such matters.  In fact, that's a
key goal of PEPs. :)

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 8:19 AM, Brett Cannon  wrote:
> I understand you are arguing that a try expression will lead to people just
> doing `something() except Exception: None` or whatever and that people will
> simply get lazy and not think about what they are doing with their
> exceptions.

Exactly.

> Unfortunately they already are; that shipped sailed when we
> didn't eliminate bare except clauses in Python 3 (hopefully we can change
> that in Python 4).

We should have a page somewhere tracking a py4k "wishlist". :)

>
> I personally don't think that making people type out a try statement is
> going to lead to that much thought compared to an expression. I'm willing to
> bet most IDEs have a code snippet for creating a try statement so people are
> already not using the extra typing of a full-blown statement with at least
> two clauses as a way to stop and think about what they are doing.
>
> I'm totally fine restricting this proposal to not having any concept of
> exception catching or finally clause: it just replaces the simplest
> try/except clause possible (while requiring an exception be specified). That
> takes care of the common control flow use case of exceptions while requiring
> more thought for more complex cases.

+1

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 8:27 AM, Chris Angelico  wrote:
> It doesn't need to save a huge number of lines. Just like lambda and
> the if/else expression, it's there as a tool - if it makes your code
> easier to read, it's a good too, and if it makes it harder, then don't
> use it.

And as long as the tool/syntax is obviously linked to an existing one
(and does not change semantics), people really won't need to learn
anything new.  So it wouldn't be adding much to the keep-it-in-my-head
size of the language.

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


[Python-Dev] Summary of Python tracker Issues

2014-02-21 Thread Python tracker

ACTIVITY SUMMARY (2014-02-14 - 2014-02-21)
Python tracker at http://bugs.python.org/

To view or respond to any of the issues listed below, click on the issue.
Do NOT respond to this message.

Issues counts and deltas:
  open4558 (+34)
  closed 27937 (+62)
  total  32495 (+96)

Open issues with patches: 2059 


Issues opened (60)
==

#10510: distutils upload/register should use CRLF in HTTP requests
http://bugs.python.org/issue10510  reopened by eric.araujo

#20628: csv.DictReader
http://bugs.python.org/issue20628  opened by rogererens

#20629: Python ctypes BigEndianStructure bitfield assignment misbehavi
http://bugs.python.org/issue20629  opened by Alan.Ning

#20630: Add sorting helpers for collections containing None values
http://bugs.python.org/issue20630  opened by ncoghlan

#20631: python readline module crashing on NULL access
http://bugs.python.org/issue20631  opened by tfiala

#20632: Define a new __key__ protocol
http://bugs.python.org/issue20632  opened by ncoghlan

#20633: SystemError: Parent module 'multiprocessing' not loaded, canno
http://bugs.python.org/issue20633  opened by Amr.Ali

#20635: Fix the grid geometry manager and add tests for geometry manag
http://bugs.python.org/issue20635  opened by serhiy.storchaka

#20636: Better repr for tkinter widgets
http://bugs.python.org/issue20636  opened by serhiy.storchaka

#20637: Support key-sharing dictionaries in subclasses
http://bugs.python.org/issue20637  opened by pingebretson

#20639: pathlib.PurePath.with_suffix() does not allow removing the suf
http://bugs.python.org/issue20639  opened by july

#20640: Adds idle test for configHelpSourceEdit
http://bugs.python.org/issue20640  opened by sahutd

#20641: Python installer needs elevated rights to install pip
http://bugs.python.org/issue20641  opened by poke

#20642: Enhance deepcopy-ing for tuples
http://bugs.python.org/issue20642  opened by Claudiu.Popa

#20643: Strange dot in documentation (after generator.close)
http://bugs.python.org/issue20643  opened by rutsky

#20644: OS X installer build broken by changes to documentation build
http://bugs.python.org/issue20644  opened by ned.deily

#20646: 3.4 cherry-pick: 180e4b678003 select and kqueue round the time
http://bugs.python.org/issue20646  opened by haypo

#20648: 3.4 cherry-pick: multiple changesets for asyncio
http://bugs.python.org/issue20648  opened by haypo

#20650: asyncio.BaseEventLoop.run_in_executor docs have awkward wordin
http://bugs.python.org/issue20650  opened by brett.cannon

#20653: Pickle enums by name
http://bugs.python.org/issue20653  opened by serhiy.storchaka

#20657: OpenBSD: Merge patches
http://bugs.python.org/issue20657  opened by haypo

#20658: os.environ.clear() fails with empty keys (posix.unsetenv)
http://bugs.python.org/issue20658  opened by blueyed

#20659: Want to make a class method a property by combining decorators
http://bugs.python.org/issue20659  opened by the.mulhern

#20660: Starting a second multiprocessing.Manager causes INCREF on all
http://bugs.python.org/issue20660  opened by mythsmith

#20662: Pydoc doesn't escape parameter defaults in html
http://bugs.python.org/issue20662  opened by serhiy.storchaka

#20663: Introduce exception argument to iter
http://bugs.python.org/issue20663  opened by cool-RR

#20664: _findLib_crle and _get_soname broken on latest SunOS 5.11
http://bugs.python.org/issue20664  opened by rygorde4

#20668: Remove dependency on tests.txt when running test_asyncio suite
http://bugs.python.org/issue20668  opened by vajrasky

#20669: OpenBSD: socket.recvmsg tests fail with OSError: [Errno 40] Me
http://bugs.python.org/issue20669  opened by haypo

#20671: test_create_at_shutdown_with_encoding() of test_io hangs on "S
http://bugs.python.org/issue20671  opened by haypo

#20674: Update comments in dictobject.c
http://bugs.python.org/issue20674  opened by rhettinger

#20677: Minor typo in enum docs
http://bugs.python.org/issue20677  opened by flashk

#20678: re does not allow back references in {} matching operator
http://bugs.python.org/issue20678  opened by hardkrash

#20679: 3.4 cherry-pick: 587fd4b91120  improve Enum subclass behavior
http://bugs.python.org/issue20679  opened by ethan.furman

#20680: Pickle socket enums by names
http://bugs.python.org/issue20680  opened by serhiy.storchaka

#20683: [doc] Ease comprehension of section 9.2 of docs for Python 2 a
http://bugs.python.org/issue20683  opened by krichter

#20686: Confusing statement
http://bugs.python.org/issue20686  opened by Daniel.U..Thibault

#20687: Change in expectedFailure breaks testtools
http://bugs.python.org/issue20687  opened by barry

#20689: socket.AddressFamily is absent in html pydoc
http://bugs.python.org/issue20689  opened by serhiy.storchaka

#20690: IDLE Indents convert to spaces and then throws error
http://bugs.python.org/issue20690  opened by Justin.Barker

#20691: inspect.signature: Consider exposing 'follow_wrapper_chains' o
http://bugs.python.org/issue20691  opened by ys

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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 3:46 AM, Eric Snow  wrote:
> Be sure to capture in the PEP (within reason) a summary of concerns
> and rebuttals/acquiescence.  Eli's, Brett's, and Antoine's concerns
> likely reflect what others are thinking as well.  The PEP and its
> result will be better for recording such matters.  In fact, that's a
> key goal of PEPs. :)

I now have a paragraph summarizing the "narrowing of scope" benefit,
though not worded as a rebuttal of a concern. Eli's concern is mainly
that this can be abused, which everything can; should I include
something about that? Brett's issue is with the colon. I'll write up a
paragraph or two of reasoning as to why that was selected, possibly
tomorrow, but the main reason is simply that nobody came up with a
compelling argument in favour of any other. Hardly the most epic tale
:)

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


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

2014-02-21 Thread Antoine Pitrou
On Sat, 22 Feb 2014 02:52:59 +1100
Chris Angelico  wrote:

> On Sat, Feb 22, 2014 at 1:34 AM, Brett Cannon  wrote:
> > While I like the general concept, I agree that it looks too much like a
> > crunched statement; the use of the colon is a non-starter for me. I'm sure
> > I'm not the only one whose brain has been trained to view a colon in Python
> > to mean "statement", period. This goes against that syntactic practice and
> > just doesn't work for me.
> >
> > I'm -1 with the current syntax, but it can go into the + range if a better
> > syntax can be chosen.
> 
> We bikeshedded that extensively on -ideas. The four best options are:
> 
> value = (expr except Exception: default)

-0.5

> value = (expr except Exception -> default)

-0.5

> value = (expr except Exception pass default)

-1 (looks terribly weird)

> value = (expr except Exception then default)

+0.5
But I'm aware it requires reserving "then" as a keyword, which might
need a prior SyntaxWarning.

Regards

Antoine.


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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 4:32 AM, Antoine Pitrou  wrote:
>> value = (expr except Exception then default)
>
> +0.5
> But I'm aware it requires reserving "then" as a keyword, which might
> need a prior SyntaxWarning.

There are no instances of "then" used as a name in the Python stdlib,
I already checked. If anyone has a good-sized codebase to check,
you're welcome to use the same analysis script - it's an AST
parser/walker, so it finds actual use as a name, not in a comment or a
string or anything.

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

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


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

2014-02-21 Thread Guido van Rossum
On Fri, Feb 21, 2014 at 9:32 AM, Antoine Pitrou  wrote:

> On Sat, 22 Feb 2014 02:52:59 +1100
> Chris Angelico  wrote:
>
> > On Sat, Feb 22, 2014 at 1:34 AM, Brett Cannon  wrote:
> > > While I like the general concept, I agree that it looks too much like a
> > > crunched statement; the use of the colon is a non-starter for me. I'm
> sure
> > > I'm not the only one whose brain has been trained to view a colon in
> Python
> > > to mean "statement", period. This goes against that syntactic practice
> and
> > > just doesn't work for me.
> > >
> > > I'm -1 with the current syntax, but it can go into the + range if a
> better
> > > syntax can be chosen.
> >
> > We bikeshedded that extensively on -ideas. The four best options are:
> >
> > value = (expr except Exception: default)
>
> -0.5
>
> > value = (expr except Exception -> default)
>
> -0.5
>
> > value = (expr except Exception pass default)
>
> -1 (looks terribly weird)
>
> > value = (expr except Exception then default)
>
> +0.5
> But I'm aware it requires reserving "then" as a keyword, which might
> need a prior SyntaxWarning.
>

I'm put off by the ':' syntax myself (it looks to me as if someone forgot a
newline somewhere) but 'then' feels even weirder (it's been hard-coded in
my brain as meaning the first branch of an 'if').

I am going to sleep on this.

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


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

2014-02-21 Thread Ethan Furman

On 02/20/2014 07:15 PM, Chris Angelico wrote:

PEP: 463
Title: Exception-catching expressions

[snip]

Deferred sub-proposals
==

Multiple except clauses
---

An examination of use-cases shows that this is not needed as often as
it would be with the statement form, and as its syntax is a point on
which consensus has not been reached, the entire feature is deferred.

In order to ensure compatibility with future versions, ensure that any
consecutive except operators are parenthesized to guarantee the
interpretation you expect.

Multiple 'except' keywords can be used, and they will all catch
exceptions raised in the original expression (only)::

 # Will catch any of the listed exceptions thrown by expr;
 # any exception thrown by a default expression will propagate.
 value = (expr
 except Exception1 [as e]: default1
 except Exception2 [as e]: default2
 # ... except ExceptionN [as e]: defaultN
 )


-1

If one wants to catch multiple exceptions from the same original operation, use the statement block.  Keep the exception 
expression syntax simple and chained, akin to the if..else syntax:


value = expr1 except exc1 expr2 except exc2 expr3 ...

So each following except is only catching exceptions from the last expression (in other words, exc1 only from expr1, 
exc2 only from expr2, etc.)  Keep it simple.  If one wants the power of the statement form, use the statement syntax.


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


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

2014-02-21 Thread Yury Selivanov

Thank you for writing this PEP, Chris. I'm impressed by the
quality of this PEP, and how you handled the discussion on
python-ideas.

I initially liked this idea, however, after reading the PEP
in detail, my vote is: -1 on the current syntax; -1 on the
whole idea.

On 2/20/2014, 10:15 PM, Chris Angelico wrote:

[snip]
* 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

We can fix that in 3.5.

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

We can add 'list.get(index, default)' method, similar to
'Mapping.get'. It's far more easier than introducing new
syntax.


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

* sum(sequence, start=default) - slightly different but can do the
   same job

'sum' is not a very frequently used builtin.

I think the Motivation section is pretty weak.

Inconvenience of dict[] raising KeyError was solved by
introducing the dict.get() method. And I think that

dct.get('a', 'b')

is 1000 times better than

dct['a'] except KeyError: 'b'

I don't want to see this (or any other syntax) used by
anyone.

I also searched how many 'except IndexError' are in
the standard library code.  Around 60.  That's a rather
low number, that can justify adding 'list.get' but not
advocate a new syntax.

Moreover, I think that explicit handling of IndexError is
rather ugly and error prone, using len() is usually
reads better.


[snip]

Consider this example of a two-level cache::
 for key in sequence:
 x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))
 # do something with x


I'm sorry, it took me a minute to understand what your
example is doing.  I would rather see two try..except blocks
than this.



Retrieve an argument, defaulting to None::
 cond = args[1] except IndexError: None

 # Lib/pdb.py:803:
 try:
 cond = args[1]
 except IndexError:
 cond = None


cond = None if (len(args) < 2) else args[1]


Attempt a translation, falling back on the original::
 e.widget = self._nametowidget(W) except KeyError: W

 # Lib/tkinter/__init__.py:1222:
 try:
 e.widget = self._nametowidget(W)
 except KeyError:
 e.widget = W

I'm not sure this is a good example either.
I presume '_nametowidget' is some function,
that might raise a KeyError because of a bug in
its implementation, or to signify that there is
no widget 'W'. Your new syntax just helps to work
with this error prone api.



Read from an iterator, continuing with blank lines once it's
exhausted::
 line = readline() except StopIteration: ''

 # Lib/lib2to3/pgen2/tokenize.py:370:
 try:
 line = readline()
 except StopIteration:
 line = ''

Handling StopIteration exception is more common in standard
library than IndexError (although not much more), but again,
not all of that code is suitable for your syntax. I'd say
about 30%, which is about 20-30 spots (correct me if I'm
wrong).



Retrieve platform-specific information (note the DRY improvement);
this particular example could be taken further, turning a series of
separate assignments into a single large dict initialization::
 # sys.abiflags may not be defined on all platforms.
 _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: ''

 # Lib/sysconfig.py:529:
 try:
 _CONFIG_VARS['abiflags'] = sys.abiflags
 except AttributeError:
 # sys.abiflags may not be defined on all platforms.
 _CONFIG_VARS['abiflags'] = ''

Ugly.
_CONFIG_VARS['abiflags'] = getattr(sys, 'abiflags', '')
Much more readable.


Retrieve an indexed item, defaulting to None (similar to dict.get)::
 def getNamedItem(self, name):
 return self._attrs[name] except KeyError: None

 # Lib/xml/dom/minidom.py:573:
 def getNamedItem(self, name):
 try:
 return self._attrs[name]
 except KeyError:
 return None

_attrs there is a dict (or at least it's something that quaks
like a dict, and has [] and keys()), so

return self._attrs.get(name)


Translate numbers to names, falling back on the numbers::
 g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid
 u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: tarinfo.uid

 # Lib/tarfile.py:2198:
 try:
 g = grp.getgrnam(tarinfo.gname)[2]
 except KeyError:
 g = tarinfo.gid
 try:
 u = pwd.getpwnam(tarinfo.uname)[2]
 except KeyError:
 u = tarinfo.uid

This one is a valid example, but totally unparseable by
humans. Moreover, it promotes a bad pattern, as you
mask KeyErrors in 'grp.getgrnam(tarinfo.gname)' call.



Perform some lengt

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

2014-02-21 Thread Tim Delaney
On 22 February 2014 02:03, Chris Angelico  wrote:

> Oops, hit the wrong key and sent that half-written.
>
> ... and simply require that the statement form be used. But the
> whelming opinion of python-dev seems to be in favour of the parens
> anyway, and since they give us the possibility of future expansion
> effectively for free, I've gone that way. Parens are now required; the
> syntax is:
>
> value = (expr except Exception: default)
>

Let me add my congratulations on a fine PEP.

I think it's much more readable with the parens (doesn't look as much like
there's a missing newline). I'd also strongly argue for permanently
disallowing multiple exceptions - as you said, this is intended to be a
simple, readable syntax.

Even with the parens, I share the bad gut feeling others are having with
the colon in the syntax. I also don't think "then" is a good fit (even if
it didn't add a keyword).

Unfortunately, I can't come up with anything better ...

Tim Delaney
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Tangent on class level scoping rules (was Re: PEP 463: Exception-catching expressions)

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 7:42 AM, Nick Coghlan  wrote:
> It's a relatively arcane scoping rule that only matters if you have
> non-trivial logic at class scope. The vast majority of Python
> programmers will never have to care, because they do the typical thing
> and their class bodies consist almost entirely of function definitions
> and relatively simple assignment statements.

That is definitely an esoteric corner.  It's only really bitten me
when I was doing stuff with nested classes [1] and mined too deeply.
Here's a simple example:

class Spam:
class Ham:
A = None
B = None
class Eggs:
class Bacon(Ham):
 A = 3

If I recall correctly, Larry Hastings ran into something similar a while back.

-eric


[1] The nested classes were used just for easy-to-read namespaces,
effectively hijacking the class definition syntax with no intention of
actually using the class as a type.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Greg Ewing

Nick Coghlan wrote:

On 21 February 2014 13:15, Chris Angelico  wrote:


Generator expressions require parentheses, unless they would be
strictly redundant.  Ambiguities with except expressions could be
resolved in the same way, forcing nested except-in-except trees to be
correctly parenthesized 


I'd like to make the case that the PEP should adopt this as its
default position.


I generally agree, but I'd like to point out that this
doesn't necessarily mean making the parenthesizing rules as
strict as they are for generator expressions.

The starting point for genexps is that the parens are part of
the syntax, the same way that square brackets are part of
the syntax of a list comprehension; we only allow them to
be omitted in very special circumstances.

On the other hand, I don't think there's any harm in allowing
an except expression to stand on its own when there is no
risk of ambiguity, e.g.

   foo = things[i] except IndexError: None

should be allowed, just as we allow

   x = a if b else c

and don't require

   x = (a if b else c)

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eric V. Smith


On 2/21/2014 5:06 PM, Greg Ewing wrote:
> Nick Coghlan wrote:
>> On 21 February 2014 13:15, Chris Angelico  wrote:
>>
>>> Generator expressions require parentheses, unless they would be
>>> strictly redundant.  Ambiguities with except expressions could be
>>> resolved in the same way, forcing nested except-in-except trees to be
>>> correctly parenthesized 
>>
>> I'd like to make the case that the PEP should adopt this as its
>> default position.
> 
> I generally agree, but I'd like to point out that this
> doesn't necessarily mean making the parenthesizing rules as
> strict as they are for generator expressions.
> 
> The starting point for genexps is that the parens are part of
> the syntax, the same way that square brackets are part of
> the syntax of a list comprehension; we only allow them to
> be omitted in very special circumstances.
> 
> On the other hand, I don't think there's any harm in allowing
> an except expression to stand on its own when there is no
> risk of ambiguity, e.g.
> 
>foo = things[i] except IndexError: None

I agree that it would be a shame to disallow this simple usage. I'd like
to leave this like any other expression: add parens if they add clarity
or if they are required for the precedence you'd prefer. Personally, I'd
probably always use parens unless it was a simple assignment (as above),
or an argument to a function call. But I think it's a style issue.

Eric.

> should be allowed, just as we allow
> 
>x = a if b else c
> 
> and don't require
> 
>x = (a if b else c)
> 
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Greg Ewing

Antoine Pitrou wrote:


   lst = [1, 2]
   value = lst[2] except IndexError: "No value"


the gain in concision is counterbalanced by a loss in
readability,


This version might be more readable:

   value = lst[2] except "No value" if IndexError

since it puts the normal and exceptional values next
to each other, and relegates the exception type (which
is of much less interest) to a trailing aside.

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Ethan Furman

On 02/21/2014 02:26 PM, Eric V. Smith wrote:

On 2/21/2014 5:06 PM, Greg Ewing wrote:

On 21 February 2014 13:15, Chris Angelico wrote:


Generator expressions require parentheses, unless they would be
strictly redundant.  Ambiguities with except expressions could be
resolved in the same way, forcing nested except-in-except trees to be
correctly parenthesized


There would be no ambiguity if only nested excepts are allowed.  If one wants to catch multiple exceptions from one 
expression, /and do something different for each one/, use the statement form as it's going to be clearer.  For example:


   try:
   value = 1/x
   except ZeroDivisionError:
   try:
   value = 1/default['denominator']
   except KeyError:
   value = NaN

is much cleaner as:

   value = 1/x except ZeroDivisionError: 1/default['denominator'] except 
KeyError: NaN

However, this:

   try:
  result = Parse(some_stuff)
   except MissingOperator:
  result = ...
   except InvalidOperand:
  result = ...
   except SomethingElse:
  result = ...

would not benefit from being condensed into a single expression

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


Re: [Python-Dev] Tangent on class level scoping rules (was Re: PEP 463: Exception-catching expressions)

2014-02-21 Thread Greg Ewing

Nick Coghlan wrote:

As Chris later noted, you likely *could* still implement expression
local name binding for an except expression without a full closure, it
would just be rather difficult.


I'm still not convinced it would be all *that* difficult.
Seems to me it would be semantically equivalent to
renaming the inner variable and adding a finally clause
to unbind it. Is there something I'm missing?

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Greg Ewing

Eli Bendersky wrote:
For instance, it is sometime non-trivial to know which exceptions some 
function may throw. When you write a try...raise statement, you think 
hard about covering all the bases. In an expression you're unlikely to,


Speak for yourself. I don't think I would put any less
thought into which exception I caught with an except
expression as I would for an except statement.

In fact, an except expression may even make it easier
to catch exceptions in an appropriately targeted way.
For example, a pattern frequently encountered is:

   result = computation(int(arg))

and you want to guard against arg not being a
well-formed int. It's tempting to do this:

   try:
  result = computation(int(arg))
   except ValueError:
  abort("Invalid int")

But that's bad, because the try clause encompasses
too much. Doing it properly requires splitting up the
expression:

   try:
  i = int(arg)
   except:
  abort("Invalid int")
   else:
  result = computation(i)

With an except expression, it could be written:

   result = computation(int(arg)
  except ValueError: abort("Invalid int"))

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Ethan Furman

On 02/21/2014 03:29 PM, Greg Ewing wrote:

Antoine Pitrou wrote:


   lst = [1, 2]
   value = lst[2] except IndexError: "No value"


the gain in concision is counterbalanced by a loss in
readability,


This version might be more readable:

value = lst[2] except "No value" if IndexError


It does read nicely, and is fine for the single, non-nested, case (which is probably the vast majority), but how would 
it handle nested exceptions?


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


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

2014-02-21 Thread Tim Delaney
On 22 February 2014 10:29, Greg Ewing  wrote:

> Antoine Pitrou wrote:
>
> lst = [1, 2]
>>>value = lst[2] except IndexError: "No value"
>>>
>>
>> the gain in concision is counterbalanced by a loss in
>> readability,
>>
>
> This version might be more readable:
>
>value = lst[2] except "No value" if IndexError
>

+1 - it's readable, clear, and only uses existing keywords.

Tim Delaney
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Jan Kaliszewski

21.02.2014 18:37, Guido van Rossum wrote:


I'm put off by the ':' syntax myself (it looks to me as if someone
forgot a newline somewhere)


As I mentioned at python-ideas I believe that parens neutralize,
at least to some extent, that unfortunate statement-ish flavor
of the colon.

This one has some statement-like smell:

msg = seq[i] except IndexError: "nothing"

But this looks better, I believe:

msg = (seq[i] except IndexError: "nothing")

Or even (still being my favorite):

msg = seq[i] except (IndexError: "nothing")

Cheers.
*j

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


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

2014-02-21 Thread Greg Ewing

Chris Angelico wrote:

it wouldn't be that big a deal to completely reject multiple except
clauses and simply require that the


(rest of original post truncated)

Oh, no! The PSU has gotten wind of this proposal and doesn't
like it!

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Glenn Linderman

On 2/21/2014 3:29 PM, Greg Ewing wrote:

Antoine Pitrou wrote:


   lst = [1, 2]
   value = lst[2] except IndexError: "No value"


the gain in concision is counterbalanced by a loss in
readability,


This version might be more readable:

   value = lst[2] except "No value" if IndexError

since it puts the normal and exceptional values next
to each other, and relegates the exception type (which
is of much less interest) to a trailing aside.



Ternary if teaches us that the normal and alternate values should be on 
either end, so the present proposal corresponds to that; ternary if also 
teaches us that nesting affects the right value, in the absence of 
parentheses, this proposal seems to correspond, although requiring 
parentheses or not is presently a topic of discussion in a different 
subthread.


On the other hand, "if" and "except" are opposites in another way: "if" 
is followed by an expression that, if true, means the left value is 
used, and if false, means the right value is used. "Except" is followed 
by an exception that, if thrown, means the right value is used, and if 
not thrown, means the left value is used... but the word "except" is 
opposite in meaning to "if", so this actually fits nicely with English 
definitions.



Here's a challenge: There has been a big thread about None versus (SQL) 
Null. Show how an except: expression can help the DB API more easily 
convert from using None to using a new Null singleton, and you'll have a 
winner :)
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Ethan Furman

On 02/21/2014 11:04 AM, Yury Selivanov wrote:

On 2/20/2014, 10:15 PM, Chris Angelico wrote:


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


We can fix that in 3.5.


How many are you going to "fix"?  How are you going to "fix" the routines you 
don't control?


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


We can add 'list.get(index, default)' method, similar to
'Mapping.get'. It's far more easier than introducing new
syntax.


When I have to keep writing the same code over and over and aver again, I find a better way to do the job.  In this 
case, an exception expression does quite nicely.



I also searched how many 'except IndexError' are in
the standard library code.  Around 60.  That's a rather
low number, that can justify adding 'list.get' but not
advocate a new syntax.


And roughly 200 of KeyError, another couple hundred of ValueError...

This is not just about better handling of [missing] default values, but of better exception handling.  This PEP adds the 
ability to use a scalpel instead of a sledge hammer.


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


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

2014-02-21 Thread Steven D'Aprano
On Sat, Feb 22, 2014 at 01:15:13PM +1300, Greg Ewing wrote:
> Eli Bendersky wrote:
> >For instance, it is sometime non-trivial to know which exceptions some 
> >function may throw. When you write a try...raise statement, you think 
> >hard about covering all the bases. In an expression you're unlikely to,
> 
> Speak for yourself. I don't think I would put any less
> thought into which exception I caught with an except
> expression as I would for an except statement.

+1

With the possibly exception of messing about in the interactive 
interpreter, "catch as much as possible" is an anti-pattern. If you're 
not trying to catch as little as possible, you're doing it wrong.
 


> In fact, an except expression may even make it easier
> to catch exceptions in an appropriately targeted way.
> For example, a pattern frequently encountered is:
> 
>result = computation(int(arg))
> 
> and you want to guard against arg not being a
> well-formed int. It's tempting to do this:
> 
>try:
>   result = computation(int(arg))
>except ValueError:
>   abort("Invalid int")
> 
> But that's bad, because the try clause encompasses
> too much. Doing it properly requires splitting up the
> expression:
> 
>try:
>   i = int(arg)
>except:
>   abort("Invalid int")
>else:
>   result = computation(i)
> 
> With an except expression, it could be written:
> 
>result = computation(int(arg)
>   except ValueError: abort("Invalid int"))

Nice example! Except I'd lay the code out a bit better to emphasise 
which part is being guarded:

result = computation(
 int(arg) except ValueError: abort("Invalid int")
 )

Actually, not quite so nice as I first thought, since you're relying on 
the side-effects of abort() rather than returning a value. But apart 
from that quibble, the ability to guard *small* subcalculations without 
needing a visually heavy try...block is a good use-case.




-- 
Steven
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Greg Ewing

Ethan Furman wrote:

On 02/21/2014 03:29 PM, Greg Ewing wrote:


value = lst[2] except "No value" if IndexError


It does read nicely, and is fine for the single, non-nested, case (which 
is probably the vast majority), but how would it handle nested exceptions?


Hmmm, probably not very well, unless we define

   a except b if E1 except c if E2

to mean

   a except (b except c if E2) if E1

If E1 == E2, that could perhaps be abbreviated to

   a except b except c if E

Or we could just decide that the nested case is going
to be so rare it's not worth worrying about.

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Yury Selivanov


On 2/21/2014, 7:42 PM, Ethan Furman wrote:

On 02/21/2014 11:04 AM, Yury Selivanov wrote:

On 2/20/2014, 10:15 PM, Chris Angelico wrote:


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


We can fix that in 3.5.


How many are you going to "fix"?  How are you going to "fix" the 
routines you don't control?


This new syntax won't magically fix all the code either.
But it may let people write code like this:

  # I'm sorry, I really can't read this.
  logging.info("Message shown to user: %s",((cache[k]
  except LookupError:
  (backend.read(k) except OSError: 'Resource not available')
  )
  if check_permission(k) else 'Access denied'
  ) except BaseException: "This is like a bare except clause")

or this:

  # We happily mask exceptions from getgrnam
  g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid

And this particular case or list.pop method, let's be honest,
can be fixed ;)




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


We can add 'list.get(index, default)' method, similar to
'Mapping.get'. It's far more easier than introducing new
syntax.


When I have to keep writing the same code over and over and aver 
again, I find a better way to do the job.  In this case, an exception 
expression does quite nicely.


I can't believe you find

   list[42] except IndexError: 'spam'

to be better than

   list.get(42, 'spam')

If IndexError is such a big deal, I think we can add this function
to list and collections.abc.Sequence. Authors of libraries
will follow.




I also searched how many 'except IndexError' are in
the standard library code.  Around 60.  That's a rather
low number, that can justify adding 'list.get' but not
advocate a new syntax.


And roughly 200 of KeyError, another couple hundred of ValueError...

Many KeyErrors can be fixed with a proper use of '.get()', or 'in'
operator.

Many AttributeErrors can be fixed with use of getattr() or
hasattr(), or by designing a better API.

Many ValueErrors... wait, there are no ValueError examples
in the PEP, so I won't comment.



This is not just about better handling of [missing] default values, 
but of better exception handling.  This PEP adds the ability to use a 
scalpel instead of a sledge hammer.


I'd say it's another sledge-hammer, but a tad smaller and a cuter
one (to some people).  But it's still exception handling, still
more code than a function call.


Yury
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Ethan Furman

On 02/21/2014 05:21 PM, Steven D'Aprano wrote:

On Sat, Feb 22, 2014 at 01:15:13PM +1300, Greg Ewing wrote:


With an except expression, it could be written:

result = computation(int(arg)
   except ValueError: abort("Invalid int"))


Nice example! Except I'd lay the code out a bit better to emphasise
which part is being guarded:

 result = computation(
  int(arg) except ValueError: abort("Invalid int")
  )

Actually, not quite so nice as I first thought, since you're relying on
the side-effects of abort() rather than returning a value.


Think of it rather as transforming the exception to be more useful.

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


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

2014-02-21 Thread Steven D'Aprano
On Fri, Feb 21, 2014 at 04:42:36PM -0800, Ethan Furman wrote:

> This is not just about better handling of [missing] default values, but of 
> better exception handling.  This PEP adds the ability to use a scalpel 
> instead of a sledge hammer.

Beautifully said!


-- 
Steven
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Greg Ewing

Steven D'Aprano wrote:


result = computation(
 int(arg) except ValueError: abort("Invalid int")
 )

Actually, not quite so nice as I first thought, since you're relying on 
the side-effects of abort() rather than returning a value.


Yeah, while I was writing that I wondered whether
you should be allowed to write

   int(arg) except ValueError: raise UserError("Invalid int")

That looks heretical, because 'raise' can't in any
way be interpreted as a value-returning expression.
But you can achieve the same result using a function
that always raises and exception, so forbidding it
on those grounds would be pointless.

And writing it that way at least makes it obvious that
it *does* always raise an exception, in the same way
that

   try:
   i = int(arg)
except ValueError:
   raise UserError("Invalid int")
else:
   result = computation(i)

makes it obvious that control can't fall off the
end of the except branch.

--
Greg
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Glenn Linderman

On 2/21/2014 5:06 PM, Jan Kaliszewski wrote:

Or even (still being my favorite):

msg = seq[i] except (IndexError: "nothing") 


This syntax actually has a benefit: the parenthesized syntax after 
except could become a list, to allow handling different exceptions from 
the tried expression with different results:


msg = seq[dictionary[i]] except (IndexError: "nothing", KeyError: 
"serious problems")


And still allows nesting:

msg = seq[i] except (IndexError: dictionary[i] except (KeyError: "no 
fallback data for %s" % i))
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


[Python-Dev] GSOC 2014

2014-02-21 Thread NAVNEET SUMAN
Hi,
   This is my first year in gsoc. I have been working with python and
django from quite a time. One of the Gsoc proposed ideas drew my attention
and i would surely like to work on that.
I would like to work for creating a extension for idle to integrate
PEP8, what are the prerequisites . I have been studying  the PEP8 code past
a week. This might be useful for a quick start to this project. Please
guide.

-- 
 Thanks and Regards,

Navneet suman,
IIIT-Allahabad
+91-9305612151
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 6:06 PM, Jan Kaliszewski  wrote:
> 21.02.2014 18:37, Guido van Rossum wrote:
>
>> I'm put off by the ':' syntax myself (it looks to me as if someone
>> forgot a newline somewhere)
>
>
> As I mentioned at python-ideas I believe that parens neutralize,
> at least to some extent, that unfortunate statement-ish flavor
> of the colon.
>
> This one has some statement-like smell:
>
> msg = seq[i] except IndexError: "nothing"
>
> But this looks better, I believe:
>
> msg = (seq[i] except IndexError: "nothing")

Agreed.  The same holds true with {'a': 5} and function annotations
(e.g. "def f(a: 5)").

> Or even (still being my favorite):
>
> msg = seq[i] except (IndexError: "nothing")

+1

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Victor Stinner
Hi,


2014-02-21 4:15 GMT+01:00 Chris Angelico :
> PEP: 463
> Title: Exception-catching expressions

Nice PEP. Good luck, it's really hard to modify the language. Be
prepared to get many alternatives, criticisms, and suggestions. Good
luck to handle them :-) Here is mine.

I like the simple case "expr1 except Exception: expr2", but it is used
twice like "expr1 except Exception: (expr2 except Exception: expr3)".

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

I never used this once, I didn't know that it exists :)

> * min(sequence, default=default) - keyword argument in place of
>   ValueError
> * sum(sequence, start=default) - slightly different but can do the
>   same job

You should remove the sum() from your list, the start parameter is
unrelated. It is used to control input and output types for example.
It's not related to an exception.

> The proposal adds this::
>
> lst = [1, 2]
> value = lst[2] except IndexError: "No value"

The PEP looks nice on such simple example...

> Consider this example of a two-level cache::
> for key in sequence:
> x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))
> # do something with x

... but I don't like when it is used to build complex expressions.

At the first read, I'm unable to understand this long expression. At
the second read, I'm still unable to see which instruction will be
executed first: lvl1[key] or lvl2[key]?

The advantage of the current syntax is that the control flow is
obvious, from the top to the bottom:

# start
try:
x = lvl1[key]   # first instruction
except KeyError:
try:
x = lvl2[key]
except KeyError:
x = f(key)   # latest instruction
# end

Thanks to Python indentation, it's easier to see the control flow.

After having read a lot of code last 10 years, I now try to follow
this rule: one instruction per line.

For example, I don't like "if ((res = func()) == NULL)" in the C
language, I always split it into two lines. A drawback of writing more
than one instruction is that it's hard to debug instruction per
instruction (in pdb/gdb). Think for example of "if ((res = func()) ==
NULL)": if you execute step by step, how do you know which instruction
is currently executed?

You should maybe write your example differently:

x = (lvl1[key]
except KeyError: (lvl2[key]
   except KeyError: f(key)))

It looks like the classic try/except syntax.

> # sys.abiflags may not be defined on all platforms.
> _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: ''
>
> # Lib/sysconfig.py:529:
> try:
> _CONFIG_VARS['abiflags'] = sys.abiflags
> except AttributeError:
> # sys.abiflags may not be defined on all platforms.
> _CONFIG_VARS['abiflags'] = ''

getattr(sys, 'abiflags', '') can be used here.

> Retrieve an indexed item, defaulting to None (similar to dict.get)::
> def getNamedItem(self, name):
> return self._attrs[name] except KeyError: None
>
> # Lib/xml/dom/minidom.py:573:
> def getNamedItem(self, name):
> try:
> return self._attrs[name]
> except KeyError:
> return None

Hum, I don't understand this one. name is an index or a key? If it's a
key and self._attrs is a dict, you can use self._attrs.get(name).

> Translate numbers to names, falling back on the numbers::
> g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid
> u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: tarinfo.uid
>
> # Lib/tarfile.py:2198:
> try:
> g = grp.getgrnam(tarinfo.gname)[2]
> except KeyError:
> g = tarinfo.gid
> try:
> u = pwd.getpwnam(tarinfo.uname)[2]
> except KeyError:
> u = tarinfo.uid

Note (for myself): the KeyError comes from the function call, not from entry[2].

> Retrieving a message from either a cache or the internet, with auth
> check::
>
> logging.info("Message shown to user: %s",((cache[k]
> except LookupError:
> (backend.read(k) except OSError: 'Resource not available')
> )
> if check_permission(k) else 'Access denied'
> ) except BaseException: "This is like a bare except clause")

Oh, again: I prefer the try/except syntax (above), it's more easy to
see the control flow and understand the code. Too many instruction per
lines, the code is too "dense".

It looks like cache[k] is the first executed instruction, but it's
wrong: check_permission(k) is executed before.

So I prefer this version:

> try:
> if check_permission(k):
> try:
> _ = cache[k]
> except LookupError:
> try:
> _ = backend.read(k)
> except OSError:
> _ = 'Resource not available'
> else:
> _ = 'Access d

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

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 6:48 PM, Yury Selivanov  wrote:
> This new syntax won't magically fix all the code either.
> But it may let people write code like this:
>
>   # I'm sorry, I really can't read this.
>
>   logging.info("Message shown to user: %s",((cache[k]
>   except LookupError:
>   (backend.read(k) except OSError: 'Resource not available')
>   )
>   if check_permission(k) else 'Access denied'
>   ) except BaseException: "This is like a bare except clause")

You could argue the same thing about people chaining ternary
conditional expressions (because it would be about as hard to read).
Ditto for lambda.  These expression forms (and expressions in general)
are useful for brief snippets of code.  If someone wants to write
expressions that span multiple lines like that, then that's their
problem.  I don't see how the PEP 463 syntax will make it more likely
that someone will abuse expression syntax like that.

>
> or this:
>
>   # We happily mask exceptions from getgrnam
>
>   g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid

Either you'd get this anyway:

  try:
  g = grp.getgrnam(tarinfo.gname)[2]
  except KeyError:
  g = tarinfo.gid

or your fallback value will be evaluated prematurely:

  g = grp.getgrnam(tarinfo.gname).get(2, tarinfo.gid)

So to get this right:

  _info = grp.getgrnam(tarinfo.gname)
  try:
  g = _info[2]
  except KeyError:
  g = tarinfo.gid

vs.

  _info = grp.getgrnam(tarinfo.gname)
  g = _info[2] except KeyError: tarinfo.gid

> I can't believe you find
>
>list[42] except IndexError: 'spam'
>
> to be better than
>
>list.get(42, 'spam')

What about:

  list[42] except IndexError: something_expensive()

or:

  list[42] except IndexError: something_lazy_really_we_want_to_put_off()

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Eric Snow
On Fri, Feb 21, 2014 at 7:07 PM, Victor Stinner
 wrote:
>> Consider this example of a two-level cache::
>> for key in sequence:
>> x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))
>> # do something with x
>
> ... but I don't like when it is used to build complex expressions.

This is true of any expression syntax, not just this proposal--though
some expression syntax is more apt to be abused than others: you won't
see many multiline int literals! ;)

>
> At the first read, I'm unable to understand this long expression. At
> the second read, I'm still unable to see which instruction will be
> executed first: lvl1[key] or lvl2[key]?
>
> The advantage of the current syntax is that the control flow is
> obvious, from the top to the bottom:
>
> # start
> try:
> x = lvl1[key]   # first instruction
> except KeyError:
> try:
> x = lvl2[key]
> except KeyError:
> x = f(key)   # latest instruction
> # end
>
> Thanks to Python indentation, it's easier to see the control flow.
>
> After having read a lot of code last 10 years, I now try to follow
> this rule: one instruction per line.

+1

>
> For example, I don't like "if ((res = func()) == NULL)" in the C
> language, I always split it into two lines. A drawback of writing more
> than one instruction is that it's hard to debug instruction per
> instruction (in pdb/gdb). Think for example of "if ((res = func()) ==
> NULL)": if you execute step by step, how do you know which instruction
> is currently executed?

So true.

>
> You should maybe write your example differently:
>
> x = (lvl1[key]
> except KeyError: (lvl2[key]
>except KeyError: f(key)))
>
> It looks like the classic try/except syntax.

+1

-eric
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] GSOC 2014

2014-02-21 Thread Jessica McKellar
Hi Navneet,

>This is my first year in gsoc. I have been working with python and django
> from quite a time. One of the Gsoc proposed ideas drew my attention and i
> would surely like to work on that.
> I would like to work for creating a extension for idle to integrate
> PEP8, what are the prerequisites . I have been studying  the PEP8 code past
> a week. This might be useful for a quick start to this project. Please
> guide.

Thanks for your interest in CPython for Google Summer of Code!

Mentor organizations haven't been selected yet (the official mentor
list will go out on February 24th), and we are still finalizing our
project list.

In the meantime, I recommend:

1. Joining http://pythonmentors.com/
2. Reading through the developers guide: http://docs.python.org/devguide/
3. Picking and working on a ticket to get used to the workflow:
http://bugs.python.org/

In particular, it will be important to have contributed some patches
to CPython before you apply, so I recommend focusing on that for the
next couple of weeks. If you have questions while finding bugs and
preparing patches, please don't hesitate to ask on the
pythonmentors.com mailing list.

Regards,
-Jessica
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 6:04 AM, Yury Selivanov  wrote:
>> * seq[index] - no way to handle a bounds error
>
> We can add 'list.get(index, default)' method, similar to
> 'Mapping.get'. It's far more easier than introducing new
> syntax.

That fixes it for the list. Square brackets notation works for any
sequence. Are you proposing adding magic to the language so that any
class that defines a __getitem__ automatically has a .get() with these
semantics? Or, conversely, that defining __getitem__ requires that you
also explicitly define get()?

> Inconvenience of dict[] raising KeyError was solved by
> introducing the dict.get() method. And I think that
>
> dct.get('a', 'b')
>
> is 1000 times better than
>
> dct['a'] except KeyError: 'b'
>
> I don't want to see this (or any other syntax) used by
> anyone.

Every separate method has to be written. That's code that has to be
tested, etc. Also, when you go searching for usage of something, you
have to cope with the fact that it can be spelled two different ways.
This is more noticeable with attributes:

print(spam.eggs)
# versus
print(getattr(spam,"eggs","(no eggs)")

The second one definitely doesn't look like it's retrieving spam.eggs,
either in plain text search or in an AST walk. I would like to see
getattr used primarily where the second argument isn't a literal, and
an exception-catching rig used when a default is wanted; that keeps
the "x.y" form predictable.

> Moreover, I think that explicit handling of IndexError is
> rather ugly and error prone, using len() is usually
> reads better.
>>
>> Retrieve an argument, defaulting to None::
>>  cond = args[1] except IndexError: None
>>
>>  # Lib/pdb.py:803:
>>  try:
>>  cond = args[1]
>>  except IndexError:
>>  cond = None
>
>
> cond = None if (len(args) < 2) else args[1]

There's a distinct difference between those: one is LBYL and the other
is EAFP. Maybe it won't matter with retrieving arguments, but it will
if you're trying to pop from a queue in a multi-threaded program.

>> Attempt a translation, falling back on the original::
>>  e.widget = self._nametowidget(W) except KeyError: W
>>
>>  # Lib/tkinter/__init__.py:1222:
>>  try:
>>  e.widget = self._nametowidget(W)
>>  except KeyError:
>>  e.widget = W
>
> I'm not sure this is a good example either.
> I presume '_nametowidget' is some function,
> that might raise a KeyError because of a bug in
> its implementation, or to signify that there is
> no widget 'W'. Your new syntax just helps to work
> with this error prone api.

I don't know the details; this is exactly what you can see in tkinter
at the file and line I point to. Maybe some of these are highlighting
other problems to be solved, I don't know, but certainly there will be
cases where the API is exactly like this.

>> Read from an iterator, continuing with blank lines once it's
>> exhausted::
>>  line = readline() except StopIteration: ''
>>
>>  # Lib/lib2to3/pgen2/tokenize.py:370:
>>  try:
>>  line = readline()
>>  except StopIteration:
>>  line = ''
>
> Handling StopIteration exception is more common in standard
> library than IndexError (although not much more), but again,
> not all of that code is suitable for your syntax. I'd say
> about 30%, which is about 20-30 spots (correct me if I'm
> wrong).

I haven't counted them up, but it wouldn't be hard to. Probably not
terribly many cases of this in the stdlib, but a reasonable few.

>> Retrieve platform-specific information (note the DRY improvement);
>> this particular example could be taken further, turning a series of
>> separate assignments into a single large dict initialization::
>>  # sys.abiflags may not be defined on all platforms.
>>  _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: ''
>>
>>  # Lib/sysconfig.py:529:
>>  try:
>>  _CONFIG_VARS['abiflags'] = sys.abiflags
>>  except AttributeError:
>>  # sys.abiflags may not be defined on all platforms.
>>  _CONFIG_VARS['abiflags'] = ''
>
> Ugly.
> _CONFIG_VARS['abiflags'] = getattr(sys, 'abiflags', '')
> Much more readable.

Go ahead and make that change, if you prefer it. That's exactly how it
really is currently - the try/except block. Downside is as I mentioned
above: it no longer looks like "sys.abiflags", and won't come up when
you search for that.

>> Retrieve an indexed item, defaulting to None (similar to dict.get)::
>>  def getNamedItem(self, name):
>>  return self._attrs[name] except KeyError: None
>>
>>  # Lib/xml/dom/minidom.py:573:
>>  def getNamedItem(self, name):
>>  try:
>>  return self._attrs[name]
>>  except KeyError:
>>  return None
>
> _attrs there is a dict (or at least it's something that quaks
> like a dict, and has [] and keys()), so
>
> return self._attr

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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 9:06 AM, Greg Ewing  wrote:
> Nick Coghlan wrote:
>>
>> On 21 February 2014 13:15, Chris Angelico  wrote:
>>
>>> Generator expressions require parentheses, unless they would be
>>> strictly redundant.  Ambiguities with except expressions could be
>>> resolved in the same way, forcing nested except-in-except trees to be
>>> correctly parenthesized
>>
>>
>> I'd like to make the case that the PEP should adopt this as its
>> default position.
>
>
> I generally agree, but I'd like to point out that this
> doesn't necessarily mean making the parenthesizing rules as
> strict as they are for generator expressions.
>
> The starting point for genexps is that the parens are part of
> the syntax, the same way that square brackets are part of
> the syntax of a list comprehension; we only allow them to
> be omitted in very special circumstances.
>
> On the other hand, I don't think there's any harm in allowing
> an except expression to stand on its own when there is no
> risk of ambiguity, e.g.
>
>foo = things[i] except IndexError: None
>
> should be allowed, just as we allow
>
>x = a if b else c
>
> and don't require
>
>x = (a if b else c)

I'm inclined to agree with you. I fought against the mandated parens
for a long time. Would be happy to un-mandate them, as long as there's
no way for there to be ambiguity. Is CPython able to make an operator
non-associative? That is, to allow these:

value = expr except Exception: default
value = (expr except Exception: default) except Exception: default
value = expr except Exception: (default except Exception: default)

but not this:

value = expr except Exception: default except Exception: default

? By effectively demanding parens any time two except-expressions
meet, we could leave the option open to read multiple clauses off a
single base exception. If that can be done, and if people's need for
clarity can be satisfied, and if the rules aren't too complicated, I'd
be happy to go back to "parens are optional".

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 10:29 AM, Greg Ewing
 wrote:
> Antoine Pitrou wrote:
>
>>>lst = [1, 2]
>>>value = lst[2] except IndexError: "No value"
>>
>>
>> the gain in concision is counterbalanced by a loss in
>> readability,
>
>
> This version might be more readable:
>
>value = lst[2] except "No value" if IndexError
>
> since it puts the normal and exceptional values next
> to each other, and relegates the exception type (which
> is of much less interest) to a trailing aside.

I'll expand on this in the PEP shortly, but there are two downsides to this.

1) Everywhere else in Python, "if" is followed by a boolean, and
"except" is followed by an exception list. As a boolean, IndexError is
always going to be true, which will confuse a human; and "No value"
doesn't look like a modern exception at all.

2) Order of evaluation puts the main expression first, then the
exception list, and lastly the default. Putting them in another order
in the code is confusing. With ternary if/else, this is justified, but
it's usually something to avoid.

3) Erm, among the downsides are such diverse elements... ahem. The
part after the except clause is a full expression, and could plausibly
have the if/else ternary operator. Starting with some expression, then
if, then another expression, means you have to look for an else before
you can be sure you're reading it correctly. Of course, any sane
programmer who actually puts an if/else inside an except/if should
parenthesize, but when you read someone else's code, you have to be
prepared for the more normal sort of programmer.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 12:10 PM, Glenn Linderman  wrote:
> Here's a challenge: There has been a big thread about None versus (SQL)
> Null. Show how an except: expression can help the DB API more easily convert
> from using None to using a new Null singleton, and you'll have a winner :)

Heh! I'm not entirely sure how that would work, as I've only skimmed
the DB API thread, but I understand part of it is to do with sorting.
I'm not sure how you could embed an except-expression into that
without either changing the sort function or potentially doing part of
the sort twice:

lst = sorted(stuff) except TypeError: sorted(stuff, key=keyfunc)

at which point you may as well go straight to the key= form from the start.

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


Re: [Python-Dev] Python 3.4: Cherry-picking into rc2 and final

2014-02-21 Thread Stephen J. Turnbull
Antoine Pitrou writes:
 > On Thu, 20 Feb 2014 10:24:16 +0900
 > "Stephen J. Turnbull"  wrote:
 > > 
 > > The argument that a "read-only, no cherrypicking by committers" repo
 > > is nothing but a better tarball is valid, but as I say, AFAICS the
 > > expected gain is pretty marginal.  The conflict here is not Larry's
 > > process, it's the decision to make an ambitious release on a short
 > > time schedule.
 > 
 > I don't really buy the "short time schedule" argument. The delay
 > between 3.3 and 3.4 is ~18 months as usual.

"Short" here isn't relative to calendar time nor to the development
cycle length.  It's relative to the time needed to properly beta and
RC an "ambitious" set of changes, with more than the usual number of
patches during RC AFAIK, and the time allowed for that testing.  I'm
not saying it isn't enough time, but I certainly think that more time
or a less ambitious release would make folks feel more comfortable,
and less apt to suggest changes in a release process at this late date.

My point is that I don't think that changing Larry's process would
make a big difference to our ability to test the release candidates,
Ubuntu deadlines not withstanding.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 12:55 PM, Greg Ewing
 wrote:
> Steven D'Aprano wrote:
>
>> result = computation(
>>  int(arg) except ValueError: abort("Invalid int")
>>  )
>>
>> Actually, not quite so nice as I first thought, since you're relying on
>> the side-effects of abort() rather than returning a value.
>
>
> Yeah, while I was writing that I wondered whether
> you should be allowed to write
>
>int(arg) except ValueError: raise UserError("Invalid int")
>
> That looks heretical, because 'raise' can't in any
> way be interpreted as a value-returning expression.
> But you can achieve the same result using a function
> that always raises and exception, so forbidding it
> on those grounds would be pointless.

def throw(exc):
raise exc

int(arg) except ValueError: throw(UserError("Invalid int"))

Tiny helper function and then it doesn't need any special syntax. It's
not so much that PEP 463 forbids this, as that it doesn't explicitly
permit it. The 'default' part of the syntax is an expression, raise is
not an expression, ergo it's not permitted. But if you think this is
sufficiently common (translate an exception on the way through), show
some code and justify its addition - or just write up a separate
proposal for "raise X" to become an expression, same as "yield X" is.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 1:07 PM, Victor Stinner
 wrote:
> At the first read, I'm unable to understand this long expression. At
> the second read, I'm still unable to see which instruction will be
> executed first: lvl1[key] or lvl2[key]?
>
> The advantage of the current syntax is that the control flow is
> obvious, from the top to the bottom:
>
> # start
> try:
> x = lvl1[key]   # first instruction
> except KeyError:
> try:
> x = lvl2[key]
> except KeyError:
> x = f(key)   # latest instruction
> # end

That's why I'm strongly in favour of syntax variants that have
evaluation order be equally obvious: left to right. Its notation may
be uglier, but C's ternary operator does get this right, where
Python's executes from the inside out. It's not a big deal when most
of it is constants, but it can help a lot when the expressions nest.

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 3:04 PM, Chris Angelico  wrote:
> On Sat, Feb 22, 2014 at 1:07 PM, Victor Stinner
>  wrote:
>> At the first read, I'm unable to understand this long expression. At
>> the second read, I'm still unable to see which instruction will be
>> executed first: lvl1[key] or lvl2[key]?
>>
>> The advantage of the current syntax is that the control flow is
>> obvious, from the top to the bottom:
>>
>> # start
>> try:
>> x = lvl1[key]   # first instruction
>> except KeyError:
>> try:
>> x = lvl2[key]
>> except KeyError:
>> x = f(key)   # latest instruction
>> # end
>
> That's why I'm strongly in favour of syntax variants that have
> evaluation order be equally obvious: left to right. Its notation may
> be uglier, but C's ternary operator does get this right, where
> Python's executes from the inside out. It's not a big deal when most
> of it is constants, but it can help a lot when the expressions nest.

I've added a couple of paragraphs to my draft PEP:

https://raw.github.com/Rosuav/ExceptExpr/master/pep-0463.txt

If someone could please commit that version to the official repo? Or I
can submit a diff against the peps repo if that would be easier.

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


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

2014-02-21 Thread Yury Selivanov


On 2/21/2014, 10:42 PM, Chris Angelico wrote:

On Sat, Feb 22, 2014 at 6:04 AM, Yury Selivanov  wrote:

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

We can add 'list.get(index, default)' method, similar to
'Mapping.get'. It's far more easier than introducing new
syntax.

That fixes it for the list. Square brackets notation works for any
sequence. Are you proposing adding magic to the language so that any
class that defines a __getitem__ automatically has a .get() with these
semantics? Or, conversely, that defining __getitem__ requires that you
also explicitly define get()?


No, I proposed to consider adding 'list.get()' and
'collections.abc.Sequence.get()' (or a better name),
if catching IndexError is such a popular pattern.

We can also fix stdlib. Authors of the python libraries/
frameworks will likely follow.

No magic in the language, no requirements on __getitem__,
obviously.


Inconvenience of dict[] raising KeyError was solved by
introducing the dict.get() method. And I think that

dct.get('a', 'b')

is 1000 times better than

dct['a'] except KeyError: 'b'

I don't want to see this (or any other syntax) used by
anyone.

Every separate method has to be written. That's code that has to be
tested, etc. Also, when you go searching for usage of something, you
have to cope with the fact that it can be spelled two different ways.
This is more noticeable with attributes:

print(spam.eggs)
# versus
print(getattr(spam,"eggs","(no eggs)")

The second one definitely doesn't look like it's retrieving spam.eggs,
either in plain text search or in an AST walk.

And that's not a common thing to use AttributeError/getattr at
all. It is common in frameworks, yes, but not that much
in client code.

  I would like to see
getattr used primarily where the second argument isn't a literal, and
an exception-catching rig used when a default is wanted; that keeps
the "x.y" form predictable.

I understand. But I still think that using getattr is better
than 'a.b except AttributeError: c'

Moreover, I think that explicit handling of IndexError is
rather ugly and error prone, using len() is usually
reads better.

Retrieve an argument, defaulting to None::
  cond = args[1] except IndexError: None

  # Lib/pdb.py:803:
  try:
  cond = args[1]
  except IndexError:
  cond = None


cond = None if (len(args) < 2) else args[1]

There's a distinct difference between those: one is LBYL and the other
is EAFP. Maybe it won't matter with retrieving arguments, but it will
if you're trying to pop from a queue in a multi-threaded program.

Using a method that modifies its underlying object deep in
expression is also questionable, in terms of readability and
maintainability of the code.  I find try..except statement
more favourable here.


Attempt a translation, falling back on the original::
  e.widget = self._nametowidget(W) except KeyError: W

  # Lib/tkinter/__init__.py:1222:
  try:
  e.widget = self._nametowidget(W)
  except KeyError:
  e.widget = W

I'm not sure this is a good example either.
I presume '_nametowidget' is some function,
that might raise a KeyError because of a bug in
its implementation, or to signify that there is
no widget 'W'. Your new syntax just helps to work
with this error prone api.

I don't know the details; this is exactly what you can see in tkinter
at the file and line I point to. Maybe some of these are highlighting
other problems to be solved, I don't know, but certainly there will be
cases where the API is exactly like this.


Read from an iterator, continuing with blank lines once it's
exhausted::
  line = readline() except StopIteration: ''

  # Lib/lib2to3/pgen2/tokenize.py:370:
  try:
  line = readline()
  except StopIteration:
  line = ''

Handling StopIteration exception is more common in standard
library than IndexError (although not much more), but again,
not all of that code is suitable for your syntax. I'd say
about 30%, which is about 20-30 spots (correct me if I'm
wrong).

I haven't counted them up, but it wouldn't be hard to. Probably not
terribly many cases of this in the stdlib, but a reasonable few.


Just having a "reasonable few" use cases in huge stdlib
isn't a warrant for new syntax.



Retrieve platform-specific information (note the DRY improvement);
this particular example could be taken further, turning a series of
separate assignments into a single large dict initialization::
  # sys.abiflags may not be defined on all platforms.
  _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: ''

  # Lib/sysconfig.py:529:
  try:
  _CONFIG_VARS['abiflags'] = sys.abiflags
  except AttributeError:
  # sys.abiflags may not be defined on all platforms.
  _CONFIG_VARS['abiflags'] = ''

Ugly.
_CONFIG_VARS['abiflags'] = getattr(sys, 'abiflags', '')

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

2014-02-21 Thread Yury Selivanov


On 2/21/2014, 11:22 PM, Chris Angelico wrote:

I've added a couple of paragraphs to my draft PEP:

https://raw.github.com/Rosuav/ExceptExpr/master/pep-0463.txt

If someone could please commit that version to the official repo? Or I
can submit a diff against the peps repo if that would be easier.

I've committed the new version.

Yury
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Ethan Furman

On 02/21/2014 07:46 PM, Chris Angelico wrote:


but not this:

value = expr except Exception: default except Exception: default


This should be the way it works.  Nothing is gained in readability by turning a try with multiple except statements into 
an expression.


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


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

2014-02-21 Thread Steven D'Aprano
On Fri, Feb 21, 2014 at 02:04:45PM -0500, Yury Selivanov wrote:

> Inconvenience of dict[] raising KeyError was solved by
> introducing the dict.get() method. And I think that
> 
> dct.get('a', 'b')
> 
> is 1000 times better than
> 
> dct['a'] except KeyError: 'b'

I don't think it is better. I think that if we had good 
exception-catching syntax, we wouldn't need a get method.

"get" methods do not solve the problem, they are shift it.

Every class that defines [] look-ups also needs a get method. We can 
write dict.get(key, default), but we can't write list.get(index, 
default). If we "fix" list, we then find that tuple.get(index, default) 
fails. So we "fix" tuple, and then discover that str.get(index, default) 
fails.

If Python were Ruby, then all sequences could inherit from 
one Sequence class that defines:

def get(self, index, default=None):
try:
return self[index]
except IndexError:
return default


and similarly for mappings, with KeyError instead of IndexError. But 
this is Python, not Ruby, and there is no requirement that sequences 
must inherit from the same parent class. They just have to provide the 
same duck-typed interface.

Having added a get method to every mapping and sequence, you then call 
list.pop() and discover that it too needs a default. And so on, forever. 
We're forever chasing the next method and function, adding default 
parameters to everything in sight. The latest example is max and min.

Then there are functions or methods which come in pairs, like str.find 
and str.index. From time to time people ask for a version of list.index 
that returns a default value instead of raising. Should we give them 
one? I don't think Python is a better language by adding complexity into 
the libraries and built-ins in this way.

(And let's not forget that while methods and functions can have default 
parameters, expressions cannot. So there is a whole class of potential 
operations that can never be given a default, because they aren't a 
function call.)

The essence of programming is combining primitive constructs to make 
more complicated ones, not in the proliferation of special-purpose 
methods or functions. "get" is less primitive than normal [] lookup, and 
it exists for a special purpose: to avoid needing to break apart what 
ought is a single conceptual expression into a multi-line statement. 
Consider a single conceptual chunk of code, the expression 
process(mydict[key]). In the past, if you wanted to use a default value 
if the key didn't exist, the only alternative was to break that 
expression up into two statements, regardless of whether you used LBYL 
or EAFP idioms:

if key in mydict:
tmp = mydict[key]
else:
tmp = default
result = process(tmp)


try:
tmp = mydict[key]
except KeyError:
tmp = default
result = process(tmp)


Consequently, to express a single expression *as a single expression*, 
we needed an expression that can do the same thing, and in the past that 
had to be a method:

result = process(mydict.get(key, default))


But now we have a LBYL expression form:

result = process(mydict[key] if key in mydict else default)


and are suggesting a EAFP form:

result = process(mydict[key] except KeyError: default)


If Python had this syntax 20 years ago, would dicts have grown a get 
method? I doubt it very much. People would be told to wrap it in an 
except expression.


> >Consider this example of a two-level cache::
> > for key in sequence:
> > x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: 
> > f(key)))
> > # do something with x
> 
> I'm sorry, it took me a minute to understand what your
> example is doing.  I would rather see two try..except blocks
> than this.

It helps to break it up more appropriately. (Also less cryptic names.) I 
can see PEP 8 will need some changes if this syntax is approved.

for key in sequence:
x = (cache1[key] except KeyError: 
 (cache2[key] except KeyError:
  f(key)))
# Do something with x

This proposal is not about saving lines of code, and if examples are 
written jammed into a single line or two, and that hurts readability, 
they should be formatted better. It is about expressing the EAFP idiom 
in an expression, without giving up the useful property that the 
"except" clause is only evaluated when needed, not in advance.

(Chris, I think that ought to go in the motivation section of the PEP.)



-- 
Steven

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


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

2014-02-21 Thread Chris Angelico
On Sat, Feb 22, 2014 at 4:01 PM, Steven D'Aprano  wrote:
> (Chris, I think that ought to go in the motivation section of the PEP.)

Added to my draft, and here's the peps diff:

diff -r c52a2ae3d98e pep-0463.txt
--- a/pep-0463.txt Fri Feb 21 23:27:51 2014 -0500
+++ b/pep-0463.txt Sat Feb 22 16:33:37 2014 +1100
@@ -43,6 +43,34 @@

 * 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 signal 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
 =
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Stephen J. Turnbull
Ethan Furman writes:
 > On 02/21/2014 07:46 PM, Chris Angelico wrote:
 > >
 > > but not this:
 > >
 > > value = expr except Exception: default except Exception: default
 > 
 > This should be the way it works.  Nothing is gained in readability
 > by turning a try with multiple except statements into an
 > expression.

Examples have been given several times.  In general, if 'expr' is a
function call, it may well have a couple of different ways to fail
which imply different default values.

interpolable = func(key) except TypeError: "not a string: %s" % key \
 except KeyError: "no such key: %s" % key
print("Some message that refers to '%s' % interpolable")

versus

try:
interpolable = func(key)
except TypeError:
interpolable = "not a string: %s" % key
except KeyError:
interpolable = "no such key: %s" % key
print("Some message that refers to '%s' % interpolable")

I think the latter begs to be written as the former.

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


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

2014-02-21 Thread Glenn Linderman

On 2/21/2014 7:57 PM, Chris Angelico wrote:

On Sat, Feb 22, 2014 at 12:10 PM, Glenn Linderman  wrote:

Here's a challenge: There has been a big thread about None versus (SQL)
Null. Show how an except: expression can help the DB API more easily convert
from using None to using a new Null singleton, and you'll have a winner :)

Heh! I'm not entirely sure how that would work, as I've only skimmed
the DB API thread, but I understand part of it is to do with sorting.
I'm not sure how you could embed an except-expression into that
without either changing the sort function or potentially doing part of
the sort twice:

lst = sorted(stuff) except TypeError: sorted(stuff, key=keyfunc)

at which point you may as well go straight to the key= form from the start.


Yes, the "challenge" was sort of tongue-in-cheek... it was the latest 
heavily opinionated thread with no conclusion... and if a particular 
feature could help arrive at a good solution I think a lot of people 
would be happy! And probably a lot would still think it wasn't a good 
solution!


It does help acceptance of a new feature to describe and demonstrate a 
solution to a compelling problem; Stephen's recent explanation of LBYL 
and EAFP expressions helped make it more compelling to me, it sounded 
like you added some of that to the PEP, which is good. Some folks didn't 
find the PEP examples compelling, it seems.


The sorting is a smoke-screen. The real problem is that None and Null 
are not the same thing, and so internally the DB Api should invent and 
use Null, and translate to None (optionally) at the interfaces, for 
backwards compatibility until their users can update their software to 
use Null also.


The implementation of Null can handle the comparison/sorting issue... 
there are a fixed number of types for SQL, so it isn't that hard.
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


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

2014-02-21 Thread Stephen J. Turnbull
Steven D'Aprano writes:
 > On Fri, Feb 21, 2014 at 02:04:45PM -0500, Yury Selivanov wrote:
 > 
 > > Inconvenience of dict[] raising KeyError was solved by
 > > introducing the dict.get() method. And I think that
 > > 
 > > dct.get('a', 'b')
 > > 
 > > is 1000 times better than
 > > 
 > > dct['a'] except KeyError: 'b'

Aside from the "no need for 'get'" argument, I like the looks of the
latter better, because dct.get('a', 'b') could be doing anything,
while the syntax in the expression is defined by the language and says
exactly what it's doing, even if read in English (obviously you have
to be a Python programmer to understand that, but you don't need to be
Dutch).

 > I don't think it is better. I think that if we had good 
 > exception-catching syntax, we wouldn't need a get method.
 > 
 > "get" methods do not solve the problem, they are shift it.

Note in support: I originally thought that "get" methods would be more
efficient, but since Nick pointed out that "haveattr" is implemented
by catching the exception (Yikes! LBYL implemented by using EAFP!), I
assume that get methods also are (explicitly or implicitly)
implemented that way.

I'm not a huge fan of the proposal (in my own code there aren't a lot
of potential uses, and I think the colon syntax is a little ugly), but
the "eliminates need for .get()" argument persuades me that the colon
syntax is better than nothing.

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


[Python-Dev] One more cherry-pick request for 3.4.0 that I'd like a little public debate on

2014-02-21 Thread Larry Hastings


Victor has asked me to cherry-pick 180e4b678003:

   http://bugs.python.org/issue20320  (original issue)
   http://hg.python.org/cpython/rev/180e4b678003/  (checkin into trunk)
   http://bugs.python.org/issue20646  (cherry-pick request)

This revision changes the rounding behavior of fractional-second 
timeouts for select.select and select.kqueue.  I don't have enough 
context to judge whether or not this is bad enough to warrant 
cherry-picking, and the discussion on the issue didn't seem to come to a 
firm consensus.


Can I get some opinions on this?

FWIW, I'm going to cut the next preview in a few minutes, and this won't 
be in it, but I don't actually tag until most of a day from now.



//arry/
___
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com