python syntax for conditional is unfortunate
ndbecker2 at gmail.com
Wed Sep 24 03:50:23 CEST 2008
Aaron "Castironpi" Brady wrote:
> On Sep 23, 6:52 pm, 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.
> You're talking strictly about readability, which among other things is
> in the eye of the beholder, of course. Temporary variables can clean
> up some code, even if choosing names can be a hassle and it's more
> things to keep track of. Long lines and extra variables form a trade-
> off. You are writing a line with a conditional expression the value
> of which depends on something. What does it depend on, what is its
> value if that's true, and what is it if it's false? '...if...else...'
> only takes 6 characters... maybe you want more!
> If you're looking for a strictly syntactic construct, you can always
> "fire blanks", or tracers, if the analogy's more accurate.
> z= conditionally( x ) if b else y
> This could serve as a gentle reminder, even where 'conditionally'
> returns its argument, i.e. is the identity function. You can always
> roll your own ternary with extra parameters too:
> z= condition( b, x, y )
> Just don't confuse it with threading.Condition.
> Otherwise, you're stuck with old syntax markers, and unless you
> z= if b then x else y
> You're out of options. You have to express it somehow. Did you want
> the condition first? Was there an alternative proposal you
> preferred? IINM if I'm not mistaken,
> z= b and x or y
> works just the same so long as x evaluates to True, as it will be
> Feel free to write your own from scratch, and we'll see how close
> Python can come to resembling it.
> I suppose you can compare it to someone who stops listening before the
> word 'if', and completely misunderstands your statement. "Feed the
> dog if he's standing near the food dish" != "Feed the dog", which can
> of course lead to errors of both omission and commission (doing too
> little -or- too much). There's no way to fix that in a guaranteed
> way, except to say, "listen to the whole statement".
> And strictly sarcastically, what did you want to do with reading the
> program? Why were you reading it? <snicker, ducks>
I find I'm often tripped up by:
x = Y (lots of constructor arguments....) if something ...
on first glance, I don't notice the if.
Why am I reading this? Umm, because I wrote it.
More information about the Python-list