python syntax for conditional is unfortunate

Asun Friere afriere at yahoo.co.uk
Wed Sep 24 05:07:58 EDT 2008


On Sep 24, 9:52 am, Neal Becker <ndbeck... at gmail.com> wrote:
> In hindsight, I am disappointed with the choice of conditional syntax.  I know it's too late to change.  The problem is
>
> y = some thing or other if x else something_else
>
> When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!).  Particularly if 'some thing or other' is long or complicated.

The struggle to get a conditional operator was a long and bitter, so
in the first place we should be glad we aren't writing "y =
(conditional and [p] or [q])[0] anymore.  Since it was but grudgingly
bestowed I thought BDFL had chosen this particular syntax just to be
difficult.

However since using it for a while, I am surprised how natural it is
to use and read.  A canonical use of the conditional operator is in
pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). For
this and similar short uses, where the regular if statement is an
annoyance this syntax <ususal_case> if <conditions> else
<unusual_case> works nicely.  More complicated conditionals or cases
are probably better handled by an if statement. This syntax is also
probably not the best for nested conditionals.  The latter, however,
is probably feature rather than bug.



More information about the Python-list mailing list