On 29 November 2017 at 21:53, Serhiy Storchaka firstname.lastname@example.org wrote:
29.11.17 11:45, Steven D'Aprano пише:
On Wed, Nov 29, 2017 at 09:14:12AM +0200, Serhiy Storchaka wrote:
What is the syntax of the ternary operator in these languages?
All four use:
condition ? first : second
for the ternary if operator.
If all four use ?, it is natural that in operators which are shortcuts of the ternary operator they use ?. But in Python the bar of introducing ? is higher.
It's also noteworthy that they all offer "&&" and "||" as short circuiting "and" and "or" operators. When you have that pattern established, then "??" fits right in.
With Python's only spelling for the logical operators being "and" and "or", the cryptic unpronounceable nature of "??" becomes much harder to ignore.
"a and b" -> pronounced "a and b" "a or b" -> pronounced "a or b" "a ?? b" -> pronounced "a <what??> b"
The only potentially pronounceable versions I've been able to come up with are a fair bit longer:
"a if def else b" -> pronounced "a if defined, else b" "a if ?? is not None else b" -> pronounced "a if the leftmost operand is not None, else b" "a if ?? is None else ??.b" -> pronounced "a if the leftmost operand is None, else the leftmost operand dot b"
(The last two examples there are a version where "??" appearing in either the condition expression or the RHS of a conditional expression would cause the leftmost operand to be eagerly evaluated, placed in a hidden temporary variable and then referenced multiple times as a subexpression. A similar construct could then also be used in filter expressions in comprehensions to refer back to the loop's result clause: "[f(x) for x in iterable if ?? is not None]". It's still magical and hard to look up syntax, but "??" as a magic placeholder to say "Reference the leftmost operand in the current expression here, but still only evaluate it once" seems nicer to me than using it as a cryptic binary operator)