[Python-ideas] Null coalescing operators

Paul Moore p.f.moore at gmail.com
Tue Sep 22 10:12:00 CEST 2015


On 21 September 2015 at 23:56, Carl Meyer <carl at oddbird.net> wrote:
> My jaw dropped a bit when I saw it asserted in this thread that
> functions returning "useful value or None" is an anti-pattern. I write
> functions like that all the time, and I consider it a useful and
> necessary Python idiom. I would hate to rewrite all that code to either
> deal with exceptions or add default-value-argument boilerplate to all of
> them; when "no result" is an expected and normal possibility from a
> function, letting the calling code deal with None however it chooses is
> much nicer than either of those options.

Maybe my use of the phrase "anti-pattern" was too strong (i thought it
implied a relatively mild "this causes problems"). Having the caller
deal with problems isn't bad, but in my experience, too often the
caller *doesn't* deal with the possibility None return. It feels
rather like C's practice of returning error codes which never get
checked.

But as I said, YMMV, and my experience is clearly different from yours.

> I don't love the ? syntax, but I would certainly use the feature
> discussed here happily and frequently.

If we're back to discussing indexing and attribute access rather than
??, maybe -> would work?

obj->attr meaning None if obj is None else obj.attr
obj->[n] meaning None if obj is None else obj[attr]
obj->(args) meaning None if obj is None else obj(args)

I think Matthias Bussonnier's point that ? and ?? is heavily used in
IPython is a good one. Python traditionally doesn't introduce new
punctuation (@ for decorators was AFAIK the last one). I thought that
was precisely to leave the space of unused characters available for
3rd party tools.

Paul


More information about the Python-ideas mailing list