On 12/09/2016 08:05, Michel Desmoulin wrote:
I messed up my answer and replied to one person instead of the list, so
I'll post it again.

There is also an alternative to this operator, and it's allowing a
shortcut to do:

try:
     val = do_thing()
except ThingError:
     val = "default"

In the form of:

val = do_thing() except ThingError: "default"

I was debated, and rejected, but I feel like mentioning it again because
it has some strong benefits.

First, it handles the null coalescing very quite well:

val = obj.foo.bar.hey except AttributeError: "default"

But it also can deal with many common operations in Python without the
need to add more operators or variants:

val = my_list[0] except IndexError: "default"

val = iterable[0] except TypeError: next(iter(iterable))

val = int(param) except ValueError: man.nan

It's quite readable, in the same vein of val = foo if bar else
"default", but also familiar since it's using known keyword. And it
doesn't require to add a new operator support in the parser.

Another serious benefits is that it fits current use cases, AND futur
use cases. Indeed, since it leverages Python exception mechanism, any
lib implementing a clean error model can immediately let the users
benefit from it without having to implement, tests and document lots of
helper methods with "default" keywords and the like, while not being
limited to a set of values some operators would only care about, such as
None.

Plus, since EAFP is a popular and handy pattern, it makes sense.

At last, it has the same characteristic as the null coalescing operator:
it's lazy, and hence has a small performance interest too compared to
functional equivalent.

Did I mention it's also easy to expend to a full try/except when you
need something more complicated ? And then you benefit from else and
finally immediately.

I already have many code that would benefit from such a syntax, and I'd
like to hear again what you think about it.


+1, you're preaching to the converted.
This is PEP 463, "Exception-catching expressions".
Except that the PEP required parentheses around a whole exception-catching expression, for reasons that are not clear to me, i.e.
    val = (my_list[0] except IndexError: "default")
rather than
    val = my_list[0] except IndexError: "default"
Rob Cliffe



_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to