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

Jeff Hardy jdhardy at gmail.com
Tue Sep 29 06:04:54 CEST 2015


On Mon, Sep 28, 2015 at 1:56 PM, Guido van Rossum <guido at python.org> wrote:

> On Mon, Sep 28, 2015 at 1:41 PM, Donald Stufft <donald at stufft.io> 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.
>

This whole line of discussion is why I'd prefer the PEP be split to have ??
in one and ?., ?[, etc. in another (the thread I linked isn't even the
longest one discussing the associativity - there were many that preceded
it). I agree that the short circuit behaviour is the only one that makes
any sense, but I also don't want to see the very useful ?? operator lost
because of discussions over or implementation difficulties of ?. or ?[.

And if it's going to be done anyway, I'd to see ?( as well.

- Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150928/499e910d/attachment.html>


More information about the Python-ideas mailing list