[Python-ideas] PEP 505: None-aware operators

David Mertz mertz at gnosis.cx
Wed Jul 25 22:45:04 EDT 2018


On Wed, Jul 25, 2018 at 10:29 PM Chris Angelico <rosuav at gmail.com> wrote:

> food = spam?.eggs?.bacon
>
> can be rewritten as
>
> _tmp = spam
> if _tmp is not None:
>     _tmp = _tmp.eggs
>     if _tmp is not None:
>         _tmp = _tmp.bacon
> food = _tmp
>

Yes, that looks right.  Well, you need a `del _tmp` at the end; but it's
almost right.  My point was that both you and Nicholas Chammas failed to
recognize that the other translation was wrong... I recognize it does
something "kinda similar."  But the semantics of the operators are just
plain hard to grok, even by their strongest advocates.

I can write lots of things that are "mostly correct" already in Python.
Most easily, I can write:

try:
   food = spam.eggs.bacon
except:
  food = None


That does what is actually needed about 95% of the time.  It's also clear
and easy to understand.

It is *actually impossible* to
> perfectly represent short-circuiting semantics in Python!


It's INCREDIBLY EASY to represent short-circuiting semantics in Python!
What on earth are you talking about?  That's what the if/elif/else blocks
do.

And before you go "well that proves my point, this suggestion is bad", let's
> apply the same test to a few other pieces of syntax. Rewrite the
> following statements without using the syntactic feature named in the
> comment:
>

This is childishly simple:


> # 1) Decorators
> @deco
> def func():
>     ...
>

def func():
   ...
func = deco(func)


OK, this one is harder.  The "mostly correct" version is easy.  But the
actual full version is nuanced (see
https://www.python.org/dev/peps/pep-0380/ for details).

# 2) "yield from"
> def chain(*iters):
>     for iter in iters:
>         yield from iter
>

# The simple approximation:
for iter in iters:

    for _ in iter:

        yield iter



> # 3) and the big one: generator expressions
> # yes, I'm deliberately using x multiple ways here
> def f(x): return x*x
> x = range(10)
> x = (f(x) for x in x if x % 2)
>

I'm not going to bother with that.  I'd fire anyone who wrote it, after
code review.  Minus the abuse of names, it's just:

def gen(xs):

    for x in xs:

        if x % 2:

            yield f(x)

x = gen(xs)



-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180725/098989b4/attachment-0001.html>


More information about the Python-ideas mailing list