id( ) function question

Stephen Hansen apt.shansen at gmail.com
Wed Oct 14 19:24:59 EDT 2009


On Wed, Oct 14, 2009 at 1:37 PM, Laszlo Nagy <gandalf at shopzeus.com> wrote:
>
>  Andre Engels schrieb:
>>
>>>
>>> None, True, False, NotImplemented are guaranteed to be singletons, all
>> builtin types and exceptions can be considered as singletons, too.
>>
>>
> I thought that different mutable objects always have different ids. If this
> is not true, then what the id() function is used for? What useful thing can
> we do with it?
>

They do.

None, True, False, integers and strings are not mutable. The only time the
id is the "same" between two objects is if they are the identical two
objects.

CPython just (as a performance optimization) re-uses the same objects
sometimes even if people think they're using different objects.

In,
>>> a = 2
>>> b = 2

The id is the same, as they're the same integer object. Its not two separate
integer objects. Their ID will be the same, as they're precisely the same
object.

But,
>>> a = 1e100
>>> b = 1e100

Those are two separate objects, because Python's not re-using an existing
object the second time it sees 1e100.

Christian's point is, I believe, that this is all an implementation detail
to the CPython platform and not a language-defined feature. Other
implementations may do other things, so one should not rely on this
behavior. Basically, don't use "is" unless you really know what you're doing
-- or are testing verses a singleton :) "is" is never the right thing for
numbers. Usually. Ahem.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091014/39d981d8/attachment.html>


More information about the Python-list mailing list