Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

python - Difference between "if x" and "if x is not None"

It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?

I would assume the behavior should also be identical across Python implementations - but if there are subtle differences it would be great to know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the following cases:

test = False 
test = "" 
test = 0
test = 0.0 
test = []
test = () 
test = {} 
test = set()

the if test will differ:

if test: #False

if test is not None: #True 

This is the case because is tests for identity, meaning

test is not None

is equivalent to

id(test) == id(None) #False

therefore

(test is not None) is (id(test) != id(None)) #True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...