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

Steven D'Aprano steve at pearwood.info
Sun Jul 22 21:11:22 EDT 2018


On Sun, Jul 22, 2018 at 05:09:39PM +0200, Giampaolo Rodola' wrote:

> > > I personally don't find "a ?? b" too bad (let's say I'm -0 about it)
> > > but idioms such as "a?.b", "a ??= b" and "a?[3] ?? 4" look too
> > > Perl-ish to me, non pythonic and overall not explicit, no matter what
> > > the chosen symbol is gonna be.
> >
> > Please explain what is not explicit about it. "a?.b" is very simple
> > and perfectly explicit: it means "None if a is None else a.b". What
> > does "not explicit" mean, other than "I don't like this code"?
> 
> I find it less explicit mainly because it does 3 things at once: check
> if attribute is None, use it if it's not None and continue the
> evaluation from left to right. I find that logic to be more explicit
> when living on different lines or is clearly delimited by keywords and
> spaces.

Does this mean that instead of writing:

    result = obj.attr + 1

you prefer to be "explicit" and split it over multiple lines?

    # named functions are always better than punctuation
    from operator import add  
    # explicit is better than punctuation
    value = getattr(obj, "attr")  
    result = add(value, 1)


> ? has no spaces, it's literally "variable names interrupted by
> question marks" and evaluation can stop at any time while scanning the
> line from left to right.

Just like ordinary attribute access.

This is the point I was making earlier: you accept existing punctuation 
doing these things:

    try:
        obj.spam.egsg.tomato.cheese  # oops a typo
    except AttributeError:
        # evaluation can stop at any time
        ...

while demanding a higher standard for new punctuation.

All of your criticisms of ? punctuation applies to . as well. Do you 
think that Python is a worse language than it should have been because 
we use . for attribute access?


> Multiple "?" can live on the same line so
> that's incentive to write one-liners, really, and to me one-liners are
> always less explicit than the same logic split on multiple lines.

Explicit is not always better.

    import this

is much better than:


    for location in sys.path:
        try:
            for file in os.listdir(location):
                if os.splitext(file) in ('.pyc', '.py', '.so'):
                    ...


etc. There is a HUGE amount of implicit complexity and work done behind 
the scenes in every import, and we're happy to keep it that way.


-- 
Steve


More information about the Python-ideas mailing list