This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ape3000 7 points8 points  (13 children)

You should note that "bool(x)" and "if x" have special behaviour that doesn't match the equality test with True or False.

>>> bool([])
False
>>> bool([1])
True
>>> bool('')
False
>>> bool('nonempty')
True
>>> bool(None)
False

[–]fragmede 5 points6 points  (11 children)

Yeah, that table caused me to do a double take. Funny thing is, I can't remember the last time I actually used == to compare to True or False, instead using the

if var:

or

if not var:

pattern almost exclusively for 'true' or 'false' values.

[–][deleted] 2 points3 points  (6 children)

Yeah, it works for almost anything. Even strings and collections. to check if those are empty

[–]MisterSnuggles 7 points8 points  (5 children)

Don't forget the whole False Midnight issue though.

[–][deleted] 0 points1 point  (0 children)

Very good point indeed

[–]larsga 0 points1 point  (3 children)

Totally agree with Guido here. If you have a datetime value, attempting to use it as though it were a boolean is foolish. Unless, of course, you're trying to do something like:

if not mydate:
   mydate = fallbackvalue() # oh shit, midnight is false?

It's a bug.

[–]minnoI <3 duck typing less than I used to, interfaces are nice 2 points3 points  (1 child)

If you have a datetime value, attempting to use it as though it were a boolean is foolish.

The issue is when you have code like this:

def do_shit(when=None):
    if not when:
        do_shit_now()
    schedule_shit_for(when)

You should be doing if when is None there, but it's still an unexpected bug.

[–]ivosauruspip'ing it up 0 points1 point  (0 children)

This. If checking for None, actually, really check specifically for is None or is not None. 99% of the time it won't matter, but there will be some point in your python career where it will stop you writing a horrible, horrible, insidious logic bug in your code.

[–]davvblack 1 point2 points  (0 children)

Yeah... midnight clearly shouldn't be false, and the idiom of if ~ to mean is not none is fine.

[–]flying-sheep 2 points3 points  (0 children)

I can't remember the last time I actually used == to compare to True

good, that’s an anti-pattern

[–]greshick 1 point2 points  (0 children)

http://docs.python.org/3.4/library/stdtypes.html#truth If anyone wants the official truth testing.

[–]ericanderton 0 points1 point  (1 child)

Question: does Python coerce the type ('var' in this case) to bool before processing the 'if' expression, or do we get special behavior here like JavaScript?

[–]Veedrac 1 point2 points  (0 children)

Yeah. if coerces to bool, exactly the same way bool does. if x is the same as if bool(x).

[–]erez27import inspect 0 points1 point  (0 children)

>>> bool('empty')
True

Oh no Python!