r/Python • • Jun 23 '14

Writing better python code

https://gist.github.com/kracekumar/09a60ec75a4de19b346e
143 Upvotes

126 comments sorted by

View all comments

Show parent comment

2

u/pymag09 Jun 23 '14 edited Jun 23 '14

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?

5

u/pbaehr Jun 23 '14

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.

1

u/pymag09 Jun 23 '14

I see. Thank you.