5 ms·
Is there any practical reason to use "is" to compare two ints (other than demonstrating integer interning)? Should doing so produce a warning?
by rcthompson 9y ago
Is there any practical reason to use "is" to compare two ints (other than demonstrating integer interning)? Should doing so produce a warning?
- yen223 9y agoI'll take it one step further - I don't think I've ever used `is` for anything other than comparisons to `None`.
- bobbyi_settv 9y agoIt's useful when you want a sentinel object and you don't want to use None as the sentinel because it is a valid value. Some discussion here: http://www.ianbicking.org/blog/2008/12/the-magic-sentinel.html http://www.ianbicking.org/blog/2008/12/the-magic-sentinel.ht...
- gvx 9y ago`is` is also useful for things like detecting cycles for walking object graphs. But I'd estimate 99% of the times I've used `is` was for comparisons to `None`, and 90% of the rest of times for comparisons to other sentinel values.
- DonaldPShimoda 9y agoOnly if you want to determine whether two integers are the same object and not just two objects that look similar. `is` is for identity, whereas `==` is for equivalence. Idiomatically, you generally only see `is` used for comparison to `None`. Sometimes developers want to check identity, and you'd use `is` there too (but I don't have a handy example offhand).
- bobbyi_settv 9y agoA lot of code relies on the fact that "is" is very fast because it just compares memory addresses. In order for it to give a warning when it is used on integers, it would need to also look at the types of the objects which would have have some performance impact. No, it is not good practice to rely on the interning of ints and short strings. It's implementation-specific behavior and relying on it can cause your code to not work on PyPy or even potentially a future version of CPython.
- rcthompson 9y agoI guess with MyPy type annotations, you could issue a warning when types are checked if the code is using "is" on types where doing so is implementation-defined and unlikely to produce a useful result.
- bobbyi_settv 9y agoI hadn't thought of that sort of static analysis. I would guess that the most common variation of using "is" on integers is comparing to a literal ("if x is 3"), so conceivably the bytecode compiler could warn about that without even needing annotations.
- cpsempek 9y agoYeah, this post is confusing. It reads as though I should expect `is` to be the same operator as `==`. But that's completely off. It's not that the integers are weird, it's that OP is misusing an operator. The topic could have been an explanation of what the `is` is, instead it's confusing and not helpful.
- DonHopkins 9y agoThat depends on what your definition of "is" is.
- cpburns2009 9y ago"is" is a well defined comparison operator in Python which compares object identity. Some philosophical argument about the meaning of "is" is tangential.