easy question on parsing python: "is not None"

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Aug 13 02:03:54 EDT 2010


On Thu, 12 Aug 2010 19:52:07 -0700, Matt Schinckel wrote:

>>>> a = "hello"
>>>> b = "hello"
>>>> a is b
> True
> 
> Ooh, that looks dangerous. Are they the same object?


You don't need another test to know that they are the same object. The 
`is` operator does exactly that: a is b *only* if a and b are the same 
object.


>>>> a += "o"
>>>> a
> 'helloo'
>>>> b
> 'hello'
> 
> Phew.

This tests for mutability, not sameness. If strings were mutable, then 
modifying a in place would likewise cause b to be modified (because they 
are the same object). Here's an example:

>>> a = b = [1, 2, 3]
>>> a is b
True
>>> a += [4]
>>> b
[1, 2, 3, 4]

But of course, if strings were mutable like lists, they wouldn't be 
cached! The consequences would be horrific if they were, unless Python's 
execution model were radically different. Copy-on-write perhaps?


> (Python does not make two copies of small strings until it needs to).

Python doesn't copy anything unless you ask it to.



-- 
Steven



More information about the Python-list mailing list