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

David Mertz mertz at gnosis.cx
Wed Jul 25 21:02:33 EDT 2018


On Wed, Jul 25, 2018 at 8:00 PM Steven D'Aprano <steve at pearwood.info> wrote:

> > Every use I've suggested for the magic proxy is similar to:
> >   NullCoalesce(cfg).user.profile.food
>

Thanks Steven!  Several things you suggest urge some minor improvements to
my slightly-more-than-toy library `coalescing` (
https://pypi.org/project/coalescing/).


> I trust that you don't expect everyone to religiously follow the
> exact letter of your examples. Being able to extract out subexpressions
> into variables is an important programming technique, and we ought to be
> able to do things like this:
>
>     config = NullCoalesce(cfg)
>     process(config)
>
>     # later...
>     user = config.user
>     user_records[user.id] = user
>     food = get_preferred_food(user)
>

Yes, absolutely! In many cases this will JUST WORK because of the magic in
wrapt.ObjectProxy.  But it also makes me realize that I should provide a
plain old function `unbox()` as well as the method.  In particular,
`unbox(obj)` can and will figure out whether the object is really a proxy
at all, and if not simply return `obj` itself.  Then you do no harm by
scattering unbox() calls in places where they may or may not be needed.

I also think that even though it was a typo at first, the name NullCoalesce
is better than NoneCoalesce.  I'll provide an alias.


>     spam?.attribute
>     eggs.attribute
> One of those is ordinary attribute access that can raise AttributeError
> if the object is None, and the other is None-aware "maybe dot" attribute
> access that returns None if the object is None.
>

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.

The fact that half the readers of this thread won't immediately see just
when that AttributeError might occur (based on lots of prior
misunderstandings by smart posters) makes the operator that much more
magical.

-- 
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/415a806e/attachment-0001.html>


More information about the Python-ideas mailing list