[Python-ideas] PEP 505: None-aware operators: operators ?= and ?? and OR

Michel Desmoulin desmoulinmichel at gmail.com
Fri Jul 20 09:06:54 EDT 2018


Proposal a __very__ dumbed down "try" expression
====================================================

    variable = try Expression as not sentinel [else default]

The semantic is:

1 - try the expression. If any call (from a normal method, or a
__dunder__ one) returns the sentinel, we shortcircuit.

2 - if we shortcircuit, the variable will be set do the default value.
If no default is provided, the variable is set to the sentinel.

3 - if we don't shortcircuit, the returned value is the one from the
expression.


Example
==========


    value = try foo.bar[0] as not None

If anything returns None, we shortcircuit and value will end up being
None. Otherwise value contains the result of foo.bar[0].

    value = try foo.bar[0] as not True

If anything returns True, we shortcircuit and value will end being True.
Otherwise value contains the result of foo.bar[0].

    value = try foo.bar[0] as not None else "foo"

If anything returns None, we shortcircuit and value will end up being
'foo'. Otherwise value contains the result of foo.bar[0].


    value = try foo.bar[0] as not True else "foo"

If anything returns True, we shortcircuit and value will end up being
'foo'. Otherwise value contains the result of foo.bar[0].


This as several benefits:
=========================

- Does not introduce new keywords or operators

- Read pretty much as ordinary Python

- Allow for inline try, as suggested before several times on
python-idea, but restrict it to a very narrow subset of what it can do.
This will end the debate about inline try/except, while sill providing a
sane subsets of use cases it would have provided.

- more flexible than ? as it allows to choose what to choose the
sentinel and the default value instead of just None.

- the expression is untouched. It's surrounded by the rest, so it still
reads as the expression would without try / as.

- avoding "except", exception names and ":" make sure we don't confuse
this try expression with the regular try/except statements. try would
then be a very restricted version of it, like lambda is for def.


If you don't like these keywords
===============================

We can opt for something different:

value = try Expression as not sentinel [or default]
value = try Expression if not sentinel [else default]
value = try Expression with not sentinel [else default]

The proposal is more about the structure try (stuff), guard against a
sentinel, and optionally return a default value.

Besides, I don't know what the grammar would allow.


More information about the Python-ideas mailing list