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

David Mertz mertz at gnosis.cx
Wed Jul 25 22:12:29 EDT 2018


On Wed, Jul 25, 2018 at 9:47 PM Nicholas Chammas <nicholas.chammas at gmail.com>
wrote:

> > That is disingenuous, I think.  Can this raise an AttributeError?
>> >     spam?.eggs?.bacon
>> > Of course it can! And this is exactly the pattern used in many examples
>> in
>> > the PEP and the discussion. So the PEP would create a situation where
>> code
>> > will raise AttributeError in a slightly—and subtly—different set of
>> > circumstances than plain attribute access will.
>>
>

>     food = spam?.eggs?.bacon
> Can be rewritten as:
>     food = spam
>     if spam is not None and spam.eggs is not None:
>         food = spam.eggs.bacon
> They both behave identically, no? Maybe I missed the point David was
> trying to make.
>

No, you illustrate it perfectly! I had to stare at your translation for a
while to decide if it was really identical to the proposed
`spam?.eggs?.bacon`.  The fact I have to think so hard makes the syntax
feel non-obvious.

Plus, there's the fact that your best effort at translating the proposed
syntax is WRONG.  Even a strong proponent cannot explain the behavior on a
first try.  And indeed, it behaves subtly different from plain attribute
access in where it raises AttributeError.

>>> spam = SimpleNamespace()
>>> spam.eggs = None
>>> spam.eggs.bacon
AttributeError: 'NoneType' object has no attribute 'bacon'

>>> # spam?.eggs?.bacon
>>> # Should be: None

>>> "Translation" does something different
>>> food = spam
>>> if spam is not None and spam.eggs is not None:
...     food = spam.eggs.bacon
>>> food
namespace(eggs=None)


-- 
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/71560565/attachment.html>


More information about the Python-ideas mailing list