[Tutor] string immutability

Dave Angel d at davea.name
Mon Oct 24 21:33:52 CEST 2011


On 10/24/2011 03:21 PM, Johan Martinez wrote:
> On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger<
> andreas.perstinger at gmx.net>  wrote:
>
>> On 2011-10-24 20:04, Johan Martinez wrote:
>>
>>> Hi,
>>>
>>> I am struggling to understand Python string immutability. I am able to
>>> modify Python string object after initializing/assigning it a value.
>>>
>>>    s = "First"
>>>>>>   print s.__class__
>>>>>>
>>>>> <type 'str'>
>>>>   print s
>>>>> First
>>>>   s = "Second"
>>>>>>   print s
>>>>>>
>>>>> Second
>> Dave, Sander and Wayne have already explained why you aren't modifying
>> string objects in your example.
>> With the id()-function you can also see what is happening:
>>
>>>>> s = "First"
>>>>> id(s)
>> 3077110080L    # In CPython this is the memory address of the object
>>                # with the name 's' (in your case "First")
>>>>> s = "Second"
>>>>> id(s)
>> 3077110304L    # You see that 's' refers now to another address
>>>>> id("First")
>> 3077110080L    # But "First" is still on the same address as before
>>>>> id("Second")
>> 3077110304L    # And this proves that "Second" is at the address
>>                # which 's' refers to
>>
>> Bye, Andreas
>>
> Great, that's really helpful Andreas.
>
> thanks,
> jM.
>
Unfortunately, that trick is not guaranteed to work.  The only reason 
that id("First") gives the same value as  s="First"; id(s) is that 
"First" is one of the few magic values that get cached.  Small 
non-negative integers and short strings without spaces tend to be in 
that category, but you can't count on it.

Try
     a = 400
     b = 400
     print id(a), id(b)
   it'll probably print different numbers, if the value 400 isn't one of 
the "cached" values.


Worse is that an id() can be reused once an object is garbage 
collected.  So I could do something like:
     a = 600
     print id(a)
     del a
     b = 400
     print id(b)
     and it might print the same value.  There are more subtle cases, 
but I wanted to keep it simple.
An id() is guaranteed to be unique across all objects that exist at the 
same moment.  So as long as you're comparing id's of two objects that 
are both present, you're fine.

I'm afraid to really understand id(), you have to understand how the 
object model works, so you can't use id() to prove it.

-- 

DaveA



More information about the Tutor mailing list