Steven D'Aprano writes:

 > In my opinion, writing
 > 
 >     expression if expression is None else default
 > 
 > is the *opposite* of Pythonic, it is verbose and the DRY violation is 
 > inelegant (as well as inefficient). I'd much rather use:
 > 
 >     expression ?? default

Sure, if "expression or default" won't do.  But in my code, I can't
recall encountering a case where it wouldn't.

That is, in the vast majority of my code, the point of using None as
the "oops, try again" sentinel is not that it's a different *value*
from a falsie of the expected type, it's that it's a different *type*.
It has very few attributes, and so will most likely eventually raise
if I forget the "or default" clause and a falsie escapes from the
enclosing code, rather than silently doing an erroneous computation.

Of course "in my code" is very anecdotal, and we do have testimony
from many people that these cases are important to them.  I'd still
like to know, not how much code looks better with "expr ?? default"
vs. spelling it out as a conditional statement or expression, but
rather how much code *must* be expressed as "expr ??  default" (or
"expr ?. attr ?? default", as Steve Dower reminds us) because the
falsie of expected type is a useful value of expr (or expr.attr).

 > although with PEP 572 approved, there is an alternative:
 > 
 >     temp := expression if temp is None else default
 > 
 > which avoids the DRY violation but is more verbose than even the first 
 > version.

No, it somewhat obfuscates the DRY violation, but you've still used
"temp" twice.  (Consider "var if var is None else default".)  I also
don't agree that it's more verbose than the first version if
"expression" is more complex than a variable reference, not to mention
the possibility of side effects in expression.

Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to