On Sep 18, 2015, at 15:56, Erik firstname.lastname@example.org wrote:
On 18/09/15 23:37, Chris Angelico wrote: Python generally doesn't special-case None, so having a bit of magic that works only on that one object seems a little odd.
So the answer here is to introduce a "magic" hook that None can make use of (but also other classes). I can't think of an appropriate word, so I'll use "foo" to keep it suitably abstract.
If the foo operator uses the magic method "__foo__" to mean "return an object to be used in place of the operand should it be considered ... false? [or some other definition - I'm not sure]" then any class can implement that method to return an appropriate proxy object.
If that was a postfix operator which has a high precedence, then:
bar = foo? bar.isoformat()
and the original syntax suggestion:
bar = foo?.isoformat()
... are equivalent. "?." is not a new operator. "?" is. This is essentially a slight refinement of Chris's case 3 -
I like this (modulo the corrections later in the thread). It's simpler and more flexible than the other options, and also comes closer to resolving the "spam?.eggs" vs. "spam?.cheese()" issue, by requiring "spam?.cheese?()".
Obviously "spam?" returns something with a __getattr__ method that just passes through to spam.__getattr__, except that on NoneType it returns something with a __getattr__ that always returns None. That solves the eggs case.
Next, "spam?.cheese?" returns something with a __call__ method that just passed through to spam?.cheese.__call__, except that on NoneType it returns something with a __call__ that always returns None. That solves the cheese case.
If you make None? return something whose other dunder methods also return None (except for special cases like __repr__), this also gives you "spam ?+ 3". (I'm not sure if that's a good thing or a bad thing...) Of course there's no way to do "spam ?= 3" (but I'm pretty sure that's a good thing).
So, do we need a dunder method for the "?" operator? What else would you use it for besides None?