[Python-ideas] Coming up with an alternative to PEP 505's None-aware operators

Nick Coghlan ncoghlan at gmail.com
Fri Feb 16 02:55:22 EST 2018


On 16 February 2018 at 12:19, rymg19 at gmail.com <rymg19 at gmail.com> wrote:
> I don't know...to me this looks downright ugly and an awkward special case.
> It feels like it combines reading difficulty of inline assignment with the
> awkwardness of a magic word and the ugliness of using ?. Basically, every
> con of the other proposals combined...

Yeah, it's tricky to find a spelling that looks nice without being
readily confusable with other existing constructs (most notably
keyword arguments).

The cleanest *looking* idea I've come up with would be to allow
arbitrary embedded assignments to ordinary frame local variables using
the "(expr as name)" construct:

    value = tmp.strip()[4:].upper() if (var1 as tmp) is not None else None

    value = tmp[4:].upper() if (var1 as tmp) is not None else None

    value = tmp if (var1 as tmp) is not None else tmp if (var2 as tmp)
is not None else var3

    value = tmp if not math.isnan((var1 as tmp)) else tmp if not
math.isnan((var2 as tmp)) else var3

    value = f() if (calculate as f) is not None else default

    filtered_values = [val for x in keys if (get_value(x) as val) is not None]

    range((calculate_start() as start), start+10)
    data[(calculate_start() as start):start+10]

    value if (lower_bound() as min_val) <= value < min_val+tolerance else 0

    print(f"{(get_value() as tmp)!r} is printed in pure ASCII as
{tmp!a} and in Unicode as {tmp}")

However, while I think that looks nicer in general, we'd still have to
choose between two surprising behaviours:

* implicitly delete the statement locals after the statement where
they're set (which still overwrites any values previously bound to
those names, similar to what happens with exception clauses)
* skip deleting, which means references to subexpressions may last
longer than expected (and we'd have the problem where embedded
assignments could overwrite existing local variables)

The interaction with compound statements would also be tricky to
figure out (especially if we went with the "delete after the
statement" behaviour).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list