[Python-ideas] Null coalescing operators
Chris Angelico
rosuav at gmail.com
Sat Sep 19 04:26:11 CEST 2015
On Sat, Sep 19, 2015 at 12:06 PM, Mark E. Haase <mehaase at gmail.com> wrote:
> Can anybody think of realistic use cases for overriding a magic method for
> the "?" operator? I would like to include such use cases in a PEP. One
> possible use case: being able to coalesce empty strings.
>
>>>> s1 = MyString('')
>>>> s2 = MyString('foobar')
>>>> s1? or s2
> MyString('foobar')
Frankly, I think this is a bad idea. You're potentially coalescing
multiple things with the same expression, and we already have a way of
spelling that: the "or" operator. If you don't want a generic "if it's
false, use this", and don't want a super-specific "if it's None, use
this", then how are you going to define what it is? And more
importantly, how do you reason about the expression "s1? or s2"
without knowing exactly what types coalesce to what? Let's keep the
rules simple. Make this a special feature of the None singleton, and
all other objects simply return themselves - for the same reason that
a class isn't allowed to override the "is" operator.
ChrisA
More information about the Python-ideas
mailing list