[Python-ideas] Null coalescing operators

Paul Moore p.f.moore at gmail.com
Sun Sep 20 13:05:52 CEST 2015

On 20 September 2015 at 08:31, Steven D'Aprano <steve at pearwood.info> wrote:
> I'm not convinced that we should generalise this beyond the three
> original examples of attribute access, item lookup and function call. I
> think that applying ? to arbitrary operators is a case of "YAGNI". Or
> perhaps, "You Shouldn't Need It".


Does this need to be an operator? How about the following:

    class Maybe:
        def __getattr__(self, attr): return None
        def __getitem__(self, idx): return None
        def __call__(self, *args, **kw): return None

    def maybe(obj):
        return Maybe() if obj is None else obj

    attr = maybe(obj).spam
    elt = maybe(obj)[n]
    result = maybe(callback)(args)

The Maybe class could be hidden, and the Maybe() object a singleton
(making my poor naming a non-issue :-)) and if it's felt sufficiently
useful, the maybe() function could be a builtin.

Usage of the result of maybe() outside of the above 3 contexts should
simply be "not supported" - don't worry about trying to stop people
doing weird things, just make it clear that the intent is only to
support the 3 given idiomatic usages.


More information about the Python-ideas mailing list