why () is () and [] is [] work in other way?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Apr 21 23:14:39 EDT 2012


On Sat, 21 Apr 2012 15:02:00 +0200, Bernd Nawothnig wrote:

> On 2012-04-20, dmitrey wrote:
>> I have spent some time searching for a bug in my code, it was due to
>> different work of "is" with () and []:
>>>>> () is ()
>> True
> 
> You should better not rely on that result. I would consider it to be an
> implementation detail. I may be wrong, but would an implementation that
> results in
> 
> () is () ==> False
> 
> be correct or is the result True really demanded by the language
> specification?

It would be correct, and the result True absolutely is NOT demanded by 
the language. For example, Jython does not make that same optimization:

steve at runes:~$ jython
Jython 2.5.1+ (Release_2_5_1, Aug 4 2010, 07:18:19)
[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.6.0_18
Type "help", "copyright", "credits" or "license" for more information.
>>> () is ()
False


so code which relies on it is already broken.


Python the language makes no promises that literals will always evaluate 
to the same object. The ONLY such promises that it makes are that a small 
handful of special constants are singletons:

None
NotImplemented
True
False

and perhaps one or two others. Everything else is an accident of the 
implementation.

The CPython interpreter is especially aggressive in optimizing multiple 
literals in the same line. Compare this:

>>> x = 3.1; y = 3.1; x is y
True

with this:

>>> x = 3.1
>>> y = 3.1
>>> x is y
False


Again, this is an accident of implementation, and cannot be relied on.



-- 
Steven



More information about the Python-list mailing list