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

John Roth johnroth1 at gmail.com
Sun Apr 22 18:17:25 EDT 2012


On Sunday, April 22, 2012 1:43:36 PM UTC-6, John Nagle wrote:
> On 4/20/2012 9:34 PM, john.tantalo at gmail.com wrote:
> > On Friday, April 20, 2012 12:34:46 PM UTC-7, Rotwang wrote:
> >
> >> I believe it says somewhere in the Python docs that it's undefined and
> >> implementation-dependent whether two identical expressions have the same
> >> identity when the result of each is immutable
> 
>     Bad design.  Where "is" is ill-defined, it should raise ValueError.
> 
> A worse example, one which is very implementation-dependent:
> 
> http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers
> 
>  >>> a = 256
>  >>> b = 256
>  >>> a is b
> True           # this is an expected result
>  >>> a = 257
>  >>> b = 257
>  >>> a is b
> False
> 
> Operator "is" should be be an error between immutables
> unless one is a built-in constant.  ("True" and "False"
> should be made hard constants, like "None". You can't assign
> to None, but you can assign to True, usually with
> unwanted results.  It's not clear why True and False
> weren't locked down when None was.)
> 
> 				John Nagle

Three points. First, since there's no obvious way of telling whether an arbitrary user-created object is immutable, trying to make "is" fail in that case would be a major change to the language. Given the next point, I expect that a request to change Python to do it would be rejected immediately.

Second: the definition of "is" states that it determines whether two objects are the same object; this has nothing to do with mutability or immutability. It's an implementation detail whether an immutable object is implemented as a singleton. Some common cases (None, True, False and the empty tuple) are specified to be that in the language definition, but it's not specified for the general case.

The id([]) == id([]) thing is a place where cPython's implementation is showing through. It won't work that way in any implementation that uses garbage collection and object compaction. I think Jython does it that way, I'm not sure about either IronPython or PyPy.

Third: True and False are reserved names and cannot be assigned to in the 3.x series. They weren't locked down in the 2.x series when they were introduced because of backward compatibility.

John Roth



More information about the Python-list mailing list