is this a bug?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Aug 16 05:09:35 EDT 2001


Vassilis Virvilis <vasvir at iit.demokritos.gr> wrote in
news:3B7AF5AA.977B331C at iit.demokritos.gr: 

> I apologize if this has been brought to the attention of this group
> before. Maybe I did misunderstand the use of the 'is' operator, but
> then how it is supposed to work?

It checks whether two bindings refer to the same object. If 'is' returns 1 
then the objects are the same object, modifying one will affect both 
bindings. If 'is' returns 0 then you can modify one of the objects without 
affecting the other. This of course only really matters for mutable objects 
such as lists or dictionaries as you cannot modify immutable objects at 
all, therefore the compiler can optimise its use of immutable objects in a 
way that might sometimes surprise you. Try:

>>> a = 9
>>> b = 3
>>> c = a/b
>>> c is b, c==b
(1, 1)
>>> a = 90000
>>> b = 300
>>> c = a/b
>>> c is b, c==b
(0, 1)
>>>

So when might you actually want to use 'is'? The answer is not very often 
at all. Scanning the Python 2.1 libraries, almost every use of 'is' checks 
whether an object is, or is not, None. This is a safe alternative to '==' 
as there is only one None object. You can also use 'is' to safely check the 
type of an object. e.g. "if type(x) is types.IntType: dosomething()"
there are other sporadic uses: the copy module uses 'is' when deepcopying a 
tuple, and the difflib module uses 'is' as a quick way to optimise setting 
the sequence to be compared: if setting the sequence to the same sequence 
then it can ignore the call, but an equality comparison on this situation 
could be much too slow.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list