Possible Duplicate:
When is the `==` operator not equivalent to the `is` operator? (Python)
I am using Python 2.x.
My editor gives me a 'warning' underline when I compare my_var == None
, but no warning when I use my_var is None
.
I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that my_var is None
is preferred.
Is this the case, and if so, why?
Summary:
Use
is
when you want to check against an object's identity (e.g. checking to see ifvar
isNone
). Use==
when you want to check equality (e.g. Isvar
equal to3
?).Explanation:
You can have custom classes where
my_var == None
will returnTrue
e.g:
is
checks for object identity. There is only 1 objectNone
, so when you domy_var is None
, you're checking whether they actually are the same object (not just equivalent objects)In other words,
==
is a check for equivalence (which is defined from object to object) whereasis
checks for object identity:PEP 8 defines that it is better to use the
is
operator when comparing singletons.is
is generally preferred when comparing arbitrary objects to singletons likeNone
because it is faster and more predictable.is
always compares by object identity, whereas what==
will do depends on the exact type of the operands and even on their ordering.This recommendation is supported by PEP 8, which explicitly states that "comparisons to singletons like None should always be done with
is
oris not
, never the equality operators."