[Python-ideas] Null coalescing operators
Oleg Broytman
phd at phdru.name
Sun Sep 20 13:29:26 CEST 2015
On Sun, Sep 20, 2015 at 12:05:52PM +0100, Paul Moore <p.f.moore at gmail.com> wrote:
> 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".
>
> Agreed.
>
> 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.
PyMaybe - a Python implementation of the Maybe pattern. Seems to be
quite elaborated.
https://github.com/ekampf/pymaybe
> Paul.
Oleg.
--
Oleg Broytman http://phdru.name/ phd at phdru.name
Programmers don't die, they just GOSUB without RETURN.
More information about the Python-ideas
mailing list