not and is not problem

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jan 18 11:24:25 EST 2010


On Mon, 18 Jan 2010 16:43:25 +0100, superpollo wrote:

> hi:
> 
> #!/usr/bin/env python
> data = "seq=123"
> name , value = data.split("=")
> print name
> print value
> if not name == "seq":
>      print "DOES NOT PRINT OF COURSE..."
> if name is not "seq":
>      print "WTF! WHY DOES IT PRINT?"


`is` is not an alternative spelling for `==`. `is` tests for object 
identity, not equality. Unless you care about object identity, always use 
equals.

>>> 'seq 1' is 'seq 1'  # the SAME object is used twice
True
>>> s = "seq 1"  # TWO objects are used
>>> t = "seq 1"
>>> s is t
False


Beware: Python caches strings that look like identifiers. This will 
include "seq". So, purely as an implementation-specific detail, Python 
will sometimes re-use the same string object, and sometimes not.

Do not use `is` when you are testing for equality.

By the way, instead of 

    not name == "seq"

you should write

    name != "seq"


-- 
Steven



More information about the Python-list mailing list