[Python-ideas] Fwd: Null coalescing operator

Rob Cliffe rob.cliffe at btinternet.com
Mon Sep 12 06:52:39 EDT 2016



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



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160912/b2c00894/attachment.html>


More information about the Python-ideas mailing list