[Python-ideas] Null coalescing operators
Mark Haase
mehaase at gmail.com
Fri Sep 18 19:42:59 CEST 2015
StackOverflow has many questions
<http://stackoverflow.com/search?q=%5Bpython%5D+null+coalesce> on the topic
of null coalescing operators in Python, but I can't find any discussions of
them on this list or in any of the PEPs. Has the addition of null
coalescing operators into Python ever been discussed publicly?
Python has an "or" operator that can be used to coalesce false-y values,
but it does not have an operator to coalesce "None" exclusively.
C# has nice operators for handling null: "??" (null coalesce), "?."
(null-aware member access), and "?[]" (null-aware index access). They are
concise and easy to reason about. I think these would be a great addition
to Python.
As a motivating example: when writing web services, I often want to change
the representation of a non-None value but also need to handle None
gracefully. I write code like this frequently:
response = json.dumps({
'created': created.isoformat() if created is not None else None,
'updated': updated.isoformat() if updated is not None else None,
...
})
With a null-aware member access operator, I could write this instead:
response = json.dumps({
'created': created?.isoformat(),
'updated': updated?.isoformat(),
...
})
I can implement this behavior myself in pure Python, but it would be (a)
nice to have it the in the standard library, and (b) even nicer to have an
operator in the language, since terseness is the goal.
I assume that this has never been brought up in the past because it's so
heinously un-Pythonic that you'd have to be a fool to risk the public
mockery and shunning associated with asking this question. Well, I guess
I'm that fool: flame away...
Thanks,
Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150918/2b6b6cfb/attachment.html>
More information about the Python-ideas
mailing list