Good code patterns in Python

Curly Joe woooee at yahoo.com
Thu Jul 3 15:41:14 EDT 2003


Andrew Bennetts wrote:

> 
> 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 is mostly a non-issue, and excuse me if I am
stating the obvious, but we have to be careful about
setting the default to special_val or some_val.  The
code depends on what we want to do when the inevitable
new type of data is silently introduced.  In very
general terms, we want to include what we want - as
the above code does, not exclude what we don't want -
as in the original post.  That way, new data is not
included, whereas it would be if we had excluded.  To
belabor the point, suppose we have the following code:
.if MALE :
.    male += 1
.else :
.    female += 1

instead of
.if not FEMALE :
.    male += 1
.else :
.   female += 1

These both work the same way until someone adds a
check box for "I prefer to not state my gender".  The
file gets updated with this new type, and we then run
our summary program.  In the first code example, it is
counted as female, and in the second, it is counted as
male.  This is the main reason, as far as I know, that
we use the "if exception: else: general" format.  And
if we have had our toes stepped on a few times, we
quit lying in our programs and state
.if MALE :
.    male += 1
.else :
.    not_male += 1

since that is all we really know because we didn't
explicitly test for female.  Again pardon me if I am
taking up a lot of space with an issue that most don't
care about.



__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com





More information about the Python-list mailing list