Coding style

Antoon Pardon apardon at forel.vub.ac.be
Wed Jul 19 08:27:39 EDT 2006


On 2006-07-19, Georg Brandl <g.brandl-nospam at gmx.net> wrote:
> Lawrence D'Oliveiro wrote:
>> In message <Q8OdnfqZn6udnSHZnZ2dnUVZ_vOdnZ2d at nmt.edu>, Bob Greschke wrote:
>> 
>>> I'd go even one step further.  Turn it into English (or your favorite
>>> non-computer language):
>>> 
>>> 1. While list, pop.
>>> 
>>> 2. While the length of the list is greater than 0, pop.
>>> 
>>> Which one makes more sense?  Guess which one I like.  CPU cycles be
>>> damned.
>>> :)
>> 
>> One of my rules is, always program like the language actually has a Boolean
>> type, even if it doesn't. That means, never assume that arbitrary values
>> can be interpreted as true or false, always put in an explicit comparison
>> if necessary so it's obvious the expression is a Boolean.
>
> You can do that, but it's not considered Pythonic. And it might be ineffective.
>
> Other than in PHP, Python has clear rules when an object of a builtin type
> is considered false (i.e. when it's empty). So why not take advantage of
> this?

Because it doesn't always do what I want.

I once had a producer consumer code. When the client asked whether new
items were available the function could return three different values

  1) a list with items, to be consumed
  2) an empty list (meaning there were no items available for the
                    moment but there could be in the future
  3) None (meaning the producer was done)

Just testing for the truth value of the returned result in order
to see whether the client should continue or not would often
have made the client exit prematurely.

IME such cases where testing for the truth value of an object
don't give the expected result, happen often enough to make me
carefully think about what I want to test for and then explicitly
do so.

-- 
Antoon Pardon




More information about the Python-list mailing list