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

Steven D'Aprano steve at pearwood.info
Wed Jul 25 13:40:41 EDT 2018


On Tue, Jul 24, 2018 at 07:02:54AM -0400, David Mertz wrote:
> On Tue, Jul 24, 2018, 5:50 AM Steven D'Aprano <steve at pearwood.info> wrote:
> 
> > But what certainly *is* implicity is David Mertz' suggestion for a
> > magical None-aware proxy:
> >
> >     x.attribute
> >
> > The only way to tell whether that was an ordinary attribute lookup or a
> > none-aware lookup would be to carefully inspect x and find out whether it
> > was an instance of the None-aware proxy class or not.
> >
> 
> Every use I've suggested for the magic proxy is similar to:
> 
>   NullCoalesce(cfg).user.profile.food

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)

Now there are at least four potentially magic proxy objects floating 
around: config, user, the user.id key, and food.

It is naive (if not a little disingenuous) to suggest that this 
NullCoalesce proxy object will always be used in a single expression and 
never passed as argument to a function, inserted in a list or dict, or 
otherwise processed any distance away from the call to NullCoalesce.

Consequently, the moment we see 

    from module import NullCoalesce

in a module, *every dot attribute access* becomes questionable until 
we've satisfied ourselves that the object in question isn't magic.


    spam.attribute
    eggs.attribute


One of those is ordinary attribute access that can raise AttributeError, 
and the other is magic attribute access that silently suppresses 
AttributeErrors. Which is which?


    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.

I wish there was a way to tell which is which... if only they used 
different syntax or something... *wink*



> Yes, the class is magic. That much more so in the library I published last
> night that utilizes wrapt.ObjectProxy. But it's also pretty explicit in
> that an actual *word* announces that funny stuff is going to happen on the
> same line.
> 
> Of course the this could be abused with:
> 
>   cfg = NoneCoalesce(cfg)
>   ... 1000 lines ...
>   do_something(cfg)

Why does Python have named variables if it is "abuse" to use them?



-- 
Steve


More information about the Python-ideas mailing list