How does python know?
davea at davea.name
Wed Feb 12 22:59:28 CET 2014
Tobiah <toby at tobiah.org> Wrote in message:
> On 02/12/2014 12:17 PM, Tobiah wrote:
>> I do this:
>> a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl'
>> b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl'
>> print id(a)
>> print id(b)
>> And get this:
>> This works for longer strings. Does python
>> compare a new string to every other string
>> I've made in order to determine whether it
>> needs to create a new object?
> Weird as well, is that in the interpreter,
> the introduction of punctuation appears to
> defeat the reuse of the object:
> >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
> >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
> >>> a is b
> >>> a = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
> >>> b = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
> >>> a is b
As others have said, interning is implementation specific, so you
should never rely on it.
I think the current CPython algorithm is designed to save both
memory and time in the storage and look up of symbol names. In a
typical program, those are the most likely to be duplicated. So
if your literal is of reasonable size and doesnât invalid symbol
characters (such as space, punctuation, etc) then it just might
be added to the interned dictionary.
More information about the Python-list