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

Gary Herron gherron at islandtraining.com
Wed Jan 23 04:06:39 EST 2008


Kristian Domke wrote:
> Hello to all
>
> I am trying to learn python at the moment studying an example program
> (cftp.py from the twisted framework, if you want to know)
>
> There I found a line
>
> 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
>
> because if f = None:
>
> (not f) = true,
> (true and 1) = true,
> (true or 0) = true
>
> or if f = 'bar'
>
> (not f) = false
> (false and 1) = false
> (false or 0) = false
>
> So why bothering with the longer version?
>   

Good catch!  It's my guess that you've found a way to improve on a bit
of carelessly written code.

However there *is* a (subtle) difference between
  not f
and
  (not f and 1) or 0 

The first produces a boolean value, and the second produces an int
value, but since one is a subclass of the other, you'd have to write
quite perverse code care about the difference.

Gary Herron
 
> I hope, I made clear, what I want...
>   
Quite.
> CU
>
> Kristian
>   




More information about the Python-list mailing list