[Python-ideas] PEP 505 (None coalescing operators) thoughts

Donald Stufft donald at stufft.io
Mon Sep 28 23:06:32 CEST 2015


On September 28, 2015 at 4:56:44 PM, Guido van Rossum (guido at python.org) wrote:
> On Mon, Sep 28, 2015 at 1:41 PM, Donald Stufft wrote:
>  
> > On September 28, 2015 at 4:25:12 PM, Guido van Rossum (guido at python.org)
> > wrote:
> > > On Mon, Sep 28, 2015 at 1:15 PM, Donald Stufft wrote:
> > >
> > > > The ? Modifying additional attribute accesses beyond just the immediate
> > > > one bothers me too and feels more ruby than python to me.
> > > >
> > >
> > > Really? Have you thought about it?
> >
> > Not extensively, mostly this is a gut feeling.
> >
> > >
> > > Suppose I have an object post which may be None or something with a tag
> > > attribute which should be a string. And suppose I want to get the
> > > lowercased tag, if the object exists, else None.
> > >
> > > This seems a perfect use case for writing post?.tag.lower() -- this
> > > signifies that post may be None but if it exists, post.tag is not
> > expected
> > > to be None. So basically I want the equivalent of (post.tag.lower() if
> > post
> > > is not None else None).
> > >
> > > But if post?.tag.lower() were interpreted strictly as
> > (post?.tag).lower(),
> > > then I would have to write post?.tag?.lower?(), which is an abomination.
> > > OTOH if post?.tag.lower() automatically meant post?.tag?.lower?() then I
> > > would silently get no error when post exists but post.tag is None (which
> > in
> > > this example is an error).
> > >
> >
> > Does ? propagate past a non None value? If it were post?.tag.name.lower()
> > and post was not None, but tag was None would that be an error or would the
> > ? propagate to the tag as well?
> >
>  
> I was trying to clarify that by saying that foo?.bar.baz means (foo.bar.baz
> if foo is not None else None). IOW if tag was None that would be an error.
>  
> The rule then is quite simple: each ? does exactly one None check and
> divides the expression into exactly two branches -- one for the case where
> the thing preceding ? is None and one for the case where it isn't.
>  

Ok, that makes me feel less bad than my initial impression was that ? was going to modify all following things so that they were all implicitly ?. Just splitting it into two different branches seems OK.

I’m not a big fan of the punctuation though. It took me a minute to realize that post?.tag.lower() was saying if post is None, not if post.tag is None and I feel like it’s easy to miss the ?, especially when combined with other punctuation. 

-----------------
Donald Stufft
PGP: 0x6E3CBCE93372DCFA // 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA




More information about the Python-ideas mailing list