Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

As other commenters have pointed out, this is an implementation-specification optimization rather than a property of Python as a language.

It is, at a first glance, a bit weird. But the way you should look at it is that Python the language doesn't say the two integers have the same identity, and you shouldn't assume they will. But it also doesn't say they can't be the same object. Since Python integers are immutable, and thus having the two variables actually reference the same object can't create side effects unless you're directly playing with identities and making assumptions in your code that you shouldn't make, the implementation can have the two variables reference the same object as an optimization without breaking anything.



But this is using the seemingly harmless keyword "is" that's you're supposed to use sometimes. A programmer could stumble upon one of these statements and think it's going to work reliably after it works the first time.

I used to test for None by doing what seemed to work:

  if my_variable:
    do something
until I discovered it doesn't work if my_variable = 0 or some other falsy value besides None.


You could use '== None' instead, but it's generally recommended to use 'is None' (supposedly this is slightly faster). I don't think I've ever encountered anything else relying on 'is'. IMO the 'is' keyword was a poor language decision, given how rarely it's ever used.


I agree. 'is' creates opportunities for possibly counter-intuitive implementation dependency, for very little gain.


Yes, of course. I agree. Nothing I wrote contradicts that :-)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: