On 13/09/2016 12:37, Nick Coghlan wrote:
On 13 September 2016 at 21:15, Rob Cliffe
wrote: On 13/09/2016 04:43, Guido van Rossum wrote:
Yeah, that's exactly my point. PEP 463 gives you a shorter way to catch an exception, so it gives you less motivation to find a way to write your code (or define your API) that doesn't involve catching exceptions. But APIs involving exceptions are often inferior to APIs that don't require exception catching. (Yes, I am aware of __next__() raising StopIteration -- but that API design usually doesn't require you to catch it.)
You surprise me. I thought LBYL and EAFP were both approved Python idioms, in some cases one being better, in some cases another, choice to be made on the merits of each case (or the author's preference). I certainly use both (and sometimes time both to see which is faster). Now it sounds as if you're trying to impose a style guide on the world by discouraging the EAFP. And wasn't the discussion general, not about APIs specifically? Which is preferable depends greatly on context of use, which is why you'll find a lot of Python APIs offer both forms My point exactly. Random832 echoes my thoughts:
However, blindly catching *all* exceptions from a complex subexpression is rarely the right thing to do, Of course. so APIs that only offer "this may throw exceptions during normal operation under these circumstances" without a convenience wrapper that does the exception handling for you can end up being a pain to work with.
PEP 463 makes those APIs less painful to deal with, but at the cost of encouraging overly broad exception handlers. Why? You can catch exactly the same (wide or narrow) range of exceptions in an exception-catching expression as you can in a
"Guido's argument here seems to be that exception-based EAFP is not pythonic." [snip] try+except block. Of course result = (myList[0] except Exception: MyDefault) is poor code (presumably it should have been written "except IndexError"), but so is try: result = myList[0] except Exception: result = MyDefault ISTM you're giving an exception-catching dog a bad name and hanging him. Or have I missed something? And sorry to repeat myself, but we seemed to be having a *general* discussion about null-coalescing operators, which moved on to PEP 463, then suddenly Guido is talking about APIs. A lot of the time when I'm coding, I'm not writing an API, just a program to get a job done. No doubt, exceptions should be discouraged *in APIs*, but that doesn't make exceptions, or EAFP, a bad idea per se. I really don't mean this post to sound hostile, and I'm sorry if it comes across a bit that way. I'm just surprised at what I'm hearing, and to be honest, I have a soft spot for PEP 463. Best wishes Rob Cliffe