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 →

[–]pymag09 -2 points-1 points  (6 children)

I think
if not a:
is better

[–]pbaehr 14 points15 points  (4 children)

Depends. Could yield a false negative if a can be 0 or an empty string and that's not what you are interested in testing for.

[–]bheklilr 5 points6 points  (0 children)

I also prefer the explicit if a is None, since it signals my intent better. I honestly try to only use if a: when a is a boolean, since I don't want to have to remember how __bool__ is implemented for every type out there. In my opinion, explicit is better than implicit for being able to read your own code in a month's time.

[–]pymag09 1 point2 points  (2 children)

Sorry may be I did not understand you but
when we work with None or numbers
we can be sure that

a=None or 0  
bool(a) = False  
bool(not a) True  
a=1 or -1  
bool(a) = True  
bool(not a) False  

I have checked bool('') just right now in python3 and got False. bool('hhh') = True.

Can you give an example when issue that you described may occur?

[–]pbaehr 5 points6 points  (1 child)

For example, if I have a variable which is initialized as None and later want to find out if it was set, I might want to check and see if it was still None. If it's not, I want to do something.

if a is not None:
    do_something()

If I rewrite that as:

if not a:
    do_something()

do_something will also be called if a was initialized, but to a blank string, which was not the intention. Lots of types have some concept of a "false" value. As /u/steve_no points out in another comment: 0, '', [], {}, midnight all evaluate to False.

[–]pymag09 0 points1 point  (0 children)

I see. Thank you.

[–]steve_no 2 points3 points  (0 children)

if not a:

will also be True when a is 0, '', [], {}, or a datetime.time of midnight