4 ms·
A 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
by bobbyi_settv 9y ago
A 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.