conventions/requirements for 'is' vs '==', 'not vs '!=', etc

castironpi castironpi at gmail.com
Tue May 20 10:04:32 EDT 2008


On May 20, 5:04 am, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> John Salerno <johnj... at NOSPAMgmail.com> wrote:
> >>>> a = 'this is longer'
> >>>> b = 'this is longer'
> >>>> a == b
> > True
> >>>> a is b
> > False
>
> > In the above example, Python has created only one string called
> > 'hello' and both x and y reference it. However, 'this is longer' is
> > two completely different objects.
>
> That is true when run interactively, but the behaviour changes again if you
> run it as a script:
>
> C:\Temp>type t.py
> a = 'this is longer'
> b = 'this is longer'
> print a is b
>
> C:\Temp>t
> True
>
> In short, two equal strings may or may not be identical and any code which
> makes assumptions based on observed behaviour is broken. If you want to be
> able to test identity on strings safely then use the 'intern()' builtin to
> get repeatable behaviour.
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

Strictly speaking, identity is a real notion whereas equality is an
ideal (symbolic) notion.  There is no such thing as real true equals.
Furthermore, there are no true real symbols.  But, as puzzling as that
is:

'abc' == 'abc'
abc is abc

I argue that 'is' should never be used for primitives/literals.

a is 4  #bad
a is b  #good
a is 'abc' #bad
a is { None: None } #bad
a== { None: None } #good

Just good thing I don't have check-in priveleges, right? :)



More information about the Python-list mailing list