Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'?

Duncan Booth duncan.booth at invalid.invalid
Wed Jan 23 04:30:28 EST 2008


Kristian Domke <news at neither-nor.net> wrote:

> foo = (not f and 1) or 0
> 
> In this case f may be None or a string.
> 
> If I am not wrong here, one could simply write
> 
> foo = not f
> 

Yes, it sounds pretty silly, and not just on the level you spotted.

The only difference between the two expressions is that the original sets 
foo to an integer whereas your version sets it to a bool. So the question 
of which is most appropriate actually comes down to what foo is being used 
for.

Is there really some code which requires a numeric value of 1 when f is 
None or an empty string and a value of 0 for any other string? I can't 
think offhand of any obvious situations where you would want that. My guess 
is that foo is being used later as a condition in an 'if' statement.

If you really do need an integer then in Python 2.5+ another way to write 
it would be:

    foo = 0 if f else 1

Also 'foo' is a silly name since it gives no indication at about the 
purpose of the expression, but I'm hoping that was just you paraphrasing 
the code you posted.

Ok, I just looked at the code, it is indeed being used as a boolean, so

  self.useProgressBar = not f
or
  self.useProgressBar = f is not None

if you want to be more specific about checking for None.



More information about the Python-list mailing list