[Python-Dev] Adding a conditional expression in Py3.0

Nick Coghlan ncoghlan at gmail.com
Thu Sep 29 17:19:36 CEST 2005


Raymond Hettinger wrote:
> [Aahz]
> 
>>I'm also opposed to elif in conditional expressions -- let's keep this
> 
> a
> 
>>simple Pythonic rewrite of C's ternary.
>>
>>I'm +0 on requiring parentheses precisely because they're annoying.
> 
> I'm
> 
>>still expecting simple boolean expressions to be the primary use case,
>>and my hunch is that overall Python code will read better with the
>>ternary looking cluttered.
> 
> 
> FWIW, I scanned the standard library for all the and/or pairings where a
> conditional expression was applicable.  This sampling can serve as a
> reference for what "typical" uses would look like in real Python code as
> created by a number of different authors.

Thanks for digging those out - I was thinking that would be a useful exercise, 
but hadn't taken the time to think of an easy way to find relevant lines.

> It only takes about five minutes to try out a given syntax proposal on
> all the fragments listed below.  That short exercise provides an
> excellent insight into the look and feel of each proposal in real world
> code.

I tried it with (if C then A else B) and (A if C else B), and found both to be 
significantly more readable than the current code.

In particular, I wouldn't want to bet money that none of the examples are 
buggy, as there were a few cases where the "A" value could conceivably be 0 or 
'', but I couldn't tell if it was possible for the condition to also be true 
in those cases.

Comparing the two syntaxes I tried, I found that the infix notation generally 
required the addition of parentheses around the "A" expression when that 
expression was itself a binary operation - otherwise the precedence was 
unclear and, even with parentheses around the whole conditional, the layout 
gave the impression that the conditional expression only applied to the second 
argument to the binary operation in "A".

That said, the more verbose form still felt like it had the elements out of 
sequence - it was just crying out for the expression to be rewritten as a 
statement.

Regards,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list