|
> If ints act that way, shouldn't strings? `str' can be interned in some situations, though the rules vary across implementations and versions. Most of these things just boil down to unintuitive caching optimizations. Like you mention, it's pretty rare to check the object identity for integers or strings, but if you are doing so, you probably want the real answer. Aside Python's small integers, True, False, and None, Java has these rules for boxing in the specification [1]: > If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b. > Ideally, boxing a primitive value would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rule above is a pragmatic compromise, requiring that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, the rule disallows any assumptions about the identity of the boxed values on the programmer's part [1] http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#... |