How does python know?

Chris Angelico rosuav at gmail.com
Wed Feb 12 21:33:40 CET 2014


On Thu, Feb 13, 2014 at 7:17 AM, Tobiah <toby at tobiah.org> wrote:
> 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?

No, it doesn't; but when you compile a module (including a simple
script like that), Python checks for repeated literals. It's only good
for literals, though.

If you specifically need this behaviour, it's called 'interning'. You
can ask Python to do this, or you can do it manually. But most of the
time, you can just ignore id() and simply let two strings be equal
based on their contents; the fact that constants are shared is a neat
optimization, nothing more.

ChrisA



More information about the Python-list mailing list