Pattern: Comparison to literal
Issue: -
Used when comparing an object to a literal, which is usually what you do not want to do, since you can end up comparing to a different literal than what was expected altogether.
Also note that is
is for identity testing, ==
is for equality testing.
Example of incorrect code:
test_string = "ok"
if test_string is "ok": # Returns true
# do stuff
Both strings are actually stored in the same memory location, they have the same identity, so the is
operator works as expected. But if you construct a string by some other method (even if that string contains exactly the same characters), then the string may be equal, but it is not the same string - that is, it has a different identity, because it is stored in a different place in memory.
Example of correct code:
test_string = "ok"
if test_string == "ok":
# do stuff