Gary Herron wrote: > Robert Kern wrote: >> On 2009-03-06 14:23, Gary Herron wrote: >>> Robert Kern wrote: >>>> On 2009-03-06 13:46, Gary Herron wrote: >>>>> Emanuele D'Arrigo wrote: >>>>>> Hi everybody, >>>>>> >>>>>> while testing a module today I stumbled on something that I can work >>>>>> around but I don't quite understand. >>>>> >>>>> *Do NOT use "is" to compare immutable types.* **Ever! ** >>>> >>>> Well, "foo is None" is actually recommended practice.... >>>> >>> >>> But since newbies are always falling into this trap, it is still a good >>> rule to say: >>> >>> Newbies: Never use "is" to compare immutable types. >>> >>> and then later point out, for those who have absorbed the first rule: >>> >>> Experts: Singleton immutable types *may* be compared with "is", >>> although normal equality with == works just as well. >> >> That's not really true. If my object overrides __eq__ in a funny way, >> "is None" is much safer. >> >> Use "is" when you really need to compare by object identity and not >> value. > > But that definition is the *source* of the trouble. It is *completely* > meaningless to newbies. Until one has experience in programming in > general and experience in Python in particular, the difference between > "object identity" and "value" is a mystery. > So in order to lead newbies away from this *very* common trap they often > fall into, it is still a valid rule to say > > Newbies: Never use "is" to compare immutable types. > I think this is addressing the wrong problem. I;d prefer to say
Newbies: never assume that the interpreter keeps just one copy of any value. Just because a == b that doesn't mean that a is b. *Sometimes* it will be, but it isn't usually guaranteed. > of even better > > Newbies: Never use "is" to compare anything. > > This will help them avoid traps, and won't hurt their use of the > language. If they get to a point that they need to contemplate using > "is", then almost be definition, they are not a newbie anymore, and the > rule is still valid. personally I believe newbies should be allowed the freedom to shoot themselves in the foot occasionally, and will happily explain the issues that arise when they do so. It's all good learning. I think using "is" to compare mutable objects is a difficult topic to explain, and I think your division of objects into mutable and immutable types is unhelpful and not to-the-point. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Want to know? Come to PyCon - soon! http://us.pycon.org/ -- http://mail.python.org/mailman/listinfo/python-list