not and is not problem
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon Jan 18 12:05:37 EST 2010
Steven D'Aprano wrote:
> 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?"
>>
> [snip]
> 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.
>
This is the most important point to understand. Some people use equality
where in fact they should test for identity, because of this 'cache'
effect Steven described that makes you feel that the 'is' operator is
not reliable.
>>>'seq' is 'seq'
True
>>>name = 'seq'
>>>name is 'seq'
True
>>>name, _ = 'seq _'.split()
>>>name is 'seq'
False
In your case, what you want is equality, because you don't care if name
and 'seq' are the same object in memory, there's a good chance they are
not in fact (see last example).
A simple example to illustrate the difference:
>>>class Foo:
>>> def __eq__(self, any):
>>> """Foo equals everything."
>>> return True
>>>f = Foo()
>>>f == None
True
>>>f is None
False
f equals None, but f is not None.
JM
More information about the Python-list
mailing list