Good code patterns in Python

Andrew Bennetts andrew-pythonlist at puzzling.org
Wed Jul 2 05:48:33 EDT 2003


On Wed, Jul 02, 2003 at 08:28:28AM +0200, Max M wrote:
[...]
> 
> if some_condition:
>     some_name = some_value
> else:
>     if some_exotic_condition:
>         some_name = third_value
>     else:
>         some_name = other_value
> 
> 
> It would have been a simpler and less error prone procedure to change 
> the code if it it had used the first form.
> 
> 
> some_name = other_value
> if some_condition:
>     some_name = some_value
> else:
>     if some_exotic_condition:
>         some_name = third_value

For this specific example, I think I'd prefer:

if some_condition:
    some_name = some_value
elif some_exotic_condition:
    some_name = third_value
else:
    some_name = other_value

Regardless, I always feel uneasy about:

x = some_val
if cond:
    x = special_val

I think it's the reassignment of 'x' here that bugs me -- conceptually, this
code is setting x to a value depending on a certain condition, and so having
to mentally trace through "it's set to val -- oh, no, now it isn't" is an
unwelcome distraction, whereas:

if cond:
    x = special_val
else:
    x = some_val

can be "read" more-or-less directly into English: "if the condition is true,
then 'x' is set to 'special_val'; otherwise, 'x' is set to 'some_val'".
Saying "'x' is set to 'some_val'.  Now, if some condition is true, 'x' is
set to 'special_val'" is counter-intuitive to my way of thinking.

That said, I can readily recognise both idioms (despite having a slight
preference for one form), so it's really a non-issue... 

it's-all-fun-and-games-until-someone-mentions-ternary-operators-ly yrs, Andrew.






More information about the Python-list mailing list