[Python-ideas] A better (simpler) approach to PEP 505

Antoine Pitrou solipsis at pitrou.net
Mon Jul 23 12:46:07 EDT 2018


On Mon, 23 Jul 2018 11:12:45 -0400
David Mertz <mertz at gnosis.cx> wrote:
> 
> The particular names I use are nothing special, and better ones might be
> found.  I just called the class NoneAware and the "escape" method
> `.unbox()` because that seemed intuitive at first brush.
> 
> I don't disagree that needing to call .unbox() at the end of the chained
> attribute access is a little bit ugly.  But it's a lot less ugly than large
> family of new operators.  And honestly, it's a nice way of being explicit
> about the fact that we're entering then leaving a special world where
> attribute accesses don't fail.
> 
> I haven't implemented the equivalent dictionary lookups in the below.  That
> would be straightforward, and I'm sure my 5 minute throwaway code could be
> improved in other ways also.  But something better than this in the
> standard library would address ALL the actual needs described in PEP 505.
> Even the pattern Steve Dower is especially fond of like:
> 
> favorite = cfg?.user?.profile?.food ?? "Spam"
> 
> 
> (i.e. a configuration may be incomplete at any level, if levels are missing
> default favorite food is Spam).  We could simply spell that:
> 
> favorite = NoneAware(cfg, "Spam").user.profile.food.unbox()
> 
> 
> I think that's 14 characters more in this example, but still compact.  We
> could get that down to 2 characters if we used one-letter names for the
> class and method.  I suppose down to zero characters if .unbox() was a
> property.

You could use .__call__() instead of .unbox().  Also you can make
unboxing unnecessary in most cases by having your class proxy most
operations, like weakref.proxy does.  The "wrapt" library may help with
that:
http://wrapt.readthedocs.io/en/latest/wrappers.html

Regards

Antoine.




More information about the Python-ideas mailing list