On 21 September 2015 at 15:41, Steven D'Aprano firstname.lastname@example.org wrote:
An actual real-life example where we work around this by using a temporary name that otherwise isn't actually used for anything:
mo = re.match(needle, haystack) if mo: substr = mo.group() else: substr = None
I think it is perfectly reasonable to ask for syntactic sugar to avoid having to write code like the above:
substr = re.match(needle, haystack)?.group()
Well, (1) Mark had focused on the "coalesce" operator ??, not the ?. variant, and that is less obviously useful here, and (2) I find the former version more readable. YMMV on readability of course - which is why I added the proviso that if someone comes up with an "obviously right" syntax, I may well change my mind. But the options suggested so far are all far less readable than a simple multi-line if (maybe with a temporary variable) to me, at least.
By the way, in your example you're passing on the "none or useful" property by making substr be either the matched value or None. In real life, I'd probably do something more like
mo = re.match(needle, haystack) if mo: process(mo.group()) else: no_needle()
possibly with inline code if process or no_needle were simple. But it is of course easy to pick apart examples - real code isn't always that tractable. For example we get (what seems to me like) a *lot* of bug reports about "None has not attribute foo" style errors in pip. My comments here are based on my inclinations about how I would fix them in pip - I'd always go back to *why* we got a None, and try to avoid getting the None in the first place. But that's not always easy to do. Again, of course, YMMV.