Le 23/07/2018 à 18:00, David Mertz a écrit :
On Mon, Jul 23, 2018 at 11:26 AM Paul Moore <p.f.mo...@gmail.com
<mailto:p.f.mo...@gmail.com>> wrote:
* Library solution works with all versions of Python
* The need for unbox is a little ugly, but arguably less so than ?.
(conceded that's a subjective view)
* Mixing ?. and . is terser than unboxing and reboxing - but are there
any real examples where that's needed?
* Having the default at the beginning rather than at the end doesn't
follow natural reading order (but again that's pretty subjective)
On the last point, it would be easy enough to change the API to make
it `NoneAware(obj).a.b.c.unbox(sentinel)` if that was thought a better
API than `NoneAware(obj, sentinel).a.b.c.unbox()`.
Oh... and the production code should DEFINITELY spell 'sentinel'
correctly if that's a part of the API. :-)
One of the good things about this proposal, is that it may be expanded
to other sentinels:
ret = NoneAware(obj, sentinel=0).a.unbox(42)
# would be equivalent to
ret = obj.a if obj.a is not 0 else 42
# or, if tmp_a had side effects
tmp_a = obj.a
ret = tmp_a if tmp_a is not 0 else 42
One thing that this proposal doesn't cover easily (although I'd refactor
the code before using this syntax, as excepted in some very specific
cases like when using ORMs, I don't like chaining methods and properties
like this):
favorite = cfg?.user.profile?.food ?? "Spam" # every user should have a
profile
favorite = NoneAware(cfg).user.profile.food.unbox("Spam") # We're
silencing an exception that I didn't plan to silence
Another thing is that both parts are executed. If instead of "Spam" we
had any variable with a side effect, it would have been executed even if
cfg.user.profile.food existed. We're missing the lazy evaluation of this
part here.
That being said, I deeply believe the use case for that are not spread
enough to justify such a change. And I can see from here code where
every '.' is prepended by a '?' just in case (the same way we encounter
frequently exceptions catching for Exception).
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/