What's the address for?

Ben Finney ben+python at benfinney.id.au
Mon Feb 18 20:33:07 EST 2019


"Avi Gross" <avigross at verizon.net> writes:

> I hear that [the ‘id(foo)’ return value] is implementation dependent.
> But are there any requirements on the implementation that allow it to
> have meaning?

The requirements are that `id(foo)` should satisfy the documented API
for that function <URL:https://docs.python.org/3/library/functions.html#id>:

     Return the “identity” of an object. This is an integer which is
     guaranteed to be unique and constant for this object during its
     lifetime. Two objects with non-overlapping lifetimes may have the
     same `id()` value.

> I mean is the ID guaranteed to be unique and not reused within a
> session?

No. The identity of an object is guaranteed to be unique only during the
lifetime of that object. This implies that *outside* the lifetime of
that object (before it exists; after it is destroyed) the same value
is allowed to be the identity of some other object.

> If two things concurrently show the same ID, are they the same in some
> way?

Yes, querying the identity of two references concurrently will return
the same identity value only if those two references refer to the same
object.

That is the essential meaning of an object identity: you can compare it
with some other identity value and see whether that came from the same
object.

Other than object identity, there is pretty much no guarantee (and hence
almost no purpose for the value you get from ‘id(foo)’). That is useful
enough, of course.

> On the implementation I am using, the ID changes if I do this:

You are creating new objects and binding the name ‘a’ to different
objects in succession. Those different objects will each have different
identities.

> It looks like the ID of "a" can change depending on its contents.

That's because a name is not a container, it is a reference. Names don't
know *anything* about the object; they have no type, no identity,
nothing except the ability to refer to some object at a particular point
in time.

> So I decided to do what maybe should be done first. Find some
> documentation!

Yes (especially the documentation of the function you're using, ‘id’).

Also helpful: Learn the actual behaviour of references in Python. They
do not behave like “variables” in some other languages (I avoid talking
about Python “variables” at all, for this reason). References are not
containers, and thinking of them that way will frequently lead you to
the wrong conclusion.

<URL:https://nedbatchelder.com/text/names1.html>

-- 
 \       “Theology is the effort to explain the unknowable in terms of |
  `\                         the not worth knowing.” —Henry L. Mencken |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list