[Python-ideas] Null coalescing operators

Andrew Barnert abarnert at yahoo.com
Sun Sep 20 23:34:34 CEST 2015


On Sep 20, 2015, at 04:05, Paul Moore <p.f.moore at gmail.com> wrote:
> 
> 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)

But try this for calling a method on a possibly-null object:

    result = maybe(maybe(spam).eggs)(cheese)




More information about the Python-ideas mailing list